Environment Variable is not going to container from docker-compose

Viewed 105

I was trying to pass ENV_VAR to a container, but it was not working.

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.

1 Answers

Having a variable in your container at runtime and having this variable available on startup time in your docker-compose.yml are different things. 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.

Or, as you did, use the $$ syntax to prevent Compose to evaluate a variable, but let it do the invoked Shell in the container.

The variables in the environment part are available to the container, though. You can check it with this minimal example:

  • docker-compose.yml
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. 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 itself seems to be unable to read variables from the environment when there is no Shell "wrapped around it". Although the variables are clearly there (check this with commmand: env and docker-compose up), echo doesn't know how to get them.

If someone has a good explanation for this, I'm very happy to read it. :)

Related