How to set default environment variables for docker-compose services?

Viewed 91

Consider the example:

Dockerfile

FROM ubuntu

ENV var=hello

ENTRYPOINT ["printenv"]

This container has an environment variable with a default value, which I can override:

docker build -t exp .
docker run exp

...
var=hello
...

docker run -e var=lalala exp

...
var=lalala
...

I would like to have this optional overridability when I use the image with docker-compose. So far I tried the following three approaches:

Obligatory override - otherwise variable unset

docker-compose.yml

version: "3.1"

services:
  hello-teller:
    image: exp:latest
    environment:
      - var

result:

docker-compose up

var is not set, default value ignored.

env var=lala docker-compose up

var is overridden.

Cast in stone

docker-compose.yml

version: "3.1"

services:
  hello-teller:
    image: exp:latest
    environment:
      - var=lala

result:

docker-compose up

var is overridden to lala.

env var=huhu docker-compose up

var is still overridden to lala.

No effect

docker-compose.yml

version: "3.1"

services:
  hello-teller:
    image: exp:latest
    environment:
      - ${var:-lala}

result:

docker-compose up

var is not overridden.

env var=huhu docker-compose up

var is not overridden.

1 Answers

According to the documentation, this is possible with the 2.1 file format:

Both $VARIABLE and ${VARIABLE} syntax are supported. Additionally when using the 2.1 file format, it is possible to provide inline default values using typical shell syntax:

${VARIABLE:-default} evaluates to default if VARIABLE is unset or empty in the environment. ${VARIABLE-default} evaluates to default only if VARIABLE is unset in the environment.

So ${var:-lala} as you've shown in the question, is the way to go, but you appear to be missing the left side. The full line should be:

- var=${var:-lala}

I tested the syntax in my environment and it works. To use your example, I would override the variable in one of two ways:

1) Export the variable to the environment, e.g.

export var=happy
sudo -E docker-compose up

2) Pass the environment variable directly

var=kind sudo -E docker-compose up

Note that I use the -E option with sudo to preserve existing environment variables. This is very easy to forget if one has an alias like alias docker-compose='sudo docker-compose'.

One option is to fix that alias, or my personal preference: alias sudo='sudo -E'.

By the way, option 2 is my preference if running docker-compose over SSH.

Using the env file

Another option is to use an env file:

Values present in the environment at runtime always override those defined inside the .env file. Similarly, values passed via command-line arguments take precedence as well.

Related