• Uncategorized

About docker : Docker-compose-not-passing-environment-variable-to-container

Question Detail

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.

My docker-compose.yml file:

  build: .
  dockerfile: Dockerfile
    - DEMO_VAR

My Dockerfile:

FROM alpine
COPY docker-start.sh /
CMD ["/docker-start.sh"]

And the docker-start.sh file:

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
$ 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

So you can see that the variable DEMO_VAR is empty!

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?

Question Answer

I found a solution. Answering my own question…

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. Use sudo -E. Demo:

    $ export DEMO_VAR=aabbdd
    $ echo $DEMO_VAR
    $ sudo -E docker-compose up
    env-file-test_1  | DEMO_VAR Var Passed in: aabbdd
  2. Use sudo VAR=value:

    sudo DEMO_VAR=$DEMO_VAR docker-compose up
  3. Add environment variables to the sudoers file (https://stackoverflow.com/a/8636711)

  4. Use docker without sudo (https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo)

you should use ENV in your Dockerfile, and avoid export.

See the doc


You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.