Images & Build

How to Create Docker Multi-Stage Builds to Reduce Image Size

Shrink production Docker image sizes from 1.5GB down to 50MB by separating heavy build dependencies from the minimal production runtime.

Quick Docker Solution
Safe CommandAdvanced
FROM node:20-alpine AS builder
...
FROM node:20-alpine AS runner
COPY --from=builder /app/dist ./dist
When to use this scenario:Your production Docker image includes large compilers (gcc, python), devDependencies, and source code that bloated image size and pose security risks.

Step-by-Step Execution Guide

1Stage 1: Build & compile application
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

Installs all dependencies (including devDependencies) and compiles TypeScript / Next.js assets.

2Stage 2: Minimal production runner
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --only=production
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/server.js"]

Only copies production dependencies and the compiled dist folder. Dev tools and compilers are discarded.

Critical Docker Pitfalls & Precautions

  • β€’Ensure "COPY package*.json ./" is run before "COPY . ." to leverage Docker layer caching when source code changes.
Frequently Asked Questions

Multi-Stage Build (Small Images) - Frequently Asked Questions

Common questions about container isolation, signal handling, and runtime behavior.

Typically 70% to 95% smaller! A Go or Rust application can go from 1GB down to a 10MB scratch image containing only the compiled binary.