So far in this series we have a container that is not a tiny VM, and an image we built ourselves. Both of those dealt with one container at a time, which is fine right up until you need a real application.
A real application is a web server, a database, probably a cache, possibly a reverse proxy. Each needs to find the others, keep its data between restarts, and come up in roughly the right order. You can absolutely do that with docker run — a network to create, a couple of volumes, four commands with eleven flags each, and a shell-history entry you will never find again. Do it twice and you will get it subtly wrong the second time.
Compose replaces all of it with one file that you keep in version control.
One file, one stack
Here is a complete stack: a database, a web application, persistent storage for both. This is roughly the shape of the thing serving you this page.
name: blog
services:
db:
image: mariadb:11.4
restart: unless-stopped
environment:
MARIADB_DATABASE: wordpress
MARIADB_USER: wordpress
MARIADB_PASSWORD: ${DB_PASSWORD}
MARIADB_RANDOM_ROOT_PASSWORD: "yes"
volumes:
- db-data:/var/lib/mysql
web:
image: wordpress:6.9-apache
restart: unless-stopped
depends_on:
- db
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_NAME: wordpress
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: ${DB_PASSWORD}
volumes:
- site-data:/var/www/html
ports:
- "127.0.0.1:8080:80"
volumes:
db-data:
site-data:
Thirty lines, and docker compose up -d turns them into two running containers, a private network, and two volumes. Delete the containers and run it again and you get the same stack back, because the file is the description. That is the entire pitch.
Three top-level keys do the work. services are the containers. volumes declares storage that outlives them. A networks key exists too, and you usually do not need it — Compose creates a network for the project automatically and puts every service on it.
There is no version: key any more
Every Compose example written before about 2020 starts with version: "3.8". That field is obsolete — modern Compose ignores it and will warn you about it. If you are copying an example off the internet and it leads with a version number, assume the rest of it is aged too. The file is also conventionally compose.yaml now, though docker-compose.yml still works and will for a long while.
Service names are hostnames
Look at the database host in that file: WORDPRESS_DB_HOST: db:3306. Not an IP address. Not localhost. Just db — the name of the service.
Compose runs a DNS resolver on the project network, and every service is resolvable there by its own name. Containers are given an address when they start and a different one when they come back, so anything written down in advance is wrong by the next restart. The name is the stable part.
$ docker compose exec web sh
# getent hosts db
172.19.0.2 db
# nc -z db 3306 && echo reachable
reachable
# getent hosts google.com
# ... also works: the project network has outbound access
This is also why “what IP did my container get?” is almost always the wrong question. If you are reaching for docker inspect to find an address so one container can talk to another, you want the service name instead.
Volumes: the part that must outlive everything
We covered why a container’s own filesystem is disposable in the first post. Compose is where you write down what is not. Two forms turn up:
- Named volumes —
db-data:/var/lib/mysql. Docker manages the storage; you refer to it by name and do not care where it lives. Right for databases and application state. - Bind mounts —
./site:/var/www/html. A specific directory on the host, mounted in. Right for configuration you edit, and for development where you want your editor and the container looking at the same files.
The rule of thumb: if a human needs to open it, bind-mount it; if only the application touches it, use a named volume. And either way, a volume is not a backup. It is one rm away from gone, and it lives on the same disk as everything else.
down removes containers. down -v removes your data.
docker compose down stops and deletes the containers and the network, and leaves the named volumes completely alone — run up -d again and your database is exactly where you left it. docker compose down -v adds the volumes to the list of things being deleted. It does not ask twice, there is no undo, and the flag is one keystroke. If you only ever remember one thing from this post, remember which of those two you just typed.
depends_on is not a readiness check
Now the one that catches everybody, and keeps catching them because the symptom looks like a flaky application rather than a configuration mistake.
depends_on: [db] reads like “start the web container once the database is ready”. It does not mean that. It means “start the database container first” — and Compose considers that obligation discharged the instant the container is running. A database that has just been handed a brand-new volume will spend the next several seconds creating system tables and accepting precisely nothing.
depends_on guarantees only that the database container was started before the application container — not that anything inside it is listening yet. A restart policy papers over the gap by retrying; a healthcheck with condition: service_healthy closes it.There are two ways out, and they are not equivalent. The lazy one is a restart policy: the web container dies, Docker starts it again, and by the third or fourth attempt the database is listening. It works, it is what restart: unless-stopped is quietly doing in the file above, and it means your logs open with a handful of crashes every time you deploy.
The honest one is to tell Compose what “ready” actually means, with a healthcheck — a command run inside the container, on an interval, whose exit status defines health. Then depend on the condition rather than the container:
db:
# ... as before ...
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 12
start_period: 30s # grace while a fresh volume initialises
web:
# ... as before ...
depends_on:
db:
condition: service_healthy
Now up -d genuinely waits, docker compose ps shows a healthy column you can trust, and the web container’s first connection attempt is also its last. The healthcheck command is image-specific — the MariaDB images ship healthcheck.sh, Postgres has pg_isready, and for your own application it is usually curl -fsS localhost:8080/healthz against an endpoint you wrote. Which, as a side effect, forces you to define what healthy means. That is not a bad thing to be forced into.
Make the check exercise the dependency
A healthcheck that returns 200 from a static route proves the web server is up and nothing else. If the endpoint does not touch the database, the container reports healthy with a dead database behind it — and now your orchestrator is confidently routing traffic at it. Have the check do the smallest real piece of work the service exists to do.
Configuration, and keeping secrets out of the file
Notice that no password appears in compose.yaml — just ${DB_PASSWORD}. Compose interpolates that from the environment, and from a .env file sitting next to the compose file, which it reads automatically.
DB_PASSWORD=a-long-random-string-from-a-password-manager
So compose.yaml is safe to commit and .env is not. Put it in .gitignore on the same day you create it, not later, and commit a .env.example with the keys and no values so the next person knows what to fill in. The same discipline as keeping secrets out of image layers, and for the same reason: once it is committed it is published, and deleting it later does not unpublish it.
Two refinements worth knowing. ${DB_PASSWORD:?set DB_PASSWORD in .env} makes Compose refuse to start with that message instead of silently handing your database an empty password. And env_file: on a service points at a different file entirely, which is handy when one stack has several services with separate credentials.
Restart policies
Four values, and the difference between two of them matters more than it looks.
| Policy | What it does |
|---|---|
no | The default. It dies, it stays dead. |
on-failure | Restart only on a non-zero exit. Right for a job that is supposed to finish. |
always | Restart whenever it stops — including after you stopped it deliberately, once the daemon next starts. |
unless-stopped | Like always, except a container you stopped by hand stays stopped across a reboot. |
unless-stopped is the right default for anything long-running. The distinction bites when you stop a service to investigate something, reboot the host hours later, and always cheerfully brings back the thing you had deliberately taken out of service.
The commands you will actually use
All of these are run from the directory holding the compose file, and all of them act on the whole project unless you name a service.
| Command | What it does |
|---|---|
docker compose up -d | Create and start everything, detached. Re-running it reconciles: only what changed is recreated. |
docker compose ps | What is running, and the health column. |
docker compose logs -f web | Follow one service’s logs. Drop the name for all of them, interleaved and colour-coded. |
docker compose exec web bash | A shell inside a running service. run starts a throwaway container instead — a common mix-up. |
docker compose pull && docker compose up -d | The upgrade. Fetch newer images, then recreate whatever moved. |
docker compose config | Print the fully resolved file with every variable interpolated. The first thing to run when something is not picking up a value. |
docker compose down | Stop and remove containers and the network. Volumes survive. |
docker compose down -v | The above, and delete the named volumes. The data-losing one. |
docker compose config deserves the attention. Nearly every “why is this variable empty” problem is answered by it in one line, because it shows you the file Compose is actually acting on rather than the one you think you wrote.
The one-sentence version
Compose is one file that describes a whole stack: services become containers on a shared network where each is reachable by its service name, volumes hold the state that has to survive them, and the file lives in version control while the secrets live in a .env beside it that does not. Order startup with depends_on, but only a healthcheck knows anything about readiness — and check the flag before you press return on down.
Next in this series, the one I have been deferring since the firewall post: Docker publishes a port by writing its own netfilter rules, which means ufw deny can be sitting there looking authoritative while your database is answering the whole internet. Worth its own post, and it is coming. A combined Docker and Compose cheatsheet will land in the Field Reference alongside it.
