You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Running a multi-container application by hand — typing long docker run commands, creating networks, managing volumes — quickly becomes tedious and error-prone. Docker Compose solves this by letting you define your entire application stack in a single YAML file and manage it with simple commands.
A docker-compose.yml (or compose.yml) file describes the services, networks, and volumes that make up your application.
# compose.yml
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
POSTGRES_DB: mydb
volumes:
- db-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
api:
build: ./api
ports:
- "4000:4000"
environment:
DATABASE_URL: postgresql://postgres:secret@db:5432/mydb
depends_on:
db:
condition: service_healthy
frontend:
build: ./frontend
ports:
- "3000:3000"
environment:
NEXT_PUBLIC_API_URL: http://localhost:4000
depends_on:
- api
volumes:
db-data:
# Start all services in the background
docker compose up -d
# Build images before starting
docker compose up -d --build
# View logs for all services
docker compose logs
# Follow logs for a specific service
docker compose logs -f api
# List running services
docker compose ps
# Stop all services (containers remain)
docker compose stop
# Stop and remove containers, networks (volumes preserved)
docker compose down
# Stop and remove containers, networks, and volumes
docker compose down -v
# Restart a single service
docker compose restart api
# Run a one-off command in a service container
docker compose exec api sh
Compose automatically reads a .env file in the same directory and makes those variables available for interpolation in the Compose file.
# .env
POSTGRES_PASSWORD=supersecret
API_PORT=4000
# compose.yml — values are substituted from .env
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
api:
ports:
- "${API_PORT}:4000"
Compose can run multiple replicas of a stateless service:
# Run 3 replicas of the api service
docker compose up -d --scale api=3
Profiles let you selectively start subsets of services. A service tagged with a profile only starts when that profile is active:
# Start only production services
docker compose --profile production up -d
# Start including debug tools
docker compose --profile debug up -d
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.