appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Compose in practice

Lesson 4 of 412 minIntermediate

Define a multi-service app once: health checks, ordering, volumes and environment.

Docker Compose describes several containers, their networks and volumes in one YAML file, so one command starts the whole application.

compose.yaml
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    volumes:
      - dbdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 10
  api:
    build: ./api
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DB_HOST: db
    depends_on:
      db:
        condition: service_healthy

volumes:
  dbdata:

secrets:
  db_password:
    file: ./db_password.txt
  • Compose creates a network for the project, so api reaches the database as db.
  • healthcheck plus depends_on: condition: service_healthy makes api wait until the database really accepts connections. Plain depends_on only waits for the container to start.
  • A named volume (dbdata) keeps data when containers are recreated.
docker compose up -d --build
docker compose ps
docker compose logs -f api
docker compose down            # stop and remove containers
docker compose down -v         # also delete named volumes (data is lost!)

Carefuldocker compose down -v deletes your volumes, including database data. Use it only when you want a clean start.

NoteKeep configuration in environment variables or an .env file that is not committed. Use docker compose config to see the final, merged configuration.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does depends_on with condition: service_healthy do?
2. What does docker compose down -v remove in addition?
Hintdocker compose up with two flags.

Key terms