Mastering Docker Multi-Stage Builds
Docker multi-stage builds are a game-changer for creating lean, production-ready container images.
The Problem
Traditional Dockerfiles often result in bloated images: - Build tools included in final image - Source code present - Unnecessary dependencies - Large image sizes
The Solution: Multi-Stage Builds
# Build stage
FROM node:16 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Production stage
FROM node:16-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY package*.json ./
RUN npm install --production
CMD ["node", "dist/index.js"]
Benefits
- Smaller images: 90% size reduction possible
- Better security: Fewer attack surfaces
- Faster deployments: Less data to transfer
- Cleaner separation: Build vs runtime
Advanced Patterns
Using Multiple Builders
FROM golang:1.19 AS go-builder
# Go build steps...
FROM node:16 AS node-builder
# Node build steps...
FROM alpine:latest
COPY --from=go-builder /app/binary ./
COPY --from=node-builder /app/dist ./static
Best Practices
- Order layers by change frequency
- Use .dockerignore
- Combine RUN commands
- Use specific tags, not
latest - Leverage build cache
Multi-stage builds are essential for modern Docker workflows!