Docker-compose不将环境变量传递给容器 [英] Docker-compose not passing environment variable to container
问题描述
我正在使用Docker 17.04.0-ce,使用docker-compose 1.12.0构建4845c56,在Ubuntu 16.04.2 LTS上构建b31ff33.我只想传递一个环境变量,并从运行在容器中的脚本中显示它.我正在根据文档 https://docs.docker.com/compose执行此操作/compose-file/#environment .问题在于该变量未传递到容器.
I am using Docker 17.04.0-ce, build 4845c56 with docker-compose 1.12.0, build b31ff33 on Ubuntu 16.04.2 LTS. I simply want to pass an environment variable and display it from my script running in a container. I am doing this according to the documentation https://docs.docker.com/compose/compose-file/#environment . The problem is that the variable is not passed to the container.
我的docker-compose.yml文件:
My docker-compose.yml file:
env-file-test:
build: .
dockerfile: Dockerfile
environment:
- DEMO_VAR
我的Dockerfile:
My Dockerfile:
FROM alpine
COPY docker-start.sh /
CMD ["/docker-start.sh"]
和 docker-start.sh
文件:
#!/bin/sh
echo "DEMO_VAR Var Passed in: $DEMO_VAR"
我尝试在当前的终端会话中设置变量并将其传递给容器:
I try to set the variable in my current terminal session and pass it to the container:
$ export DEMO_VAR=aabbdd
$ echo $DEMO_VAR
aabbdd
$ sudo docker-compose up
Starting envfiletest_env-file-test_1
Attaching to envfiletest_env-file-test_1
env-file-test_1 | DEMO_VAR Var Passed in:
envfiletest_env-file-test_1 exited with code 0
因此您可以看到变量DEMO_VAR为空!
So you can see that the variable DEMO_VAR is empty!
我还尝试像这样在docker-compose.yml中使用变量: DEMO_VAR = $ {DEMO_VAR}
,但是当我运行 sudo docker-compose up
时,我得到了警告:警告:未设置DEMO_VAR变量.默认为空字符串."
I also tried using variables in docker-compose.yml like this: DEMO_VAR=${DEMO_VAR}
but then when I run sudo docker-compose up
, I get a warning: "WARNING: The DEMO_VAR variable is not set. Defaulting to a blank string.".
我做错了什么?我应该怎么做才能将变量传递给容器?
What am I doing wrong? What should I do to pass the variable to the container?
推荐答案
我找到了解决方案.回答我自己的问题...
I found a solution. Answering my own question...
问题出在 sudo
命令上.事实证明,默认情况下它不传递环境变量.有一些可能的解决方案:
The problem was with the sudo
command. It turned out that it does not pass environment variables by default. There are some possible solutions:
-
使用
sudo -E
.演示:
$ export DEMO_VAR=aabbdd
$ echo $DEMO_VAR
aabbdd
$ sudo -E docker-compose up
env-file-test_1 | DEMO_VAR Var Passed in: aabbdd
使用 sudo VAR = value
:
sudo DEMO_VAR=$DEMO_VAR docker-compose up
将环境变量添加到sudoers文件( https://stackoverflow.com/a/8636711 )
使用不带sudo的docker( https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo )
Use docker without sudo (https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo)
这篇关于Docker-compose不将环境变量传递给容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!