Cheatsheet: Environment variables and precedence in Docker Compose

Published on April 23, 2023

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
Darragh ORiordan

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia building and supporting happy teams that create high quality software for the web.

I also make tools for busy developers! Do you have a new M1 Mac to setup? Have you ever spent a week getting your dev environment just right?

My Universal DevShell tooling will save you 30+ hours of configuring your Windows or Mac dev environment with all the best, modern shell and dev tools.

Get DevShell here: ✨ https://usemiller.dev/dev-shell


Read more articles like this one...

List of article summaries

#engineering

How to add canonical meta tag in NextJs

It’s important to add a canonical meta tag to your pages to improve SEO or to avoid issues with query params in crawled pages.

You can easily add a canonical meta tag in NextJs by using the next/head component.

#engineering

Open Telemetry in NextJs and NestJs

I wrote about how to use open telemetry with NestJs and React previously.

I wanted to add open telemetry to my NextJs app that calls a NestJs backend. The paradigm of SSR preferred by NextJs is a bit different than the CSR paradigm of React.

I’ll describe the differences and how I added open telemetry to NextJs that propagates to other backend APIs.

#engineering

Comparing next start and next standalone with docker

I wrote about how to use nextjs with docker.

I wanted to compare using next standalone like in the article and just using next start.

#engineering

Force RSA key support for Azure DevOps Git SSH

If you’re using Azure DevOps Git SSH you have to use an RSA key. This is because Azure DevOps doesn…

Comments