How to Set a Default Environment Variable in docker-compose.yml


In Docker Compose, we can access environment variables using this notation: ${SECRET_KEY}.

For instance, our compose file might look something like this:

version: '3.1'
services:
  load_balancer:
    image: nginx:latest
    environment:
      SECRET_KEY: "${SECRET_KEY}"

Our docker-compose.yml will obtain variable values from the shell environment in which docker-compose is run. In this scenario, SECRET_KEY is likely set in our .env.

But, what if SECRET_KEY isn’t defined and we’d like a fallback value to be used as a default?

Shell Parameter Expansion

This notation is called shell parameter expansion.

The expression ${SECRET_KEY} will attempt to access SECRET_KEY as a Bash shell variable.

We can use the following syntax to provide a default value.

${SECRET_KEY:-defaultValue}

If SECRET_KEY is not set or is null, defaultValue will be used.

version: '3.1'
services:
  load_balancer:
    image: nginx:latest
    environment:
      SECRET_KEY: "${SECRET_KEY:-default_secret_key}"