TExcelTAD
Home › Docker Compose › Variables & Interpolation

Variables & Interpolation

A Compose file is a template. Wherever a value contains $VAR or ${VAR}, Compose replaces it with a variable's value before doing anything else. This is called interpolation, and it is how one file serves your laptop, CI and production: the image tag, the published port, the replica count or the log level come from the environment instead of being hard-coded.

text
 shell variables ─┐
                  ├─▶ interpolation ─▶ resolved model ─▶ validate ─▶ create containers
 .env / --env-file┘     ${TAG:-dev}       image: shop/api:1.4

Interpolation happens once, when Compose reads the file, on your machine. The container never sees ${…}; it only gets the final values. (Variables inside the container are the job of environment and env_file.)

Where the values come from

Compose looks up each variable in this order and uses the first hit:

  1. The shell environment of the docker compose command (TAG=1.5 docker compose up).
  2. The env file: .env in the project folder, or the file(s) passed with --env-file instead.
  3. Otherwise the variable is unset, and the syntax decides what happens.

In this course's examples the shell is empty, so values come from .env or from defaults.

compose · try it yourself
services:
  api:
    image: ${REGISTRY}/shop/api:${TAG}
    environment:
      DATABASE_URL: ${DATABASE_URL}
# --- .env
REGISTRY=registry.example.com
TAG=1.4
DB_USER=shop
DATABASE_URL=postgres://${DB_USER}@db/shop
name: demo
services:
  api:
    environment:
      DATABASE_URL: postgres://shop@db/shop
    image: registry.example.com/shop/api:1.4
    networks:
      default: null
networks:
  default:
    name: demo_default

The .env file can use interpolation itself: DATABASE_URL was built from DB_USER defined above it. DB_USER did not end up anywhere else; .env only provides values for the template.

The syntax

The rules are borrowed from the POSIX shell. The difference between the forms with and without a colon is whether an empty value counts as missing:

Syntax Unset Set but empty Set
${VAR} or $VAR "" + warning "" value
${VAR:-default} default default value
${VAR-default} default "" value
${VAR:?message} error error value
${VAR?message} error "" value
${VAR:+alt} "" "" alt
${VAR+alt} "" alt alt

Every row of the table, checked by Compose itself (EMPTY is set to an empty string, NOPE is unset):

compose · try it yourself
services:
  api:
    image: alpine:3.22
    environment:
      COLON_DEFAULT_EMPTY: ${EMPTY:-fallback}
      DEFAULT_EMPTY: ${EMPTY-fallback}
      COLON_DEFAULT_UNSET: ${NOPE:-fallback}
      DEFAULT_UNSET: ${NOPE-fallback}
      COLON_ALT_SET: ${DEBUG:+--verbose}
      COLON_ALT_EMPTY: ${EMPTY:+--verbose}
      ALT_EMPTY: ${EMPTY+--verbose}
      REQUIRED_EMPTY: ${EMPTY?must be defined}
      DB_ADDR: ${DB_HOST}:${DB_PORT:-5432}
      NESTED: ${PRIMARY:-${SECONDARY:-built-in}}
# --- .env
EMPTY=
DEBUG=1
DB_HOST=db
name: demo
services:
  api:
    environment:
      ALT_EMPTY: --verbose
      COLON_ALT_EMPTY: ""
      COLON_ALT_SET: --verbose
      COLON_DEFAULT_EMPTY: fallback
      COLON_DEFAULT_UNSET: fallback
      DB_ADDR: db:5432
      DEFAULT_EMPTY: ""
      DEFAULT_UNSET: fallback
      NESTED: built-in
      REQUIRED_EMPTY: ""
    image: alpine:3.22
    networks:
      default: null
networks:
  default:
    name: demo_default

${VAR:-…} is the one you'll use most: a sane default that a developer can override. Defaults can nest, as NESTED shows: try PRIMARY, then SECONDARY, then a literal.

Required variables

For values that have no sensible default, such as a release tag on a server or a password, make the variable required with :?. Compose stops with your message instead of starting something half-configured:

compose · try it yourself
services:
  api:
    image: shop/api:${TAG:?set TAG to the release you want to deploy}
error while interpolating services.api.image: required variable TAG is missing a value: set TAG to the release you want to deploy

With nothing after the ?, you still get an error, just a less helpful one:

compose · try it yourself
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD:?}
error while interpolating services.db.environment.POSTGRES_PASSWORD: required variable DB_PASSWORD is missing a value

Unset variables: a warning, not an error

A plain ${VAR} that isn't set becomes an empty string, and Compose prints a warning. This is how many broken deployments start: image: /shop/api: is not what anyone wanted.

compose · try it yourself
services:
  api:
    image: registry.example.com/shop/api:${TAG}
WARN[0000] The "TAG" variable is not set. Defaulting to a blank string.
name: demo
services:
  api:
    image: 'registry.example.com/shop/api:'
    networks:
      default: null
networks:
  default:
    name: demo_default

Warnings scroll by and are easy to miss. In CI, prefer :? for anything important.

Escaping a literal $

