Docker Compose lets you define and run multi-container applications with a single YAML file. No more "works on my machine" - everyone gets the same environment.
A Real-World Example
Let's build a complete development stack: Node.js app + PostgreSQL + Redis + Mailhog (email testing).
# docker-compose.yml
version: "3.8"
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
- DATABASE_URL=postgresql://dev:devpass@postgres:5432/myapp
- REDIS_URL=redis://redis:6379
- SMTP_HOST=mailhog
- SMTP_PORT=1025
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: dev
POSTGRES_PASSWORD: devpass
POSTGRES_DB: myapp
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U dev"]
interval: 5s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
mailhog:
image: mailhog/mailhog
ports:
- "1025:1025" # SMTP
- "8025:8025" # Web UI
volumes:
postgres_data:
redis_data:The Development Dockerfile
# Dockerfile.dev
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
# Hot reload with nodemon
CMD ["npx", "nodemon", "--watch", "src", "src/index.js"]Essential Commands
# Start all services
docker compose up -d
# View logs
docker compose logs -f app
# Run database migrations
docker compose exec app npx prisma migrate dev
# Access PostgreSQL shell
docker compose exec postgres psql -U dev myapp
# Stop everything
docker compose down
# Stop and remove volumes (fresh start)
docker compose down -vPro Tips
- Use volumes for data persistence - Named volumes survive container restarts
- Health checks matter - Prevent your app from starting before the database is ready
- Bind mounts for hot reload - Mount source code so changes reflect immediately
- Use .env files - Keep secrets out of docker-compose.yml
- Profiles for optional services - Only start what you need
No comments yet. Be the first!