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

Hey! Are you a developer?

🚀 Set Up Your Dev Environment in Minutes, Not Hours!

Tired of spending hours setting up a new development machine? I used to be, too—until I automated the entire process!

Now, I just run a single script, grab a coffee, and let my setup take care of itself.

Save 30+ hours configuring a new Mac or Windows (WSL) development environment.
Ensure consistency across all your machines.
Eliminate tedious setup and get coding faster!
Get Instant Access →