How to Build Ultra‑Small Go Docker Images with Multi‑Stage & Scratch
This tutorial explains how to use Docker's build‑time features, layer minimization, multi‑stage builds, and the scratch base to create lightweight, secure, and fast Go container images, demonstrating each step with clear code examples and performance comparisons.
Docker offers powerful build‑time features and minimal base images that enable lightweight, secure, and efficient application builds.
This article shows why Go is ideal for demonstrating these features because it compiles to a single binary.
We start with a very simple main.go program and a minimal Dockerfile that uses a single layer.
Minimize layers for maximum efficiency: best practices
Dockerfile documentation recommends reducing the number of layers. Each instruction creates a new layer that is hashed and cached; fewer layers mean faster builds and smaller images, which is crucial for CI/CD pipelines.
Group related steps, place frequently‑changing parts low in the file, and keep static dependencies higher up.
Run the application as a non‑root user using RUN adduser … and USER.
FROM golang:alpine
RUN mkdir /app
ADD . /app/
WORKDIR /app
RUN go build -o main .
RUN adduser -S -D -H -h /app appuser
USER appuser
CMD ["./main"]The resulting image is about 378 MB.
Next step: multi‑stage builds
Multi‑stage builds let you compile in a builder stage and copy only the final binary into a tiny runtime image.
FROM golang:alpine as builder
RUN mkdir /build
ADD . /build/
WORKDIR /build
RUN go build -o main .
FROM alpine
RUN adduser -S -D -H -h /app appuser
USER appuser
COPY --from=builder /build/main /app/
WORKDIR /app
CMD ["./main"]This reduces the image size to 6.16 MB.
Build from scratch for the smallest image
By statically linking the Go binary and using the scratch base, the final image contains only the executable, around 2 MB.
FROM golang:alpine as builder
RUN mkdir /build
ADD . /build/
WORKDIR /build
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o main .
FROM scratch
COPY --from=builder /build/main /app/
WORKDIR /app
CMD ["./main"]Running the three images shows the same output “Hello Cloudreach!”.
Conclusion
By applying layer‑minimization, multi‑stage builds, and scratch images, Go applications can be containerized into extremely small, fast, and secure Docker images.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
