Skip to content

Lesson 6 of 24Real apps

Docker Compose

Describe a multi-container app in one compose.yaml and start the whole stack with a single command.

26 min read0/7 questions

In the last lesson it took four long docker commands, carefully ordered, to run an API with Postgres and Redis. Nobody wants to type that every morning, and new teammates will get it wrong. Docker Compose puts the whole stack in one file so docker compose up starts everything, and it is how most teams run their local development environment.

One file for the whole stack

Compose reads a file called compose.yaml (older projects use docker-compose.yml, which still works). Each entry under services: becomes one container. Here is the stack from last lesson.

compose.yaml
services:
  api:
    build: ./api
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/app
      REDIS_URL: redis://cache:6379/0
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    restart: unless-stopped
 
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d app"]
      interval: 5s
      timeout: 3s
      retries: 10
 
  cache:
    image: redis:7-alpine
 
volumes:
  pgdata:

Compose v2 is built into the Docker CLI as docker compose (with a space). The old standalone docker-compose tool and the top-level version: key are both obsolete; you can leave version: out. Recent releases are numbered v5 rather than v2, but the file format and commands are the same, so a docker compose version that prints 5.x is nothing to worry about.

The building blocks

Walk through the file piece by piece.

compose.yaml
services:
  api:
    build: ./api            # build an image from ./api/Dockerfile
    ports:
      - "8000:8000"         # same HOST:CONTAINER rule as docker run -p
    environment:
      REDIS_URL: redis://cache:6379/0
 
  cache:
    image: redis:7-alpine   # use a prebuilt image from a registry
  • build: points at a folder with a Dockerfile. Compose builds the image for you. Use it for your code.
  • image: pulls a ready-made image. Use it for other people's software: Postgres, Redis, Nginx. A service can have both, in which case image: names the image that build: produces.
  • ports: publishes ports. Quote them: YAML can misread unquoted values like 22:22 as a number in base 60.
  • environment: sets variables in the container. The service names (db, cache) work as hostnames because Compose creates a network for the project and attaches every service to it.
  • The top-level volumes: section declares named volumes. Compose prefixes them with the project name, so pgdata becomes something like shop_pgdata.
Quick check
Your compose file needs your FastAPI code, Postgres, and Redis. Which services should use build:?
Need a nudge? A hint rules out a wrong answer.

Environment variables and .env

Two separate mechanisms use .env files, and mixing them up is common.

.env
POSTGRES_PASSWORD=devpass
  1. Interpolation. Compose automatically reads a .env file next to compose.yaml and substitutes ${POSTGRES_PASSWORD} in the YAML before anything starts. You can set defaults (${PORT:-8000}) or require a value (${API_KEY:?set API_KEY}).
  2. env_file: on a service loads every line of a file into that container's environment.
services:
  api:
    env_file: .env.api      # every KEY=value line becomes a container env var

Keep .env out of git and out of the image (it is already in your .dockerignore). Commit a .env.example with fake values instead.

Which value wins

Sooner or later a container starts with the wrong LOG_LEVEL and three people say "but I set it". They probably all did, in different places. Compose resolves values in two separate passes, and each pass has its own order.

Pass 1: interpolation. Before anything runs, Compose replaces every ${VAR} in the YAML. It looks in this order:

  1. Your shell environment (what export or your CI job set).
  2. The .env file next to compose.yaml, or the file you pass with --env-file.
  3. The default inside the expression, as in ${LOG_LEVEL:-debug}.

Pass 2: the container's environment. Several sources can put the same key into the container. The higher one wins:

  1. docker compose run -e KEY=value on the command line.
  2. environment: on the service (after interpolation).
  3. env_file: on the service.
  4. ENV in the image's Dockerfile.

Two consequences catch people out. First, a shell variable beats .env, so a stale export POSTGRES_PASSWORD=old from yesterday silently overrides the file you just edited. Second, the .env file does not go into any container by itself. It only feeds ${...} in the YAML. A key that exists in .env but is never referenced is invisible to your app.

Run this model of both passes. The shell has LOG_LEVEL=warn, and four other places disagree.

