Skip to Content
Skip to content
Go Advanced: Performance, Concurrency, and Production
Advanced
Courses
Go Advanced: Performance, Concurrency, and Production

Ship a Multi-Stage Scratch Go Container

Build a static Go binary in golang:trixie and copy only the binary, CA certificates, and non-root user into FROM scratch. After this, your production image is tiny and has no shell.

Course content

Sign in to save your progress.

Course Home

Shipping a Go binary inside a golang:1.27-trixie image works locally—and leaves you deploying an ~850 MB container full of compilers, shells, and dozens of OS CVEs. A multi-stage build into FROM scratch shrinks that entire container image down to ~6–15 MB so Kubernetes pods pull in ~200 ms instead of 30 seconds.

Yet the first time most teams switch to FROM scratch, two things fail immediately in staging: outbound HTTPS calls crash with x509: certificate signed by unknown authority, and security policies block the container for running as root (UID 0).

Skip ahead

If you already build static CGO_ENABLED=0 binaries, copy ca-certificates.crt into FROM scratch, run as numeric USER 65532:65532, and know how to handle tzdata and healthchecks without a shell, take the section quiz or move on to "Fuzz Testing Parsers and Decoders With go test -fuzz."

Experiment 1: Measuring what the scratch container actually needs

First verify a minimal Go program that checks x509.SystemCertPool() and prints its runtime UID, compiled statically inside golang:trixie:

package main

import (
	"crypto/x509"
	"fmt"
	"os"
)

func main() {
	pool, err := x509.SystemCertPool()
	if err != nil {
		fmt.Println("cert_pool_err:", err)
	} else {
		fmt.Println("cert_pool_ok:", pool != nil)
	}
	fmt.Printf("uid=%d\n", os.Getuid())
}
$ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -trimpath -o app .
$ ls -lh app
-rwxr-xr-x 1 root root 2.9M Nov 27 13:31 app
$ ./app
cert_pool_ok: true
uid=0
$ ls -lh /etc/ssl/certs/ca-certificates.crt
-rw-r--r-- 1 root root 217K Nov 24 04:39 /etc/ssl/certs/ca-certificates.crt

Look at those two numbers: the entire static binary is only 2.9 MB, and the Debian root CA bundle is only 217 KB! Together they fit inside a ~3.1 MB container image with zero shell and zero OS packages.

Experiment 2: The complete multi-stage FROM scratch Dockerfile

Notice why every single line in stage 2 is there:

FROM golang:1.27-trixie AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
    go build -ldflags="-s -w" -trimpath -o /out/app ./cmd/server

FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /out/app /app
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/app"]
  • COPY go.mod go.sum before COPY . .: Keeps Docker's build cache warm for go mod download whenever only your .go source changes.
  • COPY --from=builder /etc/ssl/certs/ca-certificates.crt ...: Gives Go's crypto/x509 trusted root CAs so outbound HTTPS calls verify TLS certificates cleanly.
  • USER 65532:65532 (numeric, not named): Because scratch has no /etc/passwd, Docker cannot resolve a username like USER nonroot—passing numeric UID/GID 65532:65532 works cleanly everywhere.
  • Exec-form ENTRYPOINT ["/app"]: Shell-form ENTRYPOINT /app tries to invoke /bin/sh -c /app, which does not exist in scratch (and swallows SIGTERM!).

Experiment 3: Timezones (tzdata) and healthchecks without a shell

Two extra production surprises appear in FROM scratch once your service grows:

  • time.LoadLocation("America/New_York") fails because scratch has no /usr/share/zoneinfo. Fix it in one line by adding import _ "time/tzdata" in main.go, which embeds the IANA timezone database directly inside your binary!
  • HEALTHCHECK CMD wget ... fails because scratch has no wget or curl. Either use Kubernetes HTTP readiness probes directly, or add a 5-line -healthcheck flag to your Go binary so HEALTHCHECK CMD ["/app", "-healthcheck"] runs self-contained.

Experiment 4: When distroless beats scratch

If your service requires CGo (dynamically linked C libraries like SQLite C bindings) or you want CA certificates, /etc/passwd, and timezone files pre-installed with zero boilerplate, Google's gcr.io/distroless/static-debian12:nonroot (or base-debian12:nonroot for glibc) gives you almost the exact same minimal CVE surface as scratch with slightly less Dockerfile plumbing.

Common mistakes

  • Forgetting CGO_ENABLED=0: Dynamically links against glibc in the builder stage, then crashes at startup in scratch with exec /app: no such file or directory.
  • Trying to bind port 80 or 443 as USER 65532: Unprivileged users cannot bind ports under 1024 by default—listen on :8080 and let your reverse proxy or load balancer terminate TLS on 443.
  • Setting InsecureSkipVerify: true to "fix" missing CA certs: Disables TLS verification completely and opens outbound API calls to man-in-the-middle attacks.

💡 Tip

Pair USER 65532:65532 with a read-only root filesystem (--read-only in Docker or readOnlyRootFilesystem: true in Kubernetes). Static Go services that write logs to stdout rarely need any writable filesystem at all.

What happens if you skip this step

Shipping full golang images inflates registry costs, slows autoscaling cold starts by 10–30 seconds, and adds dozens of OS CVEs; shipping FROM scratch without CA certs passes local HTTP checks and crashes on the very first outbound HTTPS request in staging.

Your FROM scratch container runs fine locally against an HTTP mock server, then fails in staging with x509: certificate signed by unknown authority. What single file is missing from the final stage?

About

Build a static Go binary in golang:trixie and copy only the binary, CA certificates, and non-root user into FROM scratch. After this, your production image is tiny and has no shell.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.