Docker Compose cho môi trường dev: app + PostgreSQL + Redis với hot reload

"Works on my machine" — câu nói kinh điển kết thúc bằng Docker Compose. Thay vì cài Postgres và Redis thẳng lên máy (conflict version, cleanup khó), Docker Compose tạo môi trường isolated chạy giống nhau trên mọi máy trong team. Bài này xây docker-compose.yml hoàn chỉnh từ đầu cho một Node.js app với Postgres và Redis — bao gồm hot reload, healthcheck, và các lệnh thường dùng.

docker-compose.yml hoàn chỉnh

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "3000:3000"
    volumes:
      # Mount source code để hot reload — thay đổi file local = thay đổi trong container
      - .:/app
      # Anonymous volume cho node_modules — không bị overwrite bởi mount trên
      - /app/node_modules
    environment:
      - NODE_ENV=development
      - DATABASE_URL=postgresql://postgres:devpassword@postgres:5432/myapp_dev
      - REDIS_URL=redis://redis:6379
      # Hot reload trên Windows/WSL cần polling
      - CHOKIDAR_USEPOLLING=true
    depends_on:
      postgres:
        condition: service_healthy  # đợi postgres healthy trước khi start app
      redis:
        condition: service_healthy
    restart: unless-stopped

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: devpassword
      POSTGRES_DB: myapp_dev
    ports:
      - "5432:5432"   # expose ra host để dùng GUI tools (TablePlus, DBeaver...)
    volumes:
      - postgres_data:/var/lib/postgresql/data  # persist data qua container restart
      - ./db/init:/docker-entrypoint-initdb.d   # scripts chạy khi DB lần đầu init
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d myapp_dev"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    command: redis-server --appendonly yes  # persist data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

volumes:
  postgres_data:
  redis_data:

Dockerfile.dev — tối ưu cho development

FROM node:20-alpine

WORKDIR /app

# Copy package files trước — layer cache khi source code thay đổi
# (node_modules chỉ rebuild khi package.json thay đổi)
COPY package*.json ./
RUN npm install

# Không COPY source code — được mount qua volume ở docker-compose.yml

EXPOSE 3000

# nodemon để hot reload (cần cài trong devDependencies)
CMD ["npx", "nodemon", "--watch", "src", "src/index.js"]

Thứ tự COPY quan trọng: Copy package.json và chạy npm install trước, sau đó mới COPY source code. Docker cache theo layer — nếu source code thay đổi nhưng package.json không đổi, Docker dùng cached node_modules layer → build nhanh hơn nhiều.

Tại sao cần anonymous volume cho node_modules

volumes:
  - .:/app               # mount toàn bộ project directory
  - /app/node_modules    # override node_modules với anonymous volume (empty)

Nếu chỉ có .:/app, Docker sẽ mount thư mục node_modules từ máy host vào container — có thể bị lỗi nếu host là Windows (native binaries không tương thích). Anonymous volume /app/node_modules cho Dockerfile RUN là priority, không bị overwrite bởi host mount.

CHOKIDAR_USEPOLLING trên Windows/WSL

File watching (inotify) không hoạt động tốt khi mount từ Windows filesystem vào Linux container qua WSL2. CHOKIDAR_USEPOLLING=true switch sang polling — chậm hơn một chút nhưng detect được file changes.

# .env.dev (để override tùy máy)
CHOKIDAR_USEPOLLING=true
CHOKIDAR_INTERVAL=300  # ms, default 300

depends_on condition: service_healthy

depends_on thông thường chỉ chờ container start, không chờ service sẵn sàng nhận connection. PostgreSQL cần vài giây để khởi động xong sau khi container start. Nếu app start trước Postgres xong → connection error → app crash.

condition: service_healthy chờ healthcheck pass (pg_isready trả về OK) trước khi start app. Đây là cách đúng để handle startup ordering.

Các lệnh docker compose thường dùng

# Start tất cả services ở background
docker compose up -d

# Start và xem logs ngay
docker compose up

# Stop tất cả (giữ data volumes)
docker compose down

# Stop và xóa cả volumes (reset DB hoàn toàn)
docker compose down -v

# Xem logs real-time
docker compose logs -f

# Xem logs của service cụ thể
docker compose logs -f app

# Chạy lệnh trong container đang chạy
docker compose exec app sh
docker compose exec postgres psql -U postgres -d myapp_dev
docker compose exec app npm run db:migrate

# Restart một service (sau khi sửa Dockerfile)
docker compose restart app

# Rebuild image (sau khi thay đổi Dockerfile hoặc package.json)
docker compose up -d --build app

# Xem trạng thái tất cả services
docker compose ps

# Scale service (nếu cần test với nhiều instances)
docker compose up -d --scale app=3

.dockerignore — quan trọng không kém .gitignore

# .dockerignore
node_modules
npm-debug.log
.git
.env
.env.*
*.md
.DS_Store

# Không có .dockerignore → COPY . . sẽ copy cả node_modules vào image
# → Image lớn không cần thiết, build chậm

Script init database

-- db/init/01_extensions.sql (chạy tự động lần đầu init)
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";  -- cho ILIKE index

-- db/init/02_seed.sql
INSERT INTO users (name, email) VALUES
  ('Admin', 'admin@example.com')
ON CONFLICT (email) DO NOTHING;

Files trong ./db/init/ mount vào /docker-entrypoint-initdb.d/ chạy theo thứ tự alphabet khi database được tạo lần đầu. Chỉ chạy lần đầu — khi postgres_data volume đã tồn tại thì không chạy lại.

Tách file cho production

# docker-compose.prod.yml — chỉ chứa differences
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile  # Dockerfile production (không phải .dev)
    volumes: []               # không mount source code
    environment:
      - NODE_ENV=production
      # Không có CHOKIDAR_USEPOLLING

# Dùng:
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
← Về danh sách Blog