Home > database >  How to pass an existing environment variable in a Docker container
How to pass an existing environment variable in a Docker container

Time:10-20

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.

CodePudding user response:

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.
...
  • Related