To put a real dollar sign in a value, write $. That matters for passwords, for shell commands that should expand a variable inside the container, and for things like htpasswd hashes. In config output a literal $ is shown escaped again, as $, so the output is itself a valid Compose file:

compose · try it yourself
services:
  worker:
    image: alpine:3.22
    environment:
      PRICE: "costs $5"
    command: sh -c 'echo "running as $USER in $PWD"'
name: demo
services:
  worker:
    command:
      - sh
      - -c
      - echo "running as $USER in $PWD"
    environment:
      PRICE: costs $5
    image: alpine:3.22
    networks:
      default: null
networks:
  default:
    name: demo_default

Forget the second $ and Compose tries to interpolate. An unknown $USER would turn into an empty string; a stray ${ is a syntax error:

compose · try it yourself
services:
  worker:
    image: alpine:3.22
    environment:
      TEMPLATE: ${BROKEN
invalid interpolation format for services.worker.environment.TEMPLATE.
You may need to escape any $ with another $.
${BROKEN

Choosing another env file

--env-file replaces .env; it is not added on top. Pass the flag several times to layer files, later files winning:

compose · try it yourself
# $ docker compose --env-file .env --env-file staging.env config
services:
  api:
    image: registry.example.com/shop/api:${TAG}
    environment:
      LOG_LEVEL: ${LOG_LEVEL}
# --- .env
TAG=1.4
LOG_LEVEL=info
# --- staging.env
TAG=2.0-rc1
name: demo
services:
  api:
    environment:
      LOG_LEVEL: info
    image: registry.example.com/shop/api:2.0-rc1
    networks:
      default: null
networks:
  default:
    name: demo_default

TAG came from staging.env, LOG_LEVEL from .env. Note that interpolation works only in values: keys such as service names can't be variables.

Inspecting variables

config --variables lists every variable the file uses, whether it's required, and its default or alternate value. It is a quick way to document what a project needs:

compose · try it yourself
# $ docker compose config --variables
services:
  api:
    image: ${REGISTRY:-docker.io}/shop/api:${TAG:?}
    ports:
      - "${API_PORT:-8000}:8000"
    environment:
      DEBUG_FLAGS: ${DEBUG:+--reload}
NAME                REQUIRED            DEFAULT VALUE       ALTERNATE VALUE
API_PORT            false               8000
DEBUG               false                                   --reload
REGISTRY            false               docker.io
TAG                 true

And config --no-interpolate shows the file with variables untouched, handy when you want the normalised form but not the secrets that interpolation would print.

A model of the resolver

The model implements the lookup order and the main syntax forms (no nesting), then resolves a few expressions against a shell and an env file. The shell wins over .env:

python · try it yourself
import re

PATTERN = re.compile(r"\$\$|\$\{(\w+)(?:(:?)([-?+])([^}]*))?\}|\$(\w+)")

def interpolate(text, shell, env_file, warnings):
    def lookup(name):
        if name in shell:
            return shell[name]
        return env_file.get(name)

    def replace(m):
        if m.group(0) == "$":
            return "
quot; name = m.group(1) or m.group(5) colon, op, arg = m.group(2), m.group(3), m.group(4) value = lookup(name) missing = value is None or (colon == ":" and value == "") if op == "-": return arg if missing else value if op == "?": if missing: raise ValueError(f"required variable {name} is missing a value: {arg}") return value if op == "+": return "" if missing else arg if value is None: warnings.append(f'The "{name}" variable is not set. Defaulting to a blank string.') return "" return value return PATTERN.sub(replace, text) shell = {"TAG": "1.5"} env_file = {"TAG": "1.4", "LOG_LEVEL": "", "REGISTRY": "registry.example.com"} for expr in ["${REGISTRY}/shop/api:${TAG}", "level=${LOG_LEVEL:-info}", "level=${LOG_LEVEL-info}", "cost $5", "port ${PORT}", "${PASSWORD:?no password}"]: warnings = [] try: print(f"{expr:30} -> {interpolate(expr, shell, env_file, warnings)!r}", *warnings) except ValueError as err: print(f"{expr:30} -> error: {err}")
${REGISTRY}/shop/api:${TAG}    -> 'registry.example.com/shop/api:1.5'
level=${LOG_LEVEL:-info}       -> 'level=info'
level=${LOG_LEVEL-info}        -> 'level='
cost $5                       -> 'cost $5'
port ${PORT}                   -> 'port ' The "PORT" variable is not set. Defaulting to a blank string.
${PASSWORD:?no password}       -> error: required variable PASSWORD is missing a value: no password

Learn more: Environment & env_file · Override Files & Merging · Stack variables in Swarm

Test yourself

.env contains LOG_LEVEL= (empty). What does ${LOG_LEVEL:-info} give?

  1. ""
  2. info
  3. An error
  4. A warning and ""

TAG=1.5 is set in the shell and TAG=1.4 is in .env. Which tag is used?

  1. 1.4
  2. 1.5
  3. Compose fails on the conflict
  4. The later one in the file

How do you pass a literal $HOME to a shell command inside the container?

  1. $HOME
  2. $HOME
  3. ${HOME}
  4. '$HOME' in single quotes