0

Assuming the host machine has the TESTVARIABLE set

user@hostmachine> echo $TESTVARIABLE
test_value

How can you pass this variable to a container with docker-compose, using an .envfile or the docker-compose.yml file?

Most answers I find, involve explicitly defining that value in an .envfile, or directly in the docker-compose.yml, or in the command line when executing the up command`. However, I am looking to pass an existing variable on the host machine to the container.

1 Answer 1

1

First, make sure that TESTVARIABLE is actually exported to your environment and isn't just a shell variable:

export TESTVARIABLE

Then you can simply refer to it in your docker-compose.yaml like this:

version: "3"

services:
  example:
    image: docker.io/alpine:latest
    command:
      - sleep
      - inf
    environment:
      - "TESTVARIABLE=${TESTVARIABLE}"

If I run:

$ export TESTVARIABLE=foo
$ docker-compose up -d
$ docker-compose exec example env

I will get output like this:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=68705fc07b09
TERM=xterm
TESTVARIABLE=foo
HOME=/root

There you can see the value of TESTVARIABLE from the local environment.


Note that if TESTVARIABLE is not defined in your environment, docker-compose will warn you:

$ docker-compose up
WARNING: The TESTVARIABLE variable is not set. Defaulting to a blank string.
...
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Indeed the variable was not exported to the environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.