A base image is the starting point for building a container image. It supplies an existing layer—such as an operating system or language runtime—so the application image can be assembled on top of it. section 7.6 section 7.4
Choose a base image according to the image’s purpose:
- Use a language image such as golang:1.18 when the build needs Go and its tooling. section 7.6
- Use scratch for a minimal runtime image when a compiled binary has no external libraries to install. section 7.6
- Remember that each added layer can increase image size and security vulnerabilities, so development and production images may use different stages. section 7.6
One Dockerfile, two purposes
A multistage Dockerfile can start with FROM golang:1.18 AS deps, build a development image from that stage, then start a production stage with FROM scratch and copy only the compiled API binary into it. The resulting dev image contains build support, while the min image is substantially smaller. section 7.6
Listing 7.3 Dockerfile
FROM golang:1.18 AS deps #1
WORKDIR /hello-api #2
ADD *.mod *.sum ./
RUN go mod download #3
FROM deps as dev #4
ADD . . #5
EXPOSE 8080
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags "-w -X main.docker=true" \
-o api cmd/main.go #6
CMD ["/hello-api/api"]
FROM scratch as prod #7
WORKDIR /
EXPOSE 8080
COPY --from=dev /hello-api/api / #8
CMD ["/api"]
Inspect the complete multistage Dockerfile to see how dependency installation, development tooling, compilation, and the scratch-based production image fit together. section 7.6






