A build stage lets a Dockerfile compile an application without putting the compiler in the finished image. It starts with a FROM instruction, often named with AS, and uses an image containing the required build tools. A later stage copies in the compiled output. section 4.1 section 4.5
For a Go application, the steps are:
- Start a builder stage from diamol/golang:2e, which contains the Go tools. Copy in go.mod and main.go, then run go build -o /server. section 4.4
- Start the final stage from the smaller diamol/base:2e image. Use COPY --from=builder to bring in /server; the Go tools stay behind. Mark the binary executable on Linux. section 4.4
Listing 4.4 Dockerfile for building a Go application from source
FROM diamol/golang:2e AS builder
COPY go.mod main.go /go/
RUN go build -o /server
# app
FROM diamol/base:2e
ENV IMAGE_API_URL="http:/./iotd/image" \
ACCESS_API_URL="http:/./accesslog/access-log"
CMD ["/web/server"]
WORKDIR web
COPY index.html .
COPY --from=builder /server .
RUN chmod +x server
The complete Go Dockerfile shows the builder and application stages together, including the startup command and files served by the app. section 4.4
Build and compare the images
From ch04/exercises/image-gallery, run docker image build -t image-gallery . The example’s application image is 35.1 MB, compared with 230 MB for its Go toolset image. The build tools do not need to travel with the application. section 4.4 section 4.5
Stages are isolated: only files explicitly copied into the final stage appear there. A failed command fails the build. The same pattern also works for a .NET Framework application: restore dependencies and compile with an SDK image, then copy the output into an ASP.NET runtime image. Each stage has its own build cache, so instruction order also matters when tuning repeat builds. section 4.1 section 4.5 section 13.3

