Docker Compose

Docker · lesson 12 of 31 · 4 min read

Describe your app and its database in one file and start the whole stack with one command.

Open this lesson in the learning hub

Key points

  • Compose is the multi-container version of docker run. One YAML file, one command, repeatable for everyone.
  • The current filename is compose.yaml, and the top-level version: key is obsolete. Delete it.
  • Compose creates a network for you, so every service is reachable by its service name.
  • depends_on alone only orders startup. Add condition: service_healthy to actually wait for readiness.
  • Daily loop: docker compose up --build -d, then logs -f, then down. Add -v to drop the volumes too.

Example

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_DB: app
      POSTGRES_PASSWORD: secret
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d app"]
      interval: 5s
      timeout: 3s
      retries: 10

  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/app
      SPRING_DATASOURCE_USERNAME: postgres
      SPRING_DATASOURCE_PASSWORD: secret
    depends_on:
      db:
        condition: service_healthy

volumes:
  pgdata:

compose.yaml turns "works on my machine" into "docker compose up".

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Docker course, and every lesson in it is listed on the Docker contents page.