在docker-compose.yml中重用环境变量 [英] Re-using environment variables in docker-compose.yml
问题描述
是否可以重用在多个容器之间共享的环境变量?
Is it possible to re-use environment variables that are shared among multiple containers?
该想法是避免重复,如本例所示:
The idea is to avoid duplication, as illustrated in this example:
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
推荐答案
扩展
选项可能不错,但它在<$ c中是不支持 $ c> 3.x 组成文件。其他可行的方法是:
The extends
option can be nice but it's not supported in 3.x
compose files. Other ways to go are:
-
扩展名字段(组成文件3.4 +)
Extension fields (compose file 3.4+)
如果可以使用3.4+组成文件,则扩展名字段可能是最佳选择:
If you can use 3.4+ compose files, extension fields are probably the best option:
docker-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 指令
docker-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 中的noreferrer>文件(或实际撰写环境中的变量)
.env file in project root (or variables at actual compose environment)
.env文件中的变量可以在服务配置中引用:
Variables from .env file can be referenced in service configuration:
docker-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
这篇关于在docker-compose.yml中重用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!