Docker-compose 不将环境变量传递给容器 [英] Docker-compose not passing environment variable to container

查看:48
本文介绍了Docker-compose 不将环境变量传递给容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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:

  1. 使用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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