DEV Community

Yash Pritwani
Yash Pritwani

Posted on • Originally published at techsaas.cloud

Docker Multi-Stage Builds: A Quick Guide

Originally published on TechSaaS Cloud


Docker Multi-Stage Builds: A Quick Guide

Docker multi-stage builds let you use multiple FROM statements in your Dockerfile to create smaller, more efficient images.

Why Use Multi-Stage Builds?

  1. Smaller images — Only copy what you need to the final stage
  2. No build tools in production — Compilers, package managers stay in build stage
  3. Simpler Dockerfiles — No need for complex shell scripts to clean up

Example

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

# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/index.js"]
Enter fullscreen mode Exit fullscreen mode

This reduces image size from ~1GB to ~150MB.

Key Tips

  • Use specific base image tags (not latest)
  • Copy only necessary files with COPY --from=
  • Use .dockerignore to exclude unnecessary files
  • Consider distroless images for even smaller sizes

Originally published at techsaas.cloud

Top comments (0)