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.
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.
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.
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 registrybuild: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 caseimage:names the image thatbuild:produces.ports:publishes ports. Quote them: YAML can misread unquoted values like22:22as 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, sopgdatabecomes something likeshop_pgdata.
build:?Environment variables and .env
Two separate mechanisms use .env files, and mixing them up is common.
POSTGRES_PASSWORD=devpass- Interpolation. Compose automatically reads a
.envfile next tocompose.yamland substitutes${POSTGRES_PASSWORD}in the YAML before anything starts. You can set defaults (${PORT:-8000}) or require a value (${API_KEY:?set API_KEY}). 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 varKeep .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:
- Your shell environment (what
exportor your CI job set). - The
.envfile next tocompose.yaml, or the file you pass with--env-file. - 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:
docker compose run -e KEY=valueon the command line.environment:on the service (after interpolation).env_file:on the service.ENVin 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.
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.
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?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.
Compose creates the shop_default network and the pgdata volume, then starts the services with no dependencies: db and cache.
Run this simulation of the same startup. db needs three checks before it is healthy.
Press Run (⌘ Enter) to see what happens.depends_on: [db] with no healthcheck. The API sometimes crashes on docker compose up with connection refused, then works after a restart. Why?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:
| Field | What it does | Typical value |
|---|---|---|
interval | Time between checks once the container is running | 5s to 30s |
timeout | How long one check may take before it counts as a failure | 2s to 5s |
retries | Consecutive failures before the container is marked unhealthy | 3 to 10 |
start_period | A grace period after start: failures here do not count towards retries | longer 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:
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: 30sThe long form of depends_on has two more switches worth knowing:
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 enabledrestart: 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 goal to the command.
docker compose down -v to 'clean up'. What happens to the Postgres data in pgdata?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.
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.
services:
adminer:
image: adminer
ports: ["8080:8080"]
profiles: ["tools"]docker compose up -d # api, db, cachedocker compose --profile tools up -d # ...plus adminerSecrets 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.
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, withenvironment:, 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 withtarget:to put it where the app expects it. A config can also take inlinecontent: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.
environment: to a Compose secrets: entry. Which statement is true?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:
- The
-pflag. - The
COMPOSE_PROJECT_NAMEvariable (shell or.env). - The top-level
name:incompose.yaml. - 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:
name: billing
services:
db:
image: postgres:17Two 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.
~/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?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.
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-orphansEach 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-timeoutputs 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 -vin analways()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.
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.
- 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_healthyto 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.envfile. - 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.