Docker Multi-Stage Builds for Smaller and Safer Images

Large container images slow down CI/CD and increase security surface area.

Why Multi-Stage Builds Help

With multi-stage builds, you compile in one stage and copy only runtime artifacts to the final image.

Benefits:

Example (Node.js)

# Build stage
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Runtime stage
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

Production Checklist

Common Mistake

Copying the whole source tree into the runtime stage can accidentally include secrets, .env, or source maps. Use .dockerignore aggressively.