BudiBadu Logo
Samplebadu

Dockerfile by Example: Multi Stage Build Layout

Docker Engine 20.10+

Multi-stage builds allow you to use a heavy image for building and a light image for running. This sample code demonstrates how to compile a Go app and ship only the binary.

Code

# Stage 1: Builder
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o myapp main.go

# Stage 2: Runner
FROM alpine:latest
WORKDIR /root/
# Copy only the binary from the builder stage
COPY --from=builder /app/myapp .
CMD ["./myapp"]

Explanation

Multi-stage builds enable the use of multiple FROM instructions in a single Dockerfile, where each instruction starts a new build stage. This pattern allows you to copy artifacts from one stage to another, discarding the intermediate build environment. The primary benefit is the ability to separate build-time dependencies (compilers, SDKs, build tools) from runtime dependencies, resulting in drastically smaller final images.

In the first stage, named builder, a full Go SDK image is used to compile the application. This stage contains heavy tools necessary for compilation but unnecessary for execution. The second stage starts fresh with a minimal alpine image. The COPY --from=builder instruction extracts only the compiled binary from the previous stage, leaving behind the source code, caches, and compiler toolchain.

This approach significantly reduces the attack surface of the production image by excluding unnecessary software and files. It also simplifies the build process by consolidating everything into a single Dockerfile, eliminating the need for external build scripts or separate Dockerfiles for build and production environments. BuildKit can also execute independent stages in parallel, potentially speeding up the build process.

Code Breakdown

2
AS builder names the stage for later reference in COPY instructions.
10
FROM alpine:latest starts the final, minimal release image.
13
COPY --from=builder extracts only the binary artifact from the build stage.
7
RUN go build ... compiles the code within the isolated builder environment.