Script Valley
Docker: Complete Course
Docker ComposeLesson 4.2

Writing your first docker-compose.yml file

services block, image vs build, ports, environment, volumes, depends_on, restart policy, networks block

Anatomy of a Compose File

Docker Compose YAML structure

Every Compose file defines services, and optionally networks and volumes. Here is a complete, real example for a Node.js API backed by PostgreSQL:

services:
  api:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DB_HOST=db
      - DB_PASSWORD=secret
    depends_on:
      - db
    restart: unless-stopped

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: appdb
    volumes:
      - pgdata:/var/lib/postgresql/data
    restart: unless-stopped

volumes:
  pgdata:

networks:
  default:
    name: app-network

Key points: build: . tells Compose to build from the local Dockerfile. depends_on ensures db starts before api โ€” but it does not wait for Postgres to be ready, only for the container to start. Use a health check or retry logic in your app for true readiness. Compose auto-creates a default network for all services, so they can reach each other by service name out of the box.

Up next

Docker Compose environment variables and .env files

Sign in to track progress

Writing your first docker-compose.yml file โ€” Docker Compose โ€” Docker: Complete Course โ€” Script Valley โ€” Script Valley