在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
- 创建一个
template.yml
,这是你的docker-compose.yml
与环境变量。 - 假设你的环境变量是文件'env.sh'
- 将下面的代码放在sh文件中并运行。
- Create a
template.yml
, which is yourdocker-compose.yml
with environment variable. - Suppose your environment variables are in a file 'env.sh'
- 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