How to Use Docker Compose for Multi-Container Applications
Docker Compose simplifies running applications that need multiple services—like a web server, database, and cache—by letting you define everything in a single YAML file. Instead of typing long docker run commands for each container, you use docker-compose up to start all services together. This tutorial covers the essential steps for building and managing multi-container apps with Docker Compose.
1. Create a docker-compose.yml File
Place this file in your project root. Define each service under the services key. Example for a Node.js app with Redis and PostgreSQL:
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
depends_on:
- redis
- db
redis:
image: redis:alpine
db:
image: postgres:13
environment:
POSTGRES_PASSWORD: example
2. Use Environment Variables and Volumes
Keep sensitive data out of the YAML file by using an .env file. Reference variables like ${DB_PASSWORD}. For persistent data, add volumes:
services:
db:
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
3. Run and Manage Services
Start all services in detached mode: docker-compose up -d. View logs: docker-compose logs -f. Stop and remove containers: docker-compose down. Rebuild after changes: docker-compose up --build.
4. Scale Services and Networks
Scale a service (if it supports it) with docker-compose up -d --scale web=3. By default, Compose creates a single network for all services, so they can communicate using service names as hostnames.
Conclusion: Docker Compose streamlines running complex multi-container apps, saving time and reducing errors. With one YAML file, you can define, build, and manage all services together, making development and deployment far more efficient.