Sub topic 10
Example: a static Go binary in a minimal image
This chapter builds a small Go service into a minimal image, step by step. It assumes you can write a basic Go program, run containers with docker run, and read a Dockerfile. You should also know the multi-stage syntax from earlier chapters: FROM ... AS and COPY --from.
Why Go suits multi-stage builds
Go compiles to a single executable file. At runtime that file needs no Go toolchain, no package manager and no source code. The official golang image is large because it carries the compiler, the standard library sources and build tools. Those are only needed while compiling.
A multi-stage build uses that fact directly. The first stage compiles. The final stage starts from an empty image and receives only the binary.
A small program to build
Use a minimal HTTP server so you have something to run. Create main.go:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello from a small image")
})
log.Println("listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}Create the module files:
go mod init example.com/appThis program uses only the standard library, so go mod init produces a go.mod file and no go.sum. The Dockerfile below copies go.sum too, so it fails if that file is missing. Create an empty one with touch go.sum if your project has no dependencies. Once you add a dependency, Go fills the file in.
The Dockerfile
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/app .
FROM scratch
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]This assumes the app needs no CA certificates or other files at runtime. The sections below cover what to do when that assumption fails.
The build stage, line by line
FROM golang:1.22 AS buildstarts from the full Go image and names the stagebuild. Later stages and--targetrefer to this name.WORKDIR /srcsets the directory for the following instructions and creates it if needed.COPY go.mod go.sum ./copies only the dependency manifests. Because they change rarely, the layer is cached across most builds.RUN go mod downloadfetches the dependencies. This layer is rebuilt only whengo.modorgo.sumchanges.COPY . .copies the rest of the source. This layer changes on almost every edit, so it comes after the dependency layers.RUN CGO_ENABLED=0 go build ...compiles the program.
The order of these lines applies the cache rule from the earlier chapter: put what changes least first. If you wrote COPY . . before go mod download, every source edit would re-download all dependencies.
Why `CGO_ENABLED=0`
By default, Go can link against the C library (cgo) when a package needs it. The net package, for example, can use the system resolver through cgo. A binary built that way is dynamically linked and expects libc at runtime. Inside scratch there is no libc, and the container fails at start with an error like exec /app: no such file or directory. The message is misleading. The file exists, but the dynamic loader it needs does not.
Setting CGO_ENABLED=0 makes Go use its pure-Go implementations and produce a statically linked binary. That binary has no outside library dependencies and runs on an empty image.
Why `-ldflags="-s -w"`
These linker flags strip the symbol table (-s) and DWARF debug information (-w). The binary gets smaller, often by 25 to 30 percent. The cost is that you lose debugger symbols. Stack traces from panics still show function names and line numbers, because Go keeps that data separately for its runtime.
The final stage
FROM scratch is a reserved name for an empty image. It has no shell, no package manager and no files. COPY --from=build /out/app /app pulls the single file out of the build stage. ENTRYPOINT ["/app"] uses the exec form (a JSON array), which is required here because scratch has no /bin/sh to interpret a shell-form command.
Build and compare
These commands build the final image and the build stage separately, then compare them.
docker build -t myapp:small .
docker build --target build -t myapp:build .
docker image ls myapp
docker history myapp:smallThe second command uses --target build to stop after the named stage. That gives you an image that includes the toolchain, which serves as the "before" measurement.
Typical output looks like this. Exact numbers depend on your Go version and code.
| Image | Approximate size | What it contains |
|---|---|---|
| `myapp:build` | 800 MB to 1 GB | Go toolchain, OS packages, source, binary |
| `myapp:small` | 4 to 8 MB | The binary only |
docker history myapp:small shows very few layers. The COPY layer carries nearly all the size. The ENTRYPOINT layer adds zero bytes because it only records metadata.
Run it to confirm it works:
docker run --rm -p 8080:8080 myapp:smallIn another terminal, run curl http://localhost:8080/. You should see hello from a small image.
What scratch does not give you
An empty image is also missing things your program may quietly need. Three gaps appear most often.
CA certificates
If the program makes HTTPS requests, it must verify server certificates against a trusted root list. scratch has none, so calls fail with x509: certificate signed by unknown authority. Copy the bundle from the build stage:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/app .
FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The Debian-based golang image ships with this bundle, so the copy works. This adds about 200 KB.
Time zone data
time.LoadLocation("Europe/Berlin") reads files from /usr/share/zoneinfo, which does not exist in scratch. You can copy that directory, or embed the data into the binary by importing time/tzdata in your code. The embed option adds roughly 450 KB and removes the file dependency.
A user other than root
With scratch there is no /etc/passwd, so there is no named user. A later chapter covers running as non-root in detail. For now, note that you can still set a numeric user with USER 65532:65532. Docker accepts numeric IDs without needing a passwd entry.
Choosing between scratch and distroless
scratch gives the smallest result but leaves you to add every supporting file yourself. A distroless static image such as gcr.io/distroless/static-debian12 already includes CA certificates, time zone data, a minimal /etc/passwd and a nonroot user. It adds only a couple of megabytes.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/app .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]| Choice | Size added | CA certs | Time zones | Non-root user | Best when |
|---|---|---|---|---|---|
| `scratch` | 0 | No | No | Numeric ID only | The app needs nothing beyond its binary |
| `distroless/static` | about 2 MB | Yes | Yes | Yes (`nonroot`) | The app makes HTTPS calls or uses time zones |
For most services that call outside APIs, distroless static saves time with a small cost in size.
Common errors
exec /app: no such file or directory: the binary is dynamically linked. SetCGO_ENABLED=0, or switch to a base image that haslibc. You can check a binary withfileorlddon the build machine.COPY failed: file not found: the path in--from=builddoes not match wherego build -owrote the file. Keep the two paths identical.- Slow rebuilds after tiny edits:
COPY . .is placed beforego mod download, or.dockerignoreis missing and unrelated files change the context. - Wrong architecture: building on an ARM machine and running on x86 gives
exec format error. Pass--platform linux/amd64todocker build, or setGOARCHfor the build.
Review
The key choices in this example are:
- Copy
go.modandgo.sumfirst so dependency downloads are cached. - Set
CGO_ENABLED=0so the binary is static and can run withoutlibc. - Strip symbols with
-ldflags="-s -w"to shrink the binary. - Copy only the binary into the final stage.
- Add CA certificates and time zone data, or use distroless static, when the app needs them.
Exercise
Your Go service builds into a FROM scratch image without errors. When you run it, it exits at once with exec /app: no such file or directory, although /app exists in the image. What is the likely cause, and what change fixes it?
Show answer
The binary is dynamically linked, probably because cgo was enabled by default. It needs a dynamic loader and libc, which scratch does not contain, so the kernel cannot start it. Build with CGO_ENABLED=0 in the build stage's go build command to produce a statically linked binary. Alternatively, use a base image that includes libc.
Exercise
The same service now starts, but every outbound HTTPS call fails with x509: certificate signed by unknown authority. Give two ways to fix this without adding a shell or a package manager to the final image.
Show answer
First, copy the CA bundle from the build stage with COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ in the final stage. Second, change the final base image to gcr.io/distroless/static-debian12, which already contains CA certificates.
Exercise
Why does the Dockerfile copy go.mod and go.sum and run go mod download before COPY . .?
Show answer
Dependency files change rarely and source files change often. Docker invalidates the cache from the first changed layer onward. With the manifests copied first, editing a source file leaves the go mod download layer cached, so dependencies are not downloaded again.