Docker Compose Introduction - Multi-Container Configuration

intermediate | 50 min read | 2024.12.26

What You’ll Learn in This Tutorial

✓ Docker Compose basics
✓ Service definitions
✓ Networks and volumes
✓ Environment variable management
✓ Practical configuration examples

Step 1: Basic compose.yaml

# compose.yaml
services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=development
    volumes:
      - .:/app
      - /app/node_modules
    depends_on:
      - db

  db:
    image: postgres:16
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

volumes:
  postgres_data:

Step 2: Dockerfile

FROM node:20-alpine

WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .

EXPOSE 3000
CMD ["npm", "run", "dev"]

Step 3: Basic Commands

# Start
docker compose up -d

# Check logs
docker compose logs -f web

# Stop
docker compose down

# Rebuild
docker compose up -d --build

# List services
docker compose ps

Step 4: Production Configuration

# compose.prod.yaml
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.prod
    restart: always
    environment:
      - NODE_ENV=production

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - web
docker compose -f compose.prod.yaml up -d

Step 5: Combined Environment Example

services:
  app:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis

  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: password
    volumes:
      - db_data:/var/lib/postgresql/data

  redis:
    image: redis:alpine
    ports:
      - "6379:6379"

  adminer:
    image: adminer
    ports:
      - "8080:8080"

volumes:
  db_data:

Summary

Docker Compose makes it easy to build and share development environments. Manage service dependencies and networks declaratively.

← Back to list