简体   繁体   English

在 docker-compose.yml 的 env_files 中使用系统环境变量

[英]Use system environment variables in env_files in docker-compose.yml

I have an env file called myenvfile.env which is wanted to be defined from a system environment variable.我有一个名为 myenvfile.env 的 env 文件,它想从系统环境变量中定义。

.env .env

SYSTEM_ENV_VAR=prefix

myenvfile.env myenvfile.env

MY_COMPOSED_ENV_VAR=${SYSTEM_ENV_VAR}_suffix

docker-compose.yml docker-compose.yml

version: '3.4'

services:
  myservice:
    env_file: 
      - env_files/myenvfile.env

But when I create container with docker-compose up -d , I look into the container environment variables, and MY_COMPOSED_ENV_VAR = "${SYSTEM_ENV_VAR}_suffix" instead of desired "prefix_suffix" .但是,当我使用docker-compose up -d创建容器时,我查看了容器环境变量,并且MY_COMPOSED_ENV_VAR = "${SYSTEM_ENV_VAR}_suffix"而不是所需的"prefix_suffix"

How can I achieve that?我怎样才能做到这一点? Thanks谢谢

Edit: More information编辑:更多信息

If I define SYSTEM_ENV_VAR in Jenkins job, for example, it works in Linux and Windows.例如,如果我在 Jenkins 作业中定义 SYSTEM_ENV_VAR,它在 Linux 和 Windows 中都有效。 But if I try to do it in a shell, it doesn't work in Windows.但是如果我尝试在 shell 中执行它,它在 Windows 中不起作用。

Try declaring SYSTEM_ENV_VAR before the docker-compose up command, something like:尝试在SYSTEM_ENV_VAR docker-compose up命令之前声明SYSTEM_ENV_VAR ,例如:

$ export SYSTEM_ENV_VAR=test
$ docker-compose up

You'll see that it'll expand correctly.您会看到它会正确展开。

This behaviour happens because the SYSTEM_ENV_VAR is expected to be declared previous to the docker-compose up command, as it'll not expand with environment variables that are declared in the container creation instant (the env_file key section, for example), only the ones that are already available when the docker-compose runs.发生这种情况是因为SYSTEM_ENV_VAR应该在SYSTEM_ENV_VAR docker-compose up命令之前声明,因为它不会使用在容器创建瞬间(例如env_file键部分)中声明的环境变量进行扩展,只有那些当docker-compose运行时已经可用。

That's why the Jenkins job works in this case.这就是 Jenkins 工作在这种情况下起作用的原因。

.env file is used only at docker compose start time by replacing $VARIABLE with values given in .env file. .env 文件仅在 docker compose 开始时使用,方法是将 $VARIABLE 替换为 .env 文件中给出的值。 So you cannot expect it to update contents of your myenvfile.env file.所以你不能指望它更新你的 myenvfile.env 文件的内容。 (check this ) (检查这个

Instead you should declare new environment variable inside docker-compose.yaml like:相反,您应该在 docker-compose.yaml 中声明新的环境变量,例如:

environment:
    - MY_COMPOSED_ENV_VAR=${SYSTEM_ENV_VAR}_suffix

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM