Multi-stage Docker builds for Go applications¶
Multi-stage builds are a Docker feature used to optimize the final image size for compiled languages like Go^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]. This technique involves using multiple FROM statements in a single Dockerfile to create separate build stages, allowing artifacts to be copied from one stage to another while discarding unnecessary files^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
Build Stages¶
A typical Go Dockerfile defines distinct stages for compilation and runtime^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
- Builder Stage: Uses a full Go image (e.g.,
golang:1.18-rc-alpine) to provide the necessary toolchain for compiling the application source code into a binary executable^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]. - Runtime Stage: Uses a minimal base image (e.g.,
alpine:3.15.0-rc.4) and copies only the compiled binary from the builder stage^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
Implementation¶
The following Dockerfile demonstrates this workflow, defining a builder stage named builder and using COPY --from=builder to transfer the artifact^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
FROM golang:1.18-rc-alpine as builder
WORKDIR /
COPY . .
RUN go mod tidy
RUN go build -o main
FROM alpine:3.15.0-rc.4
WORKDIR /
COPY --from=builder /main .
EXPOSE 8080
ENTRYPOINT ["./main"]
In this configuration, the builder stage utilizes the Go toolchain to compile the source, whereas the final runtime stage relies on COPY --from=builder to include only the finished application binary^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
Sources¶
^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]