Module 6 Lesson 1: Multi-Stage Builds
Shrink your images by 90%. Learn the multi-stage build pattern to separate your 'Build Environment' (compilers, tools) from your 'Runtime Environment' (app only).
Module 6 Lesson 1: Multi-Stage Builds
One of the biggest problems with simple Dockerfiles is Image Bloat. To build a Java or Go app, you need a compiler (like Maven or the Go SDK) which can be 500MB. But to run the app, you only need the tiny binary file.
Multi-stage builds allow you to "Discard" the heavy tools once the build is done.
1. The Single Stage Problem (Heavy)
FROM golang:1.19
COPY . .
RUN go build -o main .
CMD ["./main"]
# Result: Image size is 800MB because it includes the entire Go SDK.
2. The Multi-Stage Solution (Light)
We use the AS keyword to name our stages.
# STAGE 1: Build
FROM golang:1.19 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp .
# STAGE 2: Runtime
FROM alpine:latest
WORKDIR /root/
# Copy ONLY the compiled binary from the 'builder' stage
COPY --from=builder /app/myapp .
CMD ["./myapp"]
# Result: Image size is 15MB!
3. Why This is Better
- Size: Your images are much smaller, meaning they download faster to your production servers.
- Security: Your production image doesn't contain a compiler or your source code. If a hacker breaks in, they can't easily rebuild your app or find secrets in your source.
- Efficiency: You can have different "Builders" for different parts of your app (e.g., one stage for CSS, one for Go) and combine them in the final stage.
4. Multi-Stage for Frontend (React/Vue/Angular)
This is the standard way to deploy modern web apps.
# Stage 1: Build the React app
FROM node:18 AS build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Stage 2: Serve with Nginx
FROM nginx:alpine
COPY --from=build-stage /app/dist /usr/share/nginx/html
# Nginx ignores all the node_modules and source code!
Exercise: The Shrinking Act
- Find a Dockerfile for a compiled language (C++, Java, Rust, or Go).
- Check its image size:
docker images. - Rewrite it using a multi-stage approach.
- Hint: Use a heavy image for the first
AS builderstage and aslimoralpineimage for the final stage.
- Hint: Use a heavy image for the first
- Compare the results. What % of size did you save?
- Why is "Security" mentioned as a benefit of smaller images? (Research: "Attack surface reduction").
Summary
Multi-stage builds are a "Cheat Code" for professional Docker developers. They allow you to maintain a clean development environment without sacrificing production performance or security.
Next Lesson: Speeding up the loop: Optimized layer order.