Docker & docker-compose 设置环境变量
Docker & docker-compose setting environment variables
这是 docker-compose.yml
文件的典型结构:
version: "3.7"
services:
serv1:
build: ./serv1
ports:
- 4040:40
env_file:
- ./docker.env
serv2:
build: ./serv2
ports:
- 3000:3000
env_file:
- ./docker.env
serv3:
build: ./serv3
ports:
- 5000:5000
env_file:
- ./docker.env
我已经在我想使用的 docker.env
文件中设置了一些环境变量,我有两个问题:
- 正在尝试使用主机上的端口,所以
serv1:
ports:
- "${SERV1_PORT}:40"
env_file:
- ./docker.env
...
serv2:
ports:
- "${SERV2_PORT}:40"
env_file:
- ./docker.env
但是当我构建时,我得到以下信息:
WARN[0000] The "SERV1_PORT" variable is not set. Defaulting to a blank string.
- 有没有一种方法可以通过只包含一次来在我的 docker-compose 上“全局”指定 env 文件,而不是在每个服务上都包含它?意思是这样的:
services:
serv1: ...
serv2: ...
...
env_file:
- ./docker.env # these variables to be accessible in all
env_file
设置了可用的环境变量 在容器 中可用,而不是在你的 docker-compose.yml
中可用。为此,您需要 .env
文件;阅读更多关于 Environment variables in docker compose.
Substitute environment variables in Compose files
It’s possible to use environment variables in your shell to populate
values inside a Compose file:
web:
image: "webapp:${TAG}"
If you have multiple environment
variables, you can substitute them by adding them to a default
environment variable file named .env or by providing a path to your
environment variables file using the --env-file command line option.
这是 docker-compose.yml
文件的典型结构:
version: "3.7"
services:
serv1:
build: ./serv1
ports:
- 4040:40
env_file:
- ./docker.env
serv2:
build: ./serv2
ports:
- 3000:3000
env_file:
- ./docker.env
serv3:
build: ./serv3
ports:
- 5000:5000
env_file:
- ./docker.env
我已经在我想使用的 docker.env
文件中设置了一些环境变量,我有两个问题:
- 正在尝试使用主机上的端口,所以
serv1:
ports:
- "${SERV1_PORT}:40"
env_file:
- ./docker.env
...
serv2:
ports:
- "${SERV2_PORT}:40"
env_file:
- ./docker.env
但是当我构建时,我得到以下信息:
WARN[0000] The "SERV1_PORT" variable is not set. Defaulting to a blank string.
- 有没有一种方法可以通过只包含一次来在我的 docker-compose 上“全局”指定 env 文件,而不是在每个服务上都包含它?意思是这样的:
services:
serv1: ...
serv2: ...
...
env_file:
- ./docker.env # these variables to be accessible in all
env_file
设置了可用的环境变量 在容器 中可用,而不是在你的 docker-compose.yml
中可用。为此,您需要 .env
文件;阅读更多关于 Environment variables in docker compose.
Substitute environment variables in Compose files
It’s possible to use environment variables in your shell to populate values inside a Compose file:
web: image: "webapp:${TAG}"
If you have multiple environment variables, you can substitute them by adding them to a default environment variable file named .env or by providing a path to your environment variables file using the --env-file command line option.