如何在docker compose中使用环境变量 [英] How to use environment variables in docker compose
问题描述
我希望能够在 docker-compose.yml 中使用 env 变量,并在 docker-compose up
时传入值.这是例子.
我今天使用基本的 docker run 命令执行此操作,该命令包含在我自己的脚本中.有没有办法通过 compose 实现它,而无需任何此类 bash 包装器?
代理:主机名:$ 主机名卷:-/mnt/data/logs/$hostname:/logs-/mnt/data/$hostname:/data
- 创建一个
template.yml
,这是你的docker-compose.yml
和环境变量. - 假设您的环境变量位于文件env.sh"中
- 将以下代码放入 sh 文件中并运行它.
<块引用>
源 env.sh;rm -rf docker-compose.yml;环境子<"template.yml" > "docker-compose.yml";
一个新文件 docker-compose.yml
将使用正确的环境变量值生成.
示例 template.yml 文件:
oracledb:图像:${ORACLE_DB_IMAGE}特权:真实cpuset:0"端口:- "${ORACLE_DB_PORT}:${ORACLE_DB_PORT}"命令:/bin/sh -c "chmod 777/tmp/start;/tmp/start"容器名称:${ORACLE_DB_CONTAINER_NAME}
示例 env.sh 文件:
#!/bin/bashexport ORACLE_DB_IMAGE=<图像名称>export ORACLE_DB_PORT=<要暴露的端口>导出 ORACLE_DB_CONTAINER_NAME=ORACLE_DB_SERVER
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
- 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";
A new file docker-compose.yml
will be generated with the correct values of environment variables.
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}
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 compose中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!