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
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-networkKey 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.
