是否可以重用多个容器之间共享的环境变量以避免重复,如下例所示:
version: '2'
services:
db:
image: example/db
ports:
- "8443:8443"
container_name: db
hostname: db
environment:
- USER_NAME = admin
- USER_PASSWORD = admin
svc:
image: example/svc
depends_on:
- db
ports:
- "9443:9443"
container_name: svc
hostname: svc
environment:
- DB_URL = https://db:8443
- DB_USER_NAME = admin
- DB_USER_PASSWORD = admin
答案 0 :(得分:42)
extends
选项可能不错,但在3.x
撰写文件时为not supported。其他方法是:
Extension fields(撰写文件3.4 +)
如果您可以使用3.4+撰写文件,扩展字段可能是最佳选择:
<强>搬运工-compose.yml 强>
version: '3.4'
x-common-variables: &common-variables
VARIABLE: some_value
ANOTHER_VARIABLE: another_value
services:
some_service:
image: someimage
environment: *common-variables
another_service:
image: anotherimage
environment:
<<: *common-variables
NON_COMMON_VARIABLE: 'non_common_value'
env_file指令
<强>搬运工-compose.yml 强>
version: '3.2'
services:
some_service:
image: someimage
env_file:
- 'variables.env'
another_service:
image: anotherimage
env_file:
- 'variables.env'
<强> variables.env 强>
VARIABLE=some_value
ANOTHER_VARIABLE=another_value
.env file (或实际撰写环境中的变量)
.env文件中的变量可以在服务配置中引用:
<强>搬运工-compose.yml 强>
version: '3.2'
services:
some_service:
image: someimage
environment:
- VARIABLE
another_service:
image: anotherimage
environment:
- VARIABLE
- ANOTHER_VARIABLE
<强> .ENV 强>
VARIABLE=some_value
ANOTHER_VARIABLE=another_value
答案 1 :(得分:25)
您可以使用extends指令让多个容器从基础服务描述继承environment
配置。例如,将以下内容放在名为base.yml
的文件中:
version: '2'
services:
base:
environment:
DB_URL: https://db:8443
DB_USER_NAME: admin
DB_USER_PASSWORD: admin
然后在docker-compose.yml
:
version: '2'
services:
container1:
image: alpine
command: sh -c "env; sleep 900"
extends:
file: base.yml
service: base
container2:
image: alpine
command: sh -c "env; sleep 900"
extends:
file: base.yml
service: base
environment:
ANOTHERVAR: this is a test
然后在container1
内,你会看到:
DB_URL=https://db:8443
DB_USER_NAME=admin
DB_USER_PASSWORD=admin
在container2
内,你会看到:
DB_URL=https://db:8443
DB_USER_NAME=admin
DB_USER_PASSWORD=admin
ANOTHERVAR=this is a test
显然,您可以将extends
用于environment
指令之外的其他内容;这是使用docker-compose时避免重复的好方法。
答案 2 :(得分:4)
您可以在docker-compose文件中引用本地环境变量。假设您要做的是USER_NAME
与DB_USER_NAME
相同:
<强>搬运工-compose.yml 强>
version: '2'
services:
db:
image: example/db
ports:
- "8443:8443"
container_name: db
hostname: db
environment:
- USER_NAME = ${USERNAME}
- USER_PASSWORD = ${PASSWORD}
svc:
image: example/svc
depends_on:
- db
ports:
- "9443:9443"
container_name: svc
hostname: svc
environment:
- DB_URL = https://db:8443
- DB_USER_NAME = ${USERNAME}
- DB_USER_PASSWORD = ${PASSWORD}
然后,运行docker-compose,如:
$ USERNAME="admin" PASSWORD="admin" docker-compose up
或者,对于更持久的内容,并且更容易定期打字:
$ printf '%s\n%s\n' 'export USERNAME="admin"' 'export PASSWORD="admin"' >> ~/.bash_profile
$ source ~/.bash_profile
$ docker-compose up