C.W.K.
Stream
Lesson 04 of 06 · published

Multi-Stage Builds — Build Big, Ship Small

~18 min · dockerfile, size

Level 0Container Curious
0 XP0/36 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Why a multi-stage build exists

You usually need a fat toolchain to build (compilers, build tools, dev dependencies) but a slim runtime to ship. Multi-stage builds give you both in one Dockerfile.

You declare multiple FROM stages. Each can use a different base image. COPY --from=<stage> pulls files from an earlier stage into a later one. Only the last stage becomes the final image.

The classic Node example

Stage 1 has Node + npm + your source + node_modules + a build tool that produces dist/. Stage 2 has only nginx + the dist/ folder. Final image: ~25MB. Single-stage equivalent: ~1.2GB.

Code

Node → static site·dockerfile
# Stage 1: build
FROM node:22-alpine AS builder
WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build
# /app/dist now contains the production assets

# Stage 2: serve (the only stage that becomes the final image)
FROM nginx:1.27-alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

# Final image: ~25MB. The 1.2GB builder stage is discarded.
Python with a compiled dependency·dockerfile
FROM python:3.12 AS builder
WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends gcc libpq-dev
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt

FROM python:3.12-slim AS runtime
WORKDIR /app
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH
COPY . .
CMD ["python", "main.py"]

# Build tools stay in the builder. Runtime gets only the installed packages.

External links

Exercise

Take any Node or Go project. Write a single-stage Dockerfile and note the final image size. Convert it to multi-stage and note the new size. Capture both Dockerfiles and the size diff. (Hint: docker images myapp shows sizes.)

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.