✦ For everyone, free.

Practical knowledge for real and everyday life

Home

12.2.4 Go Docker Workflow

A focused guide to Go Docker Workflow, connecting core concepts with practical Docker and container operations.

The Go Docker workflow takes particular advantage of Go's compilation model, producing a single, statically linked binary that can run in an extremely minimal final image — often without any traditional Linux distribution at all — making Go one of the most favorable languages for producing genuinely minimal container images.

The Basic Multi-Stage Go Build

A build stage compiles the Go application; the final stage simply copies the resulting binary into a minimal (or even empty) base.

FROM golang:1.22 AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server .

FROM scratch
COPY --from=build /app/server /server
ENTRYPOINT ["/server"]
Why CGO_ENABLED=0 Matters for True Static Linking

Disabling CGo ensures the resulting binary has no dynamic dependency on the C standard library, producing a genuinely self-contained, statically linked executable.

CGO_ENABLED=0 go build -o server .
ldd server
not a dynamic executable

This confirms the binary has no external dynamic library dependencies, meaning it can run correctly even in an image with absolutely nothing else present.

Why FROM scratch Is a Viable, Extreme Minimalism Option for Go

The scratch base image contains literally nothing — no shell, no libraries, no package manager — viable specifically because a properly built, statically linked Go binary needs nothing else to actually run.

docker images
myapp-go-scratch   8MB
Why Dependency Caching Still Matters for Go Builds

Copying go.mod and go.sum before the full source code, then running go mod download, allows this potentially slow step to be cached separately from compilation.

COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o server .
Why the Go Docker Workflow Matters

Go's compilation model, producing a single, statically linked binary, makes it uniquely well-suited to producing extremely minimal, secure container images, and understanding this specific workflow unlocks a level of image minimalism not as straightforwardly achievable with many other languages.

Content in this section