brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${VAR:?message} makes Compose stop when a variable is missing

Docker
~/tips/tip-docker-compose-required-var

services:

Stops Compose with your own error message when a needed variable is empty or missing.

An unset variable in a compose file does not make Compose fail. It quietly replaces it with an empty string and starts the container anyway.

Interpolation has three forms that fix this, and the strict one is a single character away from the sloppy one.

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
      POSTGRES_USER: ${DB_USER:-postgres}

${VAR:?error} aborts with your message when the variable is unset or empty. ${VAR:-default} falls back to a default. There is also ${VAR:+replacement}, which gives the replacement only when the variable is set.

A common use is a password or a domain that has no sensible default. Failing loudly at startup is better than a database that starts with an empty password and then refuses connections later. The error message is yours to write, so make it say what to fix and where, for example which file to edit.

The caveat is the colon. With it, an empty value counts as missing. Without it, as in ${VAR-default}, only an unset variable does, and an empty one is kept as is. That difference has bitten me and others. I use the colon form almost every time.

Further reading: Interpolation in Compose files, On this site: use docker compose exec -T when a script runs it, On this site: put optional services behind a Compose profile

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link