Multi-container applications are essential for modern development. This tutorial demonstrates how to use Docker Compose to define, configure, and deploy applications with multiple services like web apps, databases, and caches.
1. Multi-Container Architecture Overview
Single Service
One container handles one task (e.g., app, DB)
Multi-Service
Connected services working together (e.g., web + DB + cache)
2. Define Services in docker-compose.yml
version: '3.8'
services:
web:
image: my-web-app
ports:
- "80:80"
environment:
DB_HOST: database
database:
image: postgres:14
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: example
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:
Key Features in This Configuration
- Service linking: Containers can communicate using service names (web → database)
- Persistent storage: PostgreSQL data volume for data persistence
- Environment configuration: Pass connection parameters to services
3. Start and Manage Containers
# Start all services
docker compose up -d
# View running containers
docker compose ps
# Stop and remove containers
docker compose down
Docker Compose automatically creates a network connecting all services. Containers can reference each other by their service name (e.g., the web app connects to database
as the hostname).
4. Scaling Services
# Scale the web service to 3 instances
docker compose up -d --scale web=3
This is particularly useful for load balancing web applications while keeping databases and other stateful services at a single instance.
Advanced Compose Features
Extends
Re-use common service configurations
e.g., shared base configurations
Health Checks
Ensure services are properly running
e.g., healthcheck: curl http://localhost:80
Profiles
Conditional service activation
e.g., run extra services only in dev
When to Use Docker Compose
Use Case | Docker Compose | Kubernetes |
---|---|---|
Local Development | ✓ | ✗ |
Production Orchestration | ✗ | ✓ |
Multi-container Testing | ✓ | ✗ |
CI/CD Pipeline | ✓ | ✓ |
Start Building Multi-Container Apps
Use Docker Compose for local development and scale to Kubernetes when ready for production.