The compose.yaml file

Describing an application and its database instead of long commands.

Once there is more than one service, docker run commands with a dozen flags become hard to repeat without mistakes. Docker Compose describes everything in a single compose.yaml file: which services to start, from which images, with which ports, variables and volumes. One command brings the whole set up, another takes it down.

services:
  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      DATABASE_HOST: db
  db:
    image: postgres:16.4
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

The api service is built from the Dockerfile in the current folder, db is started from a ready-made image. The pgdata volume is declared at the bottom of the file.

Compose creates a network for the project itself, and services find each other by service name: the application connects to the host db. The database port is not published to the outside, and that is right: only the application needs it.

docker compose up -d
docker compose ps
docker compose logs -f api
docker compose down

up -d builds missing images and starts the services in the background. up -d --build rebuilds the images if the code has changed. down stops and removes the containers and the network but keeps the volumes.

A common mistake is to change the code and run docker compose up -d without --build. Compose sees that the api image already exists and starts the old version. If your changes “did not apply”, first check whether the image was rebuilt. Another mistake is to keep real passwords in compose.yaml: the file usually lives in the repository, and the secrets in it are visible to everyone.

Practice

  1. What down removes

    What does docker compose down remove without extra flags?

    • Containers, network and volumes
    • Containers and network, volumes stay
    • Only images
    • Nothing, it only stops the containers
  2. How Compose works

    Which statements about Docker Compose are true? Mark all.

    • Services find each other by service name
    • docker compose up -d always rebuilds the images
    • The --build flag rebuilds the images before starting
    • The database port must be published for the application to see it
  3. Starting in the background

    Which command brings up all services from compose.yaml in the background?