Beginner Guide for Docker Compose
0 views
Beginner Guide for Docker Compose
Docker Compose lets you define and run multi-container applications in a single file and with one command.
Why Docker Compose?
- One file: Describe all services, networks, and volumes in
docker-compose.yml. - One command:
docker compose upstarts (and builds) everything. - Reproducible: Same file works on any machine with Docker and Compose.
Basic example
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
depends_on:
- db
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: app
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
Common commands
| Command | Description |
|---|---|
docker compose up -d | Start all services in the background |
docker compose down | Stop and remove containers (add -v to remove volumes) |
docker compose ps | List running services |
docker compose logs -f | Follow logs from all services |
docker compose build | Build images defined with build: |
Key concepts
- services: Each container (e.g.
web,db) is a service. - build: Use
build: .to build from a Dockerfile in the current directory. - image: Use
image: name:tagto use a pre-built image. - ports: Map host port to container port (
"HOST:CONTAINER). - environment: Set environment variables for the container.
- volumes: Persist data; named volumes (e.g.
db_data) are managed by Docker. - depends_on: Start order; wait for listed services to be started (not “healthy” unless you use
condition).
Tips for beginners
- Start with
docker compose up(no-d) to see logs and Ctrl+C to stop. - Use
docker compose configto validate your file. - Use
depends_onwithcondition: service_healthywhen a service must wait for another to be ready. - Put
.envnext todocker-compose.ymland reference variables with${VAR}.
Once you’re comfortable, try adding a reverse proxy (e.g. Nginx) or multiple app services in the same Compose file.