Dev Notes

Docker Multi-Stage Builds for Smaller Images

One of the most effective ways to reduce Docker image size is using multi-stage builds. Instead of shipping your build tools in the final image, you can separate the build and runtime stages.

The Problem

A typical Go application Dockerfile might produce an image over 1GB when using golang:latest as the base:

FROM golang:1.22
WORKDIR /app
COPY . .
RUN go build -o server .
CMD ["./server"]

The Solution

With multi-stage builds, the final image can be under 20MB:

FROM golang:1.22 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o server .

FROM alpine:3.19
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/server /server
CMD ["/server"]

Results

ApproachImage Size
Single stage~1.2 GB
Multi-stage (alpine)~18 MB
Multi-stage (scratch)~8 MB

The difference is dramatic and makes a real impact on deployment speed and storage costs.