Docker multi-stage builds are the single highest-ROI optimization for container images. A typical Node.js app goes from 1.2GB to 180MB. A Go binary from 800MB to 15MB. This is not theoretical – these are real production numbers.
This guide covers patterns that work in production, not hello-world examples. Every pattern here has been used to ship real applications.
The Problem: Why Your Images Are Bloated
# The naive approach - everything in one stage
FROM node:20
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
CMD ["npm", "start"]
Result: 1.2GB image containing:
- Full Node.js toolchain (npm, node-gyp, compilers)
- Source code and tests
- devDependencies (jest, eslint, typescript, webpack)
- Build artifacts AND source maps
- Package manager cache
Production needs: Just the runtime + compiled output.
Multi-Stage Fundamentals
# Stage 1: Builder
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production=false
COPY . .
RUN npm run build
# Stage 2: Runtime
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./
CMD ["node", "dist/index.js"]
Result: ~180MB (alpine base) vs 1.2GB. 85% reduction.
Key insight: --from=builder copies ONLY what you specify. Nothing else leaks through.
Language-Specific Patterns
Node.js / TypeScript
# syntax=docker/dockerfile:1.4
FROM node:20-alpine AS base
WORKDIR /app
# Install dependencies only (cached layer)
FROM base AS deps
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --only=production
# Build stage
FROM base AS builder
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
RUN npm run build
# Production runtime
FROM base AS runner
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./
# Non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nextjs -u 1001
USER nextjs
CMD ["node", "dist/index.js"]
Critical optimizations:
--mount=type=cache– caches npm cache across buildsnpm ci– faster, deterministic, fails on mismatch- Separate
depsstage – only production deps in final image - Non-root user – security baseline
Go (Static Binary)
# syntax=docker/dockerfile:1.4
FROM golang:1.22-alpine AS builder
WORKDIR /src
RUN apk add --no-cache git make
# Cache go modules
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
# Build
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server .
# Minimal runtime
FROM scratch AS runner
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /app/server /server
COPY --from=builder /etc/passwd /etc/passwd
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/server"]
Result: 15MB (scratch) vs 800MB (golang:alpine). 98% reduction.
Key points:
CGO_ENABLED=0– static binary, no glibc dependency-ldflags="-s -w"– strip debug symbols and DWARF tablescratchbase – literally empty filesystem- Copy ca-certificates for TLS
- Copy
/etc/passwdfor user resolution
Python (uv for Speed)
# syntax=docker/dockerfile:1.4
FROM python:3.12-slim AS base
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
# Install uv (fast pip replacement)
FROM base AS deps
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen --no-dev
# Builder (includes dev deps for tests)
FROM base AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen
COPY . .
RUN uv run pytest
# Runtime
FROM base AS runner
COPY --from=deps /app/.venv /app/.venv
COPY --from=builder /app/src ./src
ENV PATH="/app/.venv/bin:$PATH"
USER 1000:1000
CMD ["python", "-m", "src.main"]
Java (JLink Custom Runtime)
# syntax=docker/dockerfile:1.4
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN --mount=type=cache,target=/root/.m2 \
./mvnw dependency:go-offline -B
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 \
./mvnw package -DskipTests -B
# Create minimal JRE
RUN jdeps --ignore-missing-deps -q \
--recursive \
--multi-release 21 \
--print-module-deps \
--class-path "target/*jar" \
target/*.jar > /tmp/deps.modules
RUN jlink \
--add-modules $(cat /tmp/deps.modules) \
--strip-debug \
--compress=2 \
--no-header-files \
--no-man-pages \
--output /jre-minimal
# Runtime
FROM alpine:3.19 AS runner
ENV JAVA_HOME=/opt/java
ENV PATH="$JAVA_HOME/bin:$PATH"
COPY --from=builder /jre-minimal $JAVA_HOME
COPY --from=builder /app/target/*.jar /app/app.jar
USER 1000:1000
ENTRYPOINT ["java", "-XX:+UseContainerSupport", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
Result: ~60MB (jlink) vs 400MB (full JDK). JLink creates a custom JRE with ONLY modules your app uses.
Rust
# syntax=docker/dockerfile:1.4
FROM rust:1.76-alpine AS builder
WORKDIR /app
RUN apk add --no-cache musl-dev pkgconfig openssl-dev
# Cache dependencies
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/app/target \
cargo build --release
# Actual build
COPY src ./src
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/app/target \
cargo build --release
# Runtime
FROM alpine:3.19 AS runner
RUN apk add --no-cache ca-certificates
COPY --from=builder /app/target/release/myapp /usr/local/bin/myapp
USER 1000:1000
ENTRYPOINT ["myapp"]
Advanced Patterns
BuildKit Cache Mounts (The Game Changer)
# syntax=docker/dockerfile:1.4
FROM node:20-alpine
WORKDIR /app
# npm cache persists across builds!
RUN --mount=type=cache,target=/root/.npm \
npm ci
# Go module cache persists!
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
# Cargo registry + build cache!
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/app/target \
cargo build --release
Requirements:
DOCKER_BUILDKIT=1(default in Docker 23+)# syntax=docker/dockerfile:1.4at top of Dockerfile
Multi-Architecture Builds
# Build for multiple platforms
docker buildx create --use --name multiarch
docker buildx build \
--platform linux/amd64,linux/arm64 \
--push \
-t myregistry/app:v1.0 \
.
Build-Time Secrets (Never in Image)
# syntax=docker/dockerfile:1.4
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json .=
# Secret available ONLY during this RUN
RUN --mount=type=secret,id=npm_token \
npm ci --registry=https://npm.pkg.github.com
COPY . .
RUN npm run build
Build command:
docker build --secret id=npm_token,src=$HOME/.npm_token .
SSH Agent Forwarding (Private Git Dependencies)
# syntax=docker/dockerfile:1.4
FROM node:20-alpine AS builder
WORKDIR /app
# Forward SSH agent for private repos
RUN --mount=type=ssh \
npm install git+ssh://[email protected]/org/private-repo.git
COPY . .
RUN npm run build
Build command:
docker build --ssh default .
Dependency Scanning in Build
# syntax=docker/dockerfile:1.4
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json .=
RUN npm ci
# Scan for vulnerabilities (fail build on high/critical)
RUN --mount=type=cache,target=/root/.cache/trivy \
trivy fs --severity HIGH,CRITICAL --exit-code 1 .
COPY . .
RUN npm run build
Optimizing Layer Caching
Order Matters: Least Changing First
# BAD - source changes invalidate npm install
COPY . .
RUN npm install
# GOOD - package.json changes rarely
COPY package*.json ./
RUN npm install
COPY . .
Use .dockerignore Aggressively
# .dockerignore
.git
.gitignore
README.md
Dockerfile
docker-compose*.yml
*.md
.vscode
.idea
node_modules
dist
build
*.log
.env*
!.env.example
coverage
.nyc_output
*.test.ts
*.spec.ts
__pycache__
.pytest_cache
venv
.env
target
Cargo.lock
Rule: If it is not needed at runtime, exclude it. node_modules in context = slow build + potential version mismatch.
Shared Base Images
# Base image with common tools
FROM alpine:3.19 AS base
RUN apk add --no-cache \
ca-certificates \
tzdata \
curl \
jq \
bash
ENV TZ=UTC
# Service A
FROM base AS service-a
COPY --from=builder /app/service-a /app/service-a
ENTRYPOINT ["/app/service-a"]
# Service B
FROM base AS service-b
COPY --from=builder /app/service-b /app/service-b
ENTRYPOINT ["/app/service-b"]
Build once, deploy multiple:
docker build --target service-a -t myservice-a .
docker build --target service-b -t myservice-b .
Security Hardening in Multi-Stage
Non-Root User (Every Stage)
FROM node:20-alpine AS builder
# Create user in builder too (for build-time security)
RUN addgroup -g 1001 -S appgroup && \
adduser -S appuser -u 1001 -G appgroup
USER appuser
WORKDIR /app
# ... build steps
FROM node:20-alpine AS runner
RUN addgroup -g 1001 -S appgroup && \
adduser -S appuser -u 1001 -G appgroup
USER appuser
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
Read-Only Root Filesystem
FROM alpine:3.19 AS runner
# Create writable directories
RUN mkdir -p /tmp /var/run/app && \
chown -R 1000:1000 /tmp /var/run/app
USER 1000:1000
# Runtime will need --read-only --tmpfs /tmp --tmpfs /var/run/app
Drop Capabilities
# In docker-compose.yml or k8s securityContext
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE # Only if binding < 1024
Distroless Base (Google)
# Instead of alpine/scratch
FROM gcr.io/distroless/nodejs20-debian12 AS runner
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["dist/index.js"]
Benefits: No shell, no package manager, no CVE surface. ~40MB for Node.js.
Debugging Multi-Stage Builds
Inspect Intermediate Stages
# Build up to specific stage
docker build --target builder -t myapp:builder .
# Run builder interactively
docker run -it --rm myapp:builder sh
# Export stage filesystem
docker create --name temp myapp:builder
docker cp temp:/app ./builder-output
docker rm temp
BuildKit Debug Output
# Verbose build with cache info
BUILDKIT_PROGRESS=plain docker build .
# Export build cache for analysis
docker buildx build --cache-to=type=local,dest=/tmp/cache .
Dive Tool (Layer Analysis)
# Install
docker run --rm -it \
-v /var/run/docker.sock:/var/run/docker.sock \
wagoodman/dive:latest myimage:latest
# Shows: layer size, file changes, wasted space
CI/CD Integration
GitHub Actions with Cache
# .github/workflows/docker.yml
name: Docker Build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Cache Docker layers
uses: actions/cache@v4
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max
Layer Caching in GitLab CI
# .gitlab-ci.yml
docker-build:
image: docker:24
services:
- docker:24-dind
variables:
DOCKER_BUILDKIT: 1
script:
- docker buildx create --use
- docker buildx build \
--cache-from=type=registry,ref=$CI_REGISTRY_IMAGE/cache \
--cache-to=type=registry,ref=$CI_REGISTRY_IMAGE/cache,mode=max \
--push \
-t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
Measuring Success
Image Size Targets
| Language | Target Size | Technique |
|---|---|---|
| Go | < 20MB | scratch + static binary |
| Rust | < 20MB | alpine + musl |
| Node.js | < 200MB | alpine + production deps only |
| Python | < 150MB | slim + uv + .venv |
| Java | < 100MB | jlink custom JRE |
| .NET | < 100MB | alpine + trimmed self-contained |
Build Time Targets
| Scenario | Target |
|---|---|
| No cache (fresh) | < 3 minutes |
| Cache hit (deps unchanged) | < 30 seconds |
| Source change only | < 1 minute |
Security Scan
# Trivy (fast, comprehensive)
trivy image --severity HIGH,CRITICAL myimage:latest
# Grype (Syft SBOM + Grype scan)
syft myimage:latest -o spdx-json=sbom.spdx.json
grype sbom:sbom.spdx.json
# Docker Scout (built-in)
docker scout cves myimage:latest
Common Mistakes to Avoid
| Mistake | Fix |
|---|---|
COPY . . before npm install |
Copy package.json first |
Using latest tags |
Pin exact versions: node:20.12.0-alpine3.19 |
| Installing build tools in runtime | Keep tools in builder stage only |
| Running as root | Create non-root user in every stage |
| Secrets in build args | Use --mount=type=secret |
No .dockerignore |
Add comprehensive .dockerignore |
| Single stage for everything | Split: deps -> build -> runtime |
| Not using BuildKit cache mounts | Add --mount=type=cache for package managers |
| Copying entire node_modules | Use separate deps stage with production only |
Migration Checklist
Moving from single-stage to multi-stage:
- [ ] Identify build-time vs runtime dependencies
- [ ] Choose appropriate base images for each stage
- [ ] Add
# syntax=docker/dockerfile:1.4 - [ ] Implement BuildKit cache mounts for package managers
- [ ] Create non-root user in runtime stage
- [ ] Add
.dockerignore - [ ] Test locally:
docker build --target runtime . - [ ] Verify image size:
docker images - [ ] Scan for vulnerabilities:
trivy image - [ ] Update CI/CD to use BuildKit
- [ ] Configure registry cache in CI
- [ ] Test multi-arch if needed
- [ ] Document build arguments and secrets
Summary
Multi-stage builds are not optional for production. The patterns:
- Separate concerns: deps -> build -> runtime
- Cache aggressively:
--mount=type=cachefor every package manager - Minimize runtime: alpine/scratch/distroless, production deps only
- Security by default: non-root, read-only, dropped capabilities
- Measure everything: size, build time, vulnerability count
The Dockerfile is not a script - it is a build specification. Treat it like code: review it, test it, measure it, improve it.