[英]Environment Variable is not going to container from docker-compose
I was trying to pass ENV_VAR
to a container, but it was not working. 我试图将ENV_VAR
传递给容器,但它无法正常工作。
version: '3.7'
services:
ubuntu:
image: ubuntu:latest
environment:
- ENV_VAR=teste
command: "echo ${ENV_VAR}"
The problem was solved using $$
instead of $
: 使用问题解决了$$
代替$
:
version: '3.7'
services:
ubuntu:
image: ubuntu:latest
environment:
- ENV_VAR=teste
command: '/bin/sh -c "echo $$ENV_VAR"'
But, I dont understand why I had to call sh
and I dont belive that a running app inside my image will be able to read this value. 但是,我不明白为什么我不得不打电话sh
,我不相信的时候,我的图像内运行的应用程序将能够读取该值。
Having a variable in your container at runtime and having this variable available on startup time in your docker-compose.yml
are different things. 在运行时在容器中有一个变量,并且在docker-compose.yml
中启动时可以使用这个变量是不同的事情。 Compose cannot substitute variables somewhere in the config file with variables from the file's environment
section – which you are trying to do in the command
part, but you would have to use an .env
file to make this work. Compose不能用配置文件中某处的变量替换文件environment
部分中的变量 - 您在command
部分尝试这样做,但是您必须使用.env
文件来完成这项工作。
Or, as you did, use the $$
syntax to prevent Compose to evaluate a variable , but let it do the invoked Shell in the container. 或者,正如您所做的那样,使用$$
语法来阻止Compose 评估变量 ,但让它在容器中执行被调用的Shell。
The variables in the environment
part are available to the container, though. 但是, environment
部分中的变量可用于容器。 You can check it with this minimal example: 您可以使用以下最小示例进行检查:
version: "3.7"
services:
foo:
image: ubuntu
container_name: ubuntu
environment:
- foo=bar
command: sleep 3
nico@tuxedo:~/StackOverflow$ docker-compose up -d && docker exec ubuntu /bin/sh -c "env | grep foo"
Starting ubuntu ... done
foo=bar
So your application inside the container should have no problem to get this variable. 因此,容器内的应用程序应该没有问题来获取此变量。
As to why exactly command: echo $$foo
doesn't work, I'm not entirely sure. 至于为什么完全command: echo $$foo
不起作用,我不完全确定。 I believe that if you use echo
as ENTRYPOINT
(because there is no other ENTRYPOINT
defined in the Dockerfile ), then there is no Shell when you start the container, because you overwrite the default /bin/bash
. 我相信,如果你使用的echo
作为ENTRYPOINT
(因为没有其他ENTRYPOINT
定义在Dockerfile ),那么有没有壳牌当您启动容器,因为你覆盖默认/bin/bash
。 echo
itself seems to be unable to read variables from the environment when there is no Shell "wrapped around it". 当没有Shell“缠绕它”时, echo
本身似乎无法从环境中读取变量。 Although the variables are clearly there (check this with commmand: env
and docker-compose up
), echo
doesn't know how to get them. 尽管变量显然存在(使用命令检查commmand: env
和docker-compose up
),但echo
不知道如何获取它们。
If someone has a good explanation for this, I'm very happy to read it. 如果有人对此有一个很好的解释,我很高兴看到它。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.