在Docker中如何使用环境变量编写 [英] How to use environment variables in docker compose

查看:181
本文介绍了在Docker中如何使用环境变量编写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在docker-compose.yml中使用env变量,并在docker-compose时传入值。
这是一个例子。我今天正在使用基本的docker运行命令,它是围绕我自己的脚本。
有没有办法通过compose实现它,没有任何这样的bash包装?

I would like to be able to use env variables inside docker-compose.yml, with values passed in at the time of docker-compose up. This is the example. I am doing this today with basic docker run command, which is wrapped around my own script. Is there a way to achieve it with compose, without any such bash wrappers?

proxy:
  hostname: $hostname
  volumes:
    - /mnt/data/logs/$hostname:/logs
    - /mnt/data/$hostname:/data


推荐答案


  1. 创建一个 template.yml ,这是你的 docker-compose.yml 与环境变量。

  2. 假设你的环境变量是文件'env.sh'

  3. 将下面的代码放在sh文件中并运行。

  1. Create a template.yml, which is your docker-compose.yml with environment variable.
  2. Suppose your environment variables are in a file 'env.sh'
  3. Put the below piece of code in a sh file and run it.




source env.sh;
rm -rf docker-compose.yml;
envsubst< template.yml>docker-compose.yml;

source env.sh; rm -rf docker-compose.yml; envsubst < "template.yml" > "docker-compose.yml";

一个新文件 docker-compose。将使用正确的环境变量值生成yml

示例template.yml文件:

Sample template.yml file:

oracledb:
        image: ${ORACLE_DB_IMAGE}
        privileged: true
        cpuset: "0"
        ports:
                - "${ORACLE_DB_PORT}:${ORACLE_DB_PORT}"
        command: /bin/sh -c "chmod 777 /tmp/start; /tmp/start"
        container_name: ${ORACLE_DB_CONTAINER_NAME}

示例env.sh文件:

Sample env.sh file:

#!/bin/bash 
export ORACLE_DB_IMAGE=<image-name> 
export ORACLE_DB_PORT=<port to be exposed> 
export ORACLE_DB_CONTAINER_NAME=ORACLE_DB_SERVER

这篇关于在Docker中如何使用环境变量编写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