Docker Compose — DevOps

With Docker Compose, you write every service (a container that Compose runs: app, db, redis) in docker-compose.yml, then start them with one command. docker…

You run docker compose up, three containers start, and the app dies right away. You run it again without changing a thing, and this time it works. A bug that sometimes appears and sometimes doesn't, like this one, is the most frustrating kind.

Docker Compose runs several containers at once from one YAML file (a text format for settings that uses indentation). In Compose, each container is called a service. A service here is not the systemd service from the Systemd & Service Management lesson, though the idea is similar: a program that keeps running. One command, docker compose up, starts them all with the same settings every time. Picture an orchestra's score. Every player, their instrument, and who comes in after whom are written on one sheet, and the conductor gives one cue. In Compose, the sheet is the YAML file, the players are the services, and the conductor's cue is docker compose up. But a violinist who has sat down hasn't necessarily finished tuning the violin. In the same way, a container that has started may not have its program ready yet. That is where the bug at the start of this lesson comes from, the bug people meet most often in Compose.

From three docker runs to one file

notes-api needs three containers: its Node app, Postgres and Redis. Postgres (the short name of PostgreSQL) stores the notes. Redis (a small in-memory database) keeps a cache (a temporary copy) of the list of notes. With docker run, you'd have to create a network (where the containers connect to each other) and a volume (a place for data that lasts) every time. Then you'd run three long commands in the right order. With Compose, it's all written once in one file in the project folder. Docker's documentation now recommends the name compose.yaml, and the older name docker-compose.yml is still read. This lesson uses docker-compose.yml:

services:
  app:
    build: .
    env_file: .env
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: notes
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - db-data:/var/lib/postgresql/data
  redis:
    image: redis:7-alpine

volumes:
  db-data:

Everyday commands

docker compose up -d          # build if needed, create the network, then start everything in the background
docker compose ps -a          # the status of every container, including ones that have exited
docker compose logs -f app    # follow the app service's logs
docker compose up -d --build  # rebuild the app image after its code changed
docker compose down           # stop and delete the containers and the network
docker compose down -v        # the same, plus delete the volumes: the database's data goes too

depends_on doesn't mean ready

When it starts, notes-api connects to the database right away to run its database migrations (changes to the tables). If that fails, notes-api exits with exit code 1. This is what happens on the first up, exactly as in the Lab:

Second db app
0.0 container starts, Postgres starts preparing a new database waiting
0.7 still preparing container starts (depends_on is met)
1.0 not listening on port 5432 yet connects, refused, exit 1
5.2 ready to accept connections already dead

At second 1.0, the app's log prints:

app-1  | Database connection failed: connect ECONNREFUSED 172.18.0.2:5432

So a plain depends_on only waits for the db container to start, not for Postgres inside it to be ready. It's a race between the app and Postgres: sometimes the app succeeds (the database already exists and gets ready quickly), sometimes it fails. That makes this bug hard to catch.

The fix: give db a healthcheck, a command Docker runs again and again to check whether the service is healthy. Then tell app to wait for that healthy status:

  app:
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
  db:
    healthcheck:
      test: ["CMD", "pg_isready", "-h", "localhost", "-U", "notes"]
      interval: 2s
      timeout: 3s
      retries: 15

Reading the list of services

In the exercise, the list of services is written in a simplified format. Each service is written as a few key: value lines, and services are separated by one empty line:

service: app
image: node:20
port: 3000

service: db
image: postgres:16
port: 5432

A service's name is on the line that starts with service: . Cut the text into lines with split("\n"), keep the lines that startsWith("service: "), then drop that prefix. The result is ["app", "db"], in the order of the file.

⚠️ Compose habits that cause trouble

TL;DR: With Docker Compose, you write every service (a container that Compose runs: app, db, redis) in docker-compose.yml, then start them with one command. docker compose up -d starts them in the background, ps -a shows every container including those that exited, and logs -f app reads the logs. up -d --build rebuilds the image, down deletes the containers and the network that joins them, and down -v also deletes the volumes (places for data that lasts) and their data. A service's name becomes its host name (the name used to reach the container), so the database is reached at db:5432. A plain depends_on (the start order) only waits for the container to start. To make the app wait until the database is really ready, give db a healthcheck (a regular check command, here pg_isready) and write condition: service_healthy in the app's depends_on.

⚡ Three containers, one file

Write:

services:
  app:
    build: .
    ports:
      - "3000:3000"
  db:
    image: postgres:16
  redis:
    image: redis:7-alpine

Meaning: Docker Compose runs several containers from one file. Every container is written as a service. build: . builds the image from the Dockerfile, image: uses a ready-made image, and ports: is the same as -p. A service's name is also its host name (the name used to reach that container). So from inside app, the Postgres database is reached at db:5432 (Postgres's port).

⚡ One command for all of them

Write:

docker compose up -d
docker compose logs -f app
docker compose down

Meaning: up -d starts every service in the background, logs -f app follows the app's logs, and down deletes the containers and the network that joins them. The volumes (where the database's data lives) stay, unless you write down -v.

⚡ depends_on doesn't mean ready

Write:

app-1  | Database connection failed: connect ECONNREFUSED 172.18.0.2:5432
Guess first: app has depends_on: db, so db is started first. Why can the app still fail to connect to the database?

A plain depends_on only waits for the db container to start, not for Postgres inside it to accept connections. Because it's a race, sometimes the app succeeds, sometimes it fails.

Meaning: ECONNREFUSED means the connection was refused: Postgres wasn't ready yet. A bug that sometimes appears and sometimes doesn't, like this one, is Compose's most common bug.

⚡ Wait until it's healthy

Write:

  app:
    depends_on:
      db:
        condition: service_healthy
  db:
    healthcheck:
      test: ["CMD", "pg_isready", "-h", "localhost", "-U", "notes"]
      interval: 2s

Meaning: A healthcheck is a check command Docker runs again and again. Here Docker runs pg_isready every 2 seconds to check whether Postgres is ready. Once a check succeeds, the status of db becomes healthy. condition: service_healthy makes Compose wait for that status first, then start app.

What you will learn