Cheatsheet: Environment variables and precedence in Docker Compose

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
${VARIABLE:-default}evaluates to default ifVARIABLEis unset or empty in the environment.${VARIABLE-default}evaluates to default only ifVARIABLEis unset in the environment.${VARIABLE:?err}exits with an error message containing err ifVARIABLEis unset or empty in the environment.${VARIABLE?err}exits with an error message containing err ifVARIABLEis 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.
- Using
-ewhen runningdocker compose - A shell variable
- A constant value in the
environmentsection of docker compose - The
.envfile