Pythonenv_wins.py
import re shell = {"LOG_LEVEL": "warn"} # exported in your terminaldot_env = {"LOG_LEVEL": "info", "TAG": "dev"} # .env next to compose.yamlenv_file = {"LOG_LEVEL": "error", "WORKERS": "4"} # env_file: .env.apiimage_env = {"LOG_LEVEL": "trace", "WORKERS": "1", "PORT": "8000"} # Dockerfile ENVenvironment = {"LOG_LEVEL": "${LOG_LEVEL:-debug}", "IMAGE": "api:${TAG}"} def interpolate(value: str) -> str: def sub(m: re.Match) -> str: name, default = m.group(1), m.group(3) if name in shell: return shell[name] if name in dot_env: return dot_env[name] return default or "" return re.sub(r"\$\{(\w+)(:-([^}]*))?\}", sub, value) final: dict[str, str] = {}for layer, source in [("image ENV", image_env), ("env_file", env_file), ("environment", {k: interpolate(v) for k, v in environment.items()})]: for key, value in source.items(): final[key] = value print(f"{layer:<12} sets {key}={value}") print("container sees:", final)print("TAG inside the container?", "TAG" in final)
Output
Press Run (⌘ Enter) to see what happens.

When you are not sure, stop guessing and ask. docker compose config prints the file after interpolation, and docker compose exec api env prints what the running process actually got.

Quick check
The Dockerfile has ENV LOG_LEVEL=trace. The service has env_file: .env.api containing LOG_LEVEL=error and environment: LOG_LEVEL: ${LOG_LEVEL:-debug}. The .env file says LOG_LEVEL=info and your shell has nothing set. What does the app see?
Need a nudge? A hint rules out a wrong answer.

Start order, done right

depends_on tells Compose to start one service after another. On its own, it only waits for the container to start, not for the program inside to be ready. Postgres takes a few seconds to accept connections, so an API that connects on boot can crash.

The fix is a healthcheck plus condition: service_healthy. Compose runs the healthcheck command repeatedly, and only starts api once pg_isready succeeds.

docker compose up
network: shop_defaultBrowser: localhost:8000Browserlocalhost:8000api: build: ./apiapibuild: ./apidb: postgres:17dbpostgres:17cache: redis:7-alpinecacheredis:7-alpinepgdata: named volumepgdatanamed volume8000:8000db:5432cache:6379data

Compose creates the shop_default network and the pgdata volume, then starts the services with no dependencies: db and cache.

1/5

Run this simulation of the same startup. db needs three checks before it is healthy.

Pythoncompose_up.py
services = { "db": {"deps": [], "checks_until_healthy": 3}, "cache": {"deps": [], "checks_until_healthy": 0}, "api": {"deps": ["db", "cache"], "checks_until_healthy": 0},}started: set[str] = set()healthy: set[str] = set() for tick in range(1, 7): for name, svc in services.items(): if name not in started and all(d in healthy for d in svc["deps"]): started.add(name) print(f"t={tick}: start {name}") elif name in started and name not in healthy: svc["checks_until_healthy"] -= 1 if name in started and svc["checks_until_healthy"] <= 0 and name not in healthy: healthy.add(name) print(f"t={tick}: {name} is healthy")
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Your compose file has depends_on: [db] with no healthcheck. The API sometimes crashes on docker compose up with connection refused, then works after a restart. Why?
Need a nudge? A hint rules out a wrong answer.

Healthchecks that hold up

A healthcheck is only as good as its command. pg_isready is a good one because it asks Postgres itself. A check that only proves the process exists (test: ["CMD", "true"]) makes service_healthy meaningless. For your own API, hit a cheap endpoint that touches what the app needs to serve, such as /healthz returning 200 once the database pool is up.

Four timing fields control the check:

FieldWhat it doesTypical value
intervalTime between checks once the container is running5s to 30s
timeoutHow long one check may take before it counts as a failure2s to 5s
retriesConsecutive failures before the container is marked unhealthy3 to 10
start_periodA grace period after start: failures here do not count towards retrieslonger than your slowest cold start

start_period is the one teams forget. An app that needs 40 seconds to warm up, checked every 5 seconds with 3 retries, is marked unhealthy after 15 seconds and never gets a chance. Newer engines also accept start_interval, a faster check rate used only during the start period, so a fast boot is noticed quickly without hammering the app later. Check the Compose file reference for your version.

