Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
advanced Docker Docker & Containers: From Zero to Production Docker Images Dockerfile Module 2 — Docker Images

Multi-Stage Builds — Dramatically Smaller Images

Reviewed & accurate
AI Summary

What You'll Learn

Beginner

  • What multi-stage builds are and why they matter
  • How to separate build tools from runtime
  • Real examples in Go, Java, and Node.js

The Problem Multi-Stage Solves

Without multi-stage, your production image includes build tools, source code, and temporary artifacts — none needed at runtime.

The Solution: Multiple Stages

A multi-stage Dockerfile has multiple FROM lines. Each FROM starts a new stage. You COPY --from only what you need.

Example: Go Application

Dockerfiledockerfile
# Stage 1: Build
FROM golang:1.21 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o myapp .

# Stage 2: Runtime
FROM alpine:3.18
RUN apk add --no-cache ca-certificates
WORKDIR /app
COPY --from=builder /app/myapp .
CMD ["./myapp"]

Result: ~22 MB image instead of ~800 MB.

Example: Node.js Application

Dockerfiledockerfile
# Stage 1: Build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: Runtime (only production deps)
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/server.js"]

Practical Exercise

Write a single-stage Dockerfile — check the size
Rewrite as multi-stage — compare the size
Run docker images to see the difference
Test that the multi-stage image still works

Key Takeaways

  • Multi-stage builds use multiple FROM lines — each is a new stage.
  • COPY --from=stage copies artifacts between stages.
  • Build in a heavy image, run in a tiny image.
  • Typical size reduction: 10-50x smaller.
  • Name stages with AS for readability.
Previously: Lesson 13 covered best practices.
Today: You learned: Use multiple FROM statements to build tiny production images.
Next: Lesson 15 covers tagging and pushing.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments