5 min read

Docker Compose - Orchestrating Multiple Containers

1. Recap: From Repeated docker run to a Single File

In the previous article, bringing up a connected API and Postgres took two long docker run commands, with network, volume and environment variable flags to remember (and type) every time. In a real project, with more services — cache, queue, background worker — this quickly becomes impossible to keep in your head or in a loose script. Docker Compose solves this by describing the whole multi-container application in a single declarative file, versioned alongside the code.

2. The compose.yaml File

Compose reads a YAML file (by convention compose.yaml, or the legacy name docker-compose.yml, still widely used) describing services (each one becomes one or more containers), networks and volumes:

# compose.yaml
services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgresql://postgres:secret@db:5432/postgres
    depends_on:
      - db

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - pg-data:/var/lib/postgresql/data

volumes:
  pg-data:

This entirely replaces the two docker run commands from the previous article. An important difference shows up right away: by default, Compose creates a network of its own for the project and connects every service to it automatically — no manual docker network create, and no --network on each service. Each service is already reachable by the others through the name declared under services: (here, db resolves to the Postgres container), exactly like the user-defined networks from the previous article.

3. Essential Compose Commands

docker compose up -d          # start every service in the background
docker compose ps             # list the project's containers and their status
docker compose logs -f api    # follow the logs of a specific service
docker compose logs -f        # follow the logs of every service, interleaved
docker compose exec api bash  # open a shell inside a service's container
docker compose stop           # stop the containers without removing them
docker compose down           # stop and remove containers and network (named volumes survive)
docker compose down -v        # also remove the volumes — careful, this deletes data

The docker compose <command> <service> pattern repeats: most commands optionally take the name of a specific service (as in logs -f api) or affect the whole project if it’s omitted.

4. depends_on: Startup Order, Not Readiness

depends_on controls the order in which containers are created and started — in the example above, db starts before api. What it does not guarantee is that Postgres is already ready to accept connections at that moment: the Postgres process can take a few seconds to initialize after the container starts running, and an API that tries to connect right away can fail in that window.

The correct way to wait for real readiness is a healthcheck:

services:
  api:
    build: .
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5

With condition: service_healthy, Compose only considers db “ready” (and only then starts api) after the healthcheck passes — much more reliable than assuming a fixed wait time or implementing manual retries in the application (although having retries in the application is still a good defensive practice, even with a healthcheck).

5. Environment Variables and the .env File

Secrets and configuration that vary per environment (database password, API keys) shouldn’t be hardcoded in compose.yaml. Compose automatically reads a .env file in the same directory and substitutes variables referenced with ${NAME}:

# .env
POSTGRES_PASSWORD=local-secret
API_PORT=8000
services:
  api:
    build: .
    ports:
      - "${API_PORT}:8000"
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}

This lets you version compose.yaml normally while .env (which contains real secrets) stays out of version control via .gitignore — the same principle of never committing credentials, applied to the Compose configuration.

6. A Complete Environment: App + Database + Cache

Extending the example to a more realistic scenario, with Redis as a cache in addition to the API and Postgres:

services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/postgres
      REDIS_URL: redis://cache:6379
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - pg-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 5

  cache:
    image: redis:7-alpine
    volumes:
      - redis-data:/data

volumes:
  pg-data:
  redis-data:

A single docker compose up -d brings up all three services, in the right order, already connected to each other and with persistent data — the equivalent of a complete local development infrastructure, reproducible on any machine with Docker installed, without installing Postgres or Redis directly on the system.

7. Scaling a Service

To run multiple instances of the same service (for example, several workers processing a queue in parallel):

docker compose up -d --scale worker=3

This only works without conflicts for services that don’t publish a fixed host port (ports:) — three containers can’t all map host port 8000 at the same time. Services designed to scale this way typically don’t expose a port to the host directly, and are reached by another service (such as a reverse proxy) through Compose’s internal network.

8. Conclusion and Next Steps

Docker Compose turns a collection of fragile, hard-to-remember docker run commands into a single declarative, versionable file that describes the whole application — services, network, volumes, startup order and environment variables. In the last article of this series, the subject moves to production-grade practices: multi-stage builds to drastically reduce the final image size, security (running without root, vulnerability scanning) and how all of this fits into a CI/CD pipeline.


References:

  1. Docker Documentation — Compose
  2. Compose File Reference