← Learning Hub
Advanced

Docker Compose: App + Database Together

Real apps have several parts - an API, a database, maybe a cache. Docker Compose describes them all in one compose.yaml file and starts them with one command.

Real apps have several services - an API, a database, maybe a cache. Compose describes them all in one file, wires up networking between them, and starts everything with one command, both on your laptop and on a server.

Example
# compose.yaml
services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://shop:${DB_PASSWORD}@db:5432/shop
    depends_on:
      - db
    restart: unless-stopped

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: shop
    volumes:
      - dbdata:/var/lib/postgresql/data
    restart: unless-stopped

volumes:
  dbdata:

Inside Compose, services find each other by name: the API connects to the host db, not localhost. ${DB_PASSWORD} is read from a .env file next to compose.yaml (keep that file out of Git).

Everyday commands

Example
docker compose up -d          # build if needed and start everything in the background
docker compose ps             # what's running
docker compose logs -f api    # follow the API's logs
docker compose exec db psql -U shop shop    # open the database console
docker compose down           # stop and remove the containers (the volume and data stay)
docker compose up -d --build  # rebuild after changing code
docker compose down -v also deletes volumes - that means your database data. Only use -v when you really want to start fresh.
Key points
  • compose.yaml lists services, ports, env and volumes.
  • Services reach each other by name.
  • docker compose up -d starts everything.

📝 Test yourself

1. How does the api service reach the database in Compose?
2. What does docker compose down -v also remove?
3. Fill in the command that starts all services in the background:
docker compose -d