Docker Compose
Docker Compose lets you define and run multi-container applications in a single place. You describe services, networks, and volumes in a Compose file (usually docker-compose.yml) and use docker compose up to start everything.
Compose File Basics
Section titled “Compose File Basics”services: web: image: nginx:alpine ports: - "8080:80" depends_on: - api
api: build: ./api environment: - DB_HOST=db - DB_PORT=5432 depends_on: - db
db: image: postgres:16-alpine environment: POSTGRES_USER: app POSTGRES_PASSWORD: secret volumes: - dbdata:/var/lib/postgresql/data
volumes: dbdata:Key Fields
Section titled “Key Fields”| Field | Purpose |
|---|---|
| services | Each key is a service name (e.g. web, api, db). |
| image | Use a pre-built image (e.g. nginx:alpine). |
| build | Build from a Dockerfile (path or context + dockerfile). |
| ports | Publish ports "host:container". |
| environment | Environment variables for the container. |
| volumes | Mount named volumes or bind mounts. |
| depends_on | Start order (does not wait for health). |
| networks | Attach services to user-defined networks. |
Commands
Section titled “Commands”# Start all services (build if needed, foreground)docker compose up
# Start in backgrounddocker compose up -d
# Build and startdocker compose up -d --build
# Stop and remove containers (volumes persist by default)docker compose down
# Stop and remove containers and named volumesdocker compose down -v
# List running servicesdocker compose ps
# View logs (all services or one)docker compose logs -fdocker compose logs -f apiNetworks
Section titled “Networks”By default Compose creates a single network per project and attaches all services to it. Containers can reach each other by service name (e.g. db, api). To use a custom network:
services: web: networks: - front api: networks: - front - back db: networks: - back
networks: front: {} back: {}Key Takeaways
Section titled “Key Takeaways”- Define services, volumes, and networks in
docker-compose.yml; use depends_on for start order. - docker compose up -d starts the stack; docker compose down stops and removes containers. Use docker compose logs and docker compose ps to inspect.