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?
- Smaller images — Only copy what you need to the final stage
- No build tools in production — Compilers, package managers stay in build stage
- 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"]
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
.dockerignoreto exclude unnecessary files - Consider
distrolessimages for even smaller sizes
Originally published at techsaas.cloud
Top comments (0)