Cheatsheet: Environment variables and precedence in Docker Compose

Photo by Adi Goldstein on Unsplash

Introduction

Docker compose evaluates inline variables in the docker-compose.yml file.

There are some ways to provide defaults or override these variables with interpolation.

I can never remember the various ways to do this so I'm writing this cheat sheet for myself!

Variable Interpolation

  1. ${VARIABLE:-default} evaluates to default if VARIABLE is unset or empty in the environment.
  2. ${VARIABLE-default} evaluates to default only if VARIABLE is unset in the environment.
  3. ${VARIABLE:?err} exits with an error message containing err if VARIABLE is unset or empty in the environment.
  4. ${VARIABLE?err} exits with an error message containing err if VARIABLE is unset in the environment.

Variable Precedence

The full list is available in the docs here: https://docs.docker.com/compose/environment-variables/envvars-precedence/

For the common use cases here are the variable precedence rules in docker compose.

  1. Using -e when running docker compose
  2. A shell variable
  3. A constant value in the environment section of docker compose
  4. The .env file