Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 41 of 8021. Container FundamentalsFree lesson

Reducing Image Size via Multi-Stage Builds

Utilize multi-stage builds to discard build-time dependencies and produce lean, production-ready images with minimal layer count and footprint.

In this lesson, you will learn how to shrink your production images significantly by using multi-stage builds to discard unnecessary files and build tools.

The "Build vs. Run" Problem

When you build an application, you often need heavy tools like compilers, build kits, and source code. However, once the application is compiled into a binary, these tools are just "dead weight." If you keep them in your final image, you waste space and potentially expose your container to security vulnerabilities.

How Multi-Stage Builds Work

Multi-stage builds allow you to use multiple FROM statements in a single Dockerfile. Each FROM instruction starts a new stage. You use the first stage to "build" your app, and then you "copy" only the final, essential artifacts to the next, much smaller stage.

Consider this example:

# Stage 1: The Build Environment
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o my-app

# Stage 2: The Production Environment
FROM alpine:latest
WORKDIR /root/
# Only copy the binary from the builder stage
COPY --from=builder /app/my-app .
CMD ["./my-app"]

Why This Wins

  1. Discarding Bloat: The golang image is large because it contains a full compiler. By moving the binary to an alpine image (a tiny Linux distribution), you might reduce your image size from hundreds of megabytes to just a few.
  2. Layer Optimization: Since the build tools never exist in the final alpine stage, they don't add to the image's immutable layers.
  3. Security: By stripping out source code and compilers, your production container has a smaller "attack surface," meaning there are fewer tools available for a potential intruder to use if they gain access to your container.

Think of it like a construction crew: you need heavy machinery to build a house, but you don't leave the cranes and concrete mixers inside the living room once the house is finished. The multi-stage build acts as the crew that finishes the job and cleans up after itself.

Key Takeaway: Multi-stage builds allow you to separate your build-time dependencies from your runtime environment, resulting in lean, secure, and production-ready images.