Your image needs the tool the check calls. python:3.13-slim has no curl, so either install it, or write the check in the language you already have:

compose.yaml
services:
  api:
    build: ./api
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz', timeout=2)"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 30s

The long form of depends_on has two more switches worth knowing:

compose.yaml
services:
  api:
    depends_on:
      db:
        condition: service_healthy
        restart: true       # restart api when Compose restarts or recreates db
      mailpit:
        condition: service_started
        required: false     # start without it if the service is not enabled

restart: true fixes a quiet failure: you run docker compose restart db or change its image, and the API keeps a pool of dead connections until someone restarts it by hand. With restart: true, Compose restarts the dependent too. It only applies to restarts that Compose itself performs. If the engine restarts a crashed db because of its restart: policy, Compose is not involved and your app's own reconnect logic has to cope.

The third condition, service_completed_successfully, waits for a one-shot service such as a migration to exit with code 0. Compose for Local Development builds a full migration pattern around it, so it is not repeated here.

Everyday commands

docker compose up -d --build        # build what changed, start everything in the backgrounddocker compose ps                   # status and health of each servicedocker compose logs -f api          # follow one service's logsdocker compose exec db psql -U postgres -d app   # a shell or client in a running servicedocker compose run --rm api pytest  # one-off command in a fresh containerdocker compose restart apidocker compose down                 # stop and remove containers and the networkdocker compose down -v              # ...and DELETE named volumes (your database!)
Match the pairs0/5 matched

Match the goal to the command.

Choose an item, then its match on the other side.
Quick check
A teammate runs docker compose down -v to 'clean up'. What happens to the Postgres data in pgdata?
Need a nudge? A hint rules out a wrong answer.

Networks and profiles

By default every service joins one network, <project>_default. You can declare your own to separate tiers, exactly like the front and back example last lesson.

compose.yaml
services:
  web:
    build: ./web
    networks: [front]
  api:
    build: ./api
    networks: [front, back]
  db:
    image: postgres:17
    networks: [back]
 
networks:
  front:
  back:

Profiles let you keep optional services in the same file without starting them every time. A service with profiles: only starts when you ask for that profile.

compose.yaml
services:
  adminer:
    image: adminer
    ports: ["8080:8080"]
    profiles: ["tools"]
docker compose up -d                     # api, db, cachedocker compose --profile tools up -d     # ...plus adminer

Secrets and configs as files

Environment variables leak: docker inspect prints them, child processes inherit them, and crash reporters log them. Compose has two top-level sections that deliver data as files instead.

compose.yaml
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
  api:
    build: ./api
    secrets:
      - db_password
    configs:
      - source: api_settings
        target: /etc/api/settings.toml
 
secrets:
  db_password:
    file: ./secrets/db_password.txt   # gitignored
configs:
  api_settings:
    file: ./config/settings.toml      # committed
  • A secret appears inside the container at /run/secrets/<name>. Only services that list it get it. The source can be a file or, with environment:, a variable from the shell that runs Compose, which suits CI.
  • A config is the same mechanism for non-sensitive files. By default it mounts at /<name>; use the long form with target: to put it where the app expects it. A config can also take inline content: in the YAML.

Without Swarm, both are bind mounts of the source file. Permissions follow the host file, and options like uid, gid and mode may not be applied for file sources, so check the Compose reference before you rely on them. The value is still a plain file on your disk, so this is about keeping secrets out of inspect output and process environments, not about encryption.

The POSTGRES_PASSWORD_FILE trick works because the official Postgres image reads any *_FILE variable from a file. Container Security in Depth shows how to support the same convention in your own settings code, and Docker in Production covers build-time secrets, which are a separate build: secrets: setting.

Quick check
You move the database password from environment: to a Compose secrets: entry. Which statement is true?
Need a nudge? A hint rules out a wrong answer.

Project names and collisions

Every container, network and volume Compose creates carries labels such as com.docker.compose.project=shop and com.docker.compose.service=db. That is how docker compose down knows what to remove, and how up finds the containers it already made. The project name is the key to all of it. Compose picks the first of:

  1. The -p flag.
  2. The COMPOSE_PROJECT_NAME variable (shell or .env).
  3. The top-level name: in compose.yaml.
  4. The name of the folder that holds the first Compose file.

The folder default goes wrong in a way that looks like magic. You have ~/work/shop/backend and ~/work/billing/backend, both with a db service. Both projects are called backend. Run up in the second folder and Compose finds a container labelled backend and db, then recreates it with billing's config. Worse, it attaches billing's Postgres to the existing backend_pgdata volume, which holds shop's data. Billing's app now sees shop's tables.

The fix is a stable name: at the top of each file:

compose.yaml
name: billing
services:
  db:
    image: postgres:17

Two related traps:

  • container_name: pins a global name. It cannot be prefixed per project, so a second checkout fails with "name already in use", and you cannot run more than one replica. Leave it out unless a tool really needs a fixed name.
  • Host ports are not per project. Two projects with "5432:5432" still fight over the host port. Use a variable such as "${DB_PORT:-5432}:5432" so each checkout can pick its own.

When Compose warns about orphan containers, it found containers with your project label for services no longer in the file, often after a rename. docker compose down --remove-orphans or up --remove-orphans cleans them up.

Quick check
Two repos live in ~/a/api and ~/b/api. Each has a compose.yaml with a db service, no name:, and no container_name:. You run docker compose up -d in ~/a/api, then in ~/b/api. What happens?
Need a nudge? A hint rules out a wrong answer.

Compose in CI

The same file that runs your laptop can run integration tests in CI, provided the job waits properly and always cleans up. docker compose up --wait starts the stack detached and blocks until every service is running, and healthy where a healthcheck exists. If a service exits or turns unhealthy, the command fails, so the job fails at the right step with a clear reason instead of at the first test with connection refused.

.github/workflows/ci.yml (excerpt)
env:
  COMPOSE_PROJECT_NAME: ci-${{ github.run_id }}
steps:
  - uses: actions/checkout@v5
  - name: Start the stack
    run: docker compose up -d --build --wait --wait-timeout 120
  - name: Integration tests
    run: docker compose run --rm api pytest -m integration
  - name: Logs on failure
    if: failure()
    run: docker compose logs --no-color --tail 200
  - name: Tear down
    if: always()
    run: docker compose down -v --remove-orphans

Each line earns its place:

  • A unique project name per run stops parallel jobs on a shared self-hosted runner from adopting each other's containers.
  • --wait-timeout puts a ceiling on a stack that never becomes healthy, so the job fails in two minutes rather than hanging until the runner's limit.
  • Dumping logs on failure is the difference between a red build you can read and one you have to rerun with debugging.
  • down -v in an always() step removes volumes, so the next run starts with an empty database and tests stay independent.

One-shot services can trip --wait, because a container that exits can look like a failure. Recent Compose versions understand services that others wait on with service_completed_successfully, but if yours does not, pass the long-running services by name: docker compose up --wait api web.

Practice

Compose works out start order from depends_on. Implement that ordering yourself.

ChallengeMedium

Compose start order

In compose.yaml, depends_on says which services must start before another. Given a map of service name to the services it depends on, return the order Compose should start them in.

  • A service starts only after all of its dependencies have started.
  • When several services are ready at the same time, start them in alphabetical order (so the answer is unique).
  • If the dependencies form a cycle, return an empty list. (Compose refuses to start a cycle too.)
{ "web": ["api"], "api": ["db", "cache"], "db": [], "cache": [] }
→ ["cache", "db", "api", "web"]

Every dependency is also a key in the map.

def start_order(services: dict[str, list[str]]) -> list[str]: # Count how many unmet dependencies each service has. pass
Key terms
compose.yaml
The file that declares services, networks, and volumes for a multi-container app.
service
One entry under services:. Compose runs one (or more) containers for it.
depends_on
Start ordering between services. Add condition: service_healthy to wait for readiness.
healthcheck
A command Docker runs repeatedly to decide whether a container is healthy.
interpolation
Compose replacing ${VAR} in the YAML using the shell environment or a .env file.
profile
A label that keeps optional services from starting unless you ask with --profile.
project name
The prefix and label Compose uses to group a stack's containers, networks, and volumes. Set it with name: or -p.
Compose secret
A file mounted at /run/secrets/<name> in only the services that list it, keeping values out of env vars.
start_period
A healthcheck grace period after start when failures do not count towards retries.