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.
FROM node:20-alpine AS builder
...
FROM node:20-alpine AS runner
COPY --from=builder /app/dist ./distStep-by-Step Execution Guide
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run buildInstalls all dependencies (including devDependencies) and compiles TypeScript / Next.js assets.
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.
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.
Related Docker Command Guides
Browse All Docker RecipesOpen an interactive terminal shell session inside a live running Docker container to inspect files, debug processes, or test network connectivity.
Reclaim gigabytes of hard drive space by removing stopped containers, unused networks, dangling images, and build caches.
Instantly stop all active containers and optionally remove them with a single command.
Copy files or directories between a Docker container and your local host file system without creating a volume mount.
Understand the fundamental differences between ENTRYPOINT and CMD directives and how to combine them for flexible container CLIs.
Inspect stdout and stderr output from containers with timestamps, tail line limits, and live streaming.