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.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
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.sumbeforeCOPY . .: Keeps Docker's build cache warm forgo mod downloadwhenever only your.gosource changes.COPY --from=builder /etc/ssl/certs/ca-certificates.crt ...: Gives Go'scrypto/x509trusted root CAs so outbound HTTPS calls verify TLS certificates cleanly.USER 65532:65532(numeric, not named): Becausescratchhas no/etc/passwd, Docker cannot resolve a username likeUSER nonroot—passing numeric UID/GID65532:65532works cleanly everywhere.- Exec-form
ENTRYPOINT ["/app"]: Shell-formENTRYPOINT /apptries to invoke/bin/sh -c /app, which does not exist inscratch(and swallowsSIGTERM!).
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 becausescratchhas no/usr/share/zoneinfo. Fix it in one line by addingimport _ "time/tzdata"inmain.go, which embeds the IANA timezone database directly inside your binary!HEALTHCHECK CMD wget ...fails becausescratchhas nowgetorcurl. Either use Kubernetes HTTP readiness probes directly, or add a 5-line-healthcheckflag to your Go binary soHEALTHCHECK 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 inscratchwithexec /app: no such file or directory. - Trying to bind port
80or443asUSER 65532: Unprivileged users cannot bind ports under1024by default—listen on:8080and let your reverse proxy or load balancer terminate TLS on443. - Setting
InsecureSkipVerify: trueto "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
Comments
Sign in to commentNo comments yet.