All posts
DevOps & Containers

Docker in Production: Multi-Stage Builds, Layer Caching, and Security Hardening

8 min readby imnb
DockerContainersDevOpsProductionSecurity
Share

Production-ready Docker practices including multi-stage builds for smaller images, layer caching strategies, security scanning, and docker-compose orchestration patterns.

Running Docker in production requires more than docker run. This guide covers optimization techniques, security hardening, and patterns I use for production containerized applications.

Multi-Stage Builds: Smaller, Faster Images

dockerfile
# ❌ Bad: Single-stage build (800MB+)
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]

# ✅ Good: Multi-stage build (150MB)
# Stage 1: Dependencies
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

# Stage 2: Build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 3: Production runtime
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production

# Copy only production dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules
# Copy only built artifacts from builder stage
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/public ./public

# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
USER nextjs

EXPOSE 3000
CMD ["node", "dist/server.js"]

# Result: 150MB vs 800MB (5x smaller)
# Faster downloads, less attack surface, lower costs

Layer Caching for Fast Builds

dockerfile
# ❌ Bad: Bust cache on any file change
FROM python:3.11-slim
WORKDIR /app
COPY . .  # This invalidates cache when ANY file changes
RUN pip install -r requirements.txt
CMD ["python", "app.py"]

# ✅ Good: Optimize layer order
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies (rarely change)
RUN apt-get update && apt-get install -y \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements first (only cache-bust when deps change)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy app code last (changes frequently)
COPY . .

CMD ["python", "app.py"]

# Build time with cache:
# First build: 3 minutes
# Rebuild after code change: 5 seconds (reuses dependency layers)

Security Hardening Checklist

dockerfile
# Production-grade secure Dockerfile
FROM node:18-alpine

# 1. Run as non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# 2. Install only what's needed
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production --ignore-scripts

# 3. Copy application files
COPY --chown=appuser:appgroup . .

# 4. Remove unnecessary files
RUN rm -rf tests/ docs/ .git/

# 5. Set environment variables
ENV NODE_ENV=production \
    PORT=3000

# 6. Use specific port
EXPOSE 3000

# 7. Switch to non-root user
USER appuser

# 8. Add health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node healthcheck.js || exit 1

# 9. Use exec form of CMD
CMD ["node", "server.js"]

# Security scanning:
# docker scan my-image
# trivy image my-image
# snyk container test my-image

Docker Compose for Multi-Container Apps

yaml
# docker-compose.yml - Production-ready setup
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      target: production
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://postgres:password@db:5432/myapp
      REDIS_URL: redis://cache:6379
      NODE_ENV: production
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    restart: unless-stopped
    networks:
      - app-network
    volumes:
      - ./logs:/app/logs  # Persist logs
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  db:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: ${DB_PASSWORD}  # Use .env file
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    ports:
      - "5432:5432"
    restart: unless-stopped
    networks:
      - app-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

  cache:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    restart: unless-stopped
    networks:
      - app-network
    volumes:
      - redis-data:/data
    command: redis-server --appendonly yes

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
    depends_on:
      - app
    restart: unless-stopped
    networks:
      - app-network

volumes:
  postgres-data:
  redis-data:

networks:
  app-network:
    driver: bridge

# Usage:
# docker-compose up -d           # Start all services
# docker-compose ps              # Check status
# docker-compose logs -f app     # View app logs
# docker-compose down -v         # Stop and remove volumes

Pro Tips and Gotchas

  • Use .dockerignore to exclude node_modules, .git, tests from build context (faster builds)
  • Pin base image versions: node:18.15-alpine not node:latest (reproducible builds)
  • BuildKit enables parallel builds: DOCKER_BUILDKIT=1 docker build . (2-3x faster)
  • Layer sizes shown with 'docker history <image>' - find bloat sources
  • Bind mounts for development: docker run -v $(pwd):/app for hot reload
  • Named volumes persist data: docker volume create prevents data loss
  • Container logs: docker logs <container> --follow --tail 100
  • Exec into running container: docker exec -it <container> sh
  • Resource limits: --memory=512m --cpus=0.5 prevents resource hogging
  • Security: Never run containers as root in production, scan images regularly
  • Restart policies: unless-stopped survives daemon restarts, always doesn't
  • Multi-platform builds: docker buildx build --platform linux/amd64,linux/arm64

Keep reading