How to Build a Minimal Docker Image for Go (scratch, distroless, alpine)

Build a minimal Go Docker image by compiling a static binary in a builder stage and running it in a scratch image.

Use a multi-stage Dockerfile to compile your Go binary with CGO disabled, then copy it into a scratch image for the smallest possible footprint. This approach avoids the overhead of Alpine or distroless while ensuring the binary is statically linked and self-contained.

FROM golang:1.23-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

FROM scratch
COPY --from=builder /app/main .
CMD ["./main"]