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 ifVARIABLE
is unset or empty in the environment.${VARIABLE-default}
evaluates to default only ifVARIABLE
is unset in the environment.${VARIABLE:?err}
exits with an error message containing err ifVARIABLE
is unset or empty in the environment.${VARIABLE?err}
exits with an error message containing err ifVARIABLE
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.
- Using
-e
when runningdocker compose
- A shell variable
- A constant value in the
environment
section of docker compose - The
.env
file