GUIDE · GO CONTAINERS · 29 MIN READ
Go in containers in 2026: GOMAXPROCS, GOMEMLIMIT, small images and clean shutdowns
Run Go well in containers: CPU-limit GOMAXPROCS, GOMEMLIMIT from memory.max, distroless images, build info and SIGTERM drains. Tested with Go 1.27.3.
Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

What changes when a Go service runs in a container
A Go binary does not know it is running in a container unless something tells it. The kernel tells it through cgroup files, Kubernetes through signals and probes, and the image through what is and is not on disk. Most production surprises with Go services in containers come from one of those channels being misread: a scheduler sized for every core of a large node inside a two-CPU limit, a heap that grows into an OOM kill because the garbage collector never learned about the memory limit, a TLS call that fails in a scratch image without CA certificates, or a rollout that drops requests because SIGTERM never reached the process.
This guide is the 24 November 2026 edition, researched and first published on 3 December 2026. Everything in it was tested with Go 1.27.3 on darwin/arm64 under gofmt, go vet and go test -race -count=3, and the Linux binaries were cross-compiled from the same module with the same toolchain. The lab tests a cgroup v2 parser against fixture trees, the derivation of GOMEMLIMIT from memory.max, how the runtime reads GOMAXPROCS, GODEBUG and GOMEMLIMIT at startup (in child processes, without asserting the host's CPU count), the probe endpoints, and the whole drain sequence on a fake clock with testing/synctest and the new in-memory httptest server. As of 3 December 2026 the current patch release is Go 1.27.4, released on 10 November 2026 with security fixes, according to the release history; the Dockerfile below uses the official golang:1.27.4-trixie image, and production binaries should be built with 1.27.4. Kubernetes statements refer to the 1.37 documentation; the current patch on the same date is 1.37.3.
One limit on what we can claim: the Docker daemon was not running on the test machine, so we did not build the image. Every size in this guide is measured on a Go binary, never on an image.
The sections follow a service's life: CPU, memory, the image, the build receipt, the signal, the probes, the tests and the manifest. The last section is a checklist you can apply to an existing service the same day.
GOMAXPROCS follows the CPU limit, not the request
Before Go 1.25, GOMAXPROCS defaulted to the number of logical CPUs the process could see, which inside a container is usually every CPU of the node. The Go 1.25 release notes changed two things. On Linux, the runtime considers the CPU bandwidth limit of the cgroup containing the process and, if that limit is lower than the number of logical CPUs, uses it as the default. On every operating system, the runtime periodically updates GOMAXPROCS when the number of logical CPUs or the cgroup limit changes.
The runtime documentation gives the details. The limit is the quota divided by the period, read from cpu.max on cgroup v2 and from cpu.cfs_quota_us and cpu.cfs_period_us on v1. A fractional limit is rounded up, the result is never below 2 unless the machine or the CPU affinity mask offers fewer than two CPUs, and updates happen at most once per second, or less often when the program is idle. The release notes say plainly that in Kubernetes this corresponds to the CPU limit and that the runtime does not consider the CPU request. To notice changes, the runtime keeps file descriptors for the cgroup files open for the life of the process.
The lab mirrors the documented rule in a small function, so a startup log can explain the number the runtime chose:
// ExpectedGOMAXPROCS mirrors the documented Go 1.25+ default on Linux: the
// cgroup CPU limit rounded up, never below 2, and never above the CPUs the
// process may run on. Use it to explain the runtime's choice in a startup
// log; the runtime does not call it.
func ExpectedGOMAXPROCS(ncpu int, cpuLimit float64, limited bool) int {
if !limited {
return ncpu
}
n := max(int(math.Ceil(cpuLimit)), 2)
return min(n, ncpu)
}Its table test pins the edge cases: a 0.5 CPU limit on an 8-CPU node gives 2, a limit of 2.5 gives 3, and a limit of 16 on the same node gives 8. Two details matter in practice. A container limited to one CPU runs with GOMAXPROCS=2, so two busy threads can use up a period's quota in half the period and then wait. And the runtime reads cpu.max of its own cgroup only: in the Go 1.27.3 runtime source a single cpu.max file is opened, so a quota that exists only on a parent cgroup is not considered. The lab's ReadCPULimit reads the same file for that reason, and a fixture where only the Pod's cgroup has a quota reports no limit, as the runtime would.
Setting GOMAXPROCS yourself, through the environment variable or runtime.GOMAXPROCS, disables both the cgroup default and the updates. Go 1.25 added runtime.SetDefaultGOMAXPROCS to return to the default; a lab test starts a child process with GOMAXPROCS set one above the default, calls it, and gets the default back.
The go line decides whether you get the new default
Upgrading the toolchain is not enough. Both behaviours are controlled by GODEBUG settings, containermaxprocs and updatemaxprocs, and the runtime documentation notes that =0 is the default for language version 1.24 and below. As the GODEBUG documentation explains, defaults come from the toolchain, amended to match the Go version in the main module's go.mod, and overridden by //go:debug lines in the main package or, since Go 1.23, by godebug lines in go.mod. A setting in the GODEBUG environment variable overrides all of them.
You can see the result in the binary without running it. We built the lab server with Go 1.27.3 after changing its go line to 1.24:
$ go version -m server | grep DefaultGODEBUG
build DefaultGODEBUG=containermaxprocs=0,cryptocustomrand=1,decoratemappings=0,httpservecontentmaxranges=1,tlssecpmlkem=0,tlssha1=1,tracebacklabels=0,updatemaxprocs=0,urlstrictcolons=0,x509sha256skid=0,x509sslcertoverrideplatform=0Built from the lab's own go 1.27 module, the same server has no DefaultGODEBUG line at all and gets the container-aware default. A binary compiled by Go 1.27 from an old module therefore behaves like Go 1.24 in a container: GOMAXPROCS equals the node's CPU count whatever the limit says. Check the go line of every service before you assume the new behaviour.
The lab's ReadRuntimeSettings resolves both keys the way the runtime does: the environment first, then DefaultGODEBUG from debug.ReadBuildInfo, and within each string the last occurrence wins, so GODEBUG=updatemaxprocs=0,updatemaxprocs=1 means 1. The tests start the test binary again as a child with different environments, and a separate package puts //go:debug containermaxprocs=0 in a test file, which the go command treats as a directive for the test binary, to exercise the DefaultGODEBUG path. Log the resolved values at startup. Do not use the /godebug/non-default-behavior/updatemaxprocs:events metric to detect the setting: in our Go 1.27.3 child processes it stayed at zero even with updatemaxprocs=0. Reading the 1.27.3 source, the runtime tries to count that event while it starts, before the counter is connected, and the increment is dropped.

Requests, limits and what each one does to a Go process
The Kubernetes page on resource management separates the two clearly. The scheduler places a Pod using its requests, and the kubelet reserves at least the requested amount for the container, which may use more when the node has spare capacity. Limits are enforced by the kernel. A CPU limit is a hard ceiling: in each scheduling interval the kernel checks whether the cgroup exceeded it and makes it wait if so. A memory limit is enforced reactively with OOM kills, which happen when the kernel detects memory pressure. A CPU request typically acts as a weight when containers compete for CPU. If you set a limit without a request, and no admission mechanism supplies a default, Kubernetes copies the limit into the request.
For a Go service that gives three situations to plan for:
- A CPU limit is set. The runtime sees it in
cpu.maxand sizesGOMAXPROCSto it. The lab Deployment requests 500m and limits at 2 CPUs, so the process runs withGOMAXPROCS=2on any node. - No CPU limit. Some teams leave CPU unlimited to avoid throttling.
cpu.maxthen readsmax, andGOMAXPROCSis the node's logical CPU count or the affinity mask, however small the request. If that is too much parallelism for the work, setGOMAXPROCSexplicitly. The downward API can exposerequests.cpuas an environment variable; with the default divisor of 1 the kubelet rounds up to a whole number (source at v1.37.3), so 500m becomes 1. That value disables the runtime's updates, and the documentation notes that environment variables are not updated after an in-place resize unless the container restarts. - Memory, always. Nothing in the Go runtime reads
memory.maxby itself. Without a soft limit the collector paces only byGOGC, and the first sign of the container limit is the OOM kill.
The lab manifest sets the memory request equal to the limit. That is a choice, not a rule: the scheduler then reserves everything the process is allowed to use, and the soft limit derived in the next section is based on memory the node has actually set aside for the container.
Derive GOMEMLIMIT from memory.max and leave headroom
GOMEMLIMIT and debug.SetMemoryLimit give the runtime a soft limit. The SetMemoryLimit documentation defines what it covers: memory mapped, managed and not released by the Go runtime, expressed as runtime.MemStats.Sys - runtime.MemStats.HeapReleased. It excludes the space used by the binary, memory allocated by C code, memory mapped with syscall.Mmap and kernel memory held on behalf of the process, and all of that still counts against the container's cgroup. That is why a soft limit equal to 100% of memory.max is wrong: the OOM killer sees the whole cgroup, while the runtime sees only its own part.
The GC guide recommends the memory limit for exactly this deployment, a web service in containers with a fixed amount of memory, and gives a rule of thumb of 5-10% extra headroom for memory sources the runtime is unaware of. The lab takes 10%:
// GoMemLimit returns the soft limit for a container memory ceiling: the
// ceiling minus a headroom fraction for memory the Go runtime does not
// manage (cgo allocations, kernel memory charged to the cgroup, and so on).
func GoMemLimit(ceiling int64, headroom float64) (int64, error) {
if ceiling <= 0 {
return 0, fmt.Errorf("memory ceiling %d: must be positive", ceiling)
}
if !(headroom > 0 && headroom < 1) {
return 0, fmt.Errorf("headroom %v: want a fraction between 0 and 1", headroom)
}
return int64(float64(ceiling) * (1 - headroom)), nil
}
// ApplyMemoryLimit derives the runtime's soft memory limit from the cgroup
// ceiling and passes it to set (debug.SetMemoryLimit in production). An
// explicit GOMEMLIMIT always wins: the runtime has already applied it.
// Outside a cgroup v2 container it changes nothing and returns no error.
func ApplyMemoryLimit(fsys fs.FS, getenv func(string) string, headroom float64,
set func(int64) int64) (MemLimitDecision, error) {
if getenv("GOMEMLIMIT") != "" {
return MemLimitDecision{Source: SourceEnv, Limit: set(-1)}, nil
}
ceiling, err := ReadMemoryCeiling(fsys)
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, ErrNoCgroupV2) {
err = nil // not in a cgroup v2 container, e.g. go run on a laptop
}
if err != nil || !ceiling.Limited {
return MemLimitDecision{Source: SourceNone, Limit: set(-1), Ceiling: ceiling}, err
}
limit, err := GoMemLimit(ceiling.Bytes, headroom)
if err != nil {
return MemLimitDecision{Source: SourceNone, Limit: set(-1), Ceiling: ceiling}, err
}
set(limit)
return MemLimitDecision{Source: SourceCgroup, Limit: limit, Ceiling: ceiling}, nil
}For the lab Deployment's 256 MiB limit, memory.max reads 268435456 and the derived soft limit is 241,591,910 bytes. An explicit GOMEMLIMIT always wins, because the runtime applied it before main ran; ApplyMemoryLimit only reads it back with SetMemoryLimit(-1), and a test proves it does not overwrite it. Outside a container, with no /proc/self/cgroup or only cgroup v1 lines in it, the function changes nothing and returns no error, so go run on a laptop behaves as before.
If you would rather set GOMEMLIMIT in the manifest, mind the units. The runtime accepts a plain number of bytes or the suffixes B, KiB, MiB, GiB and TiB. The lab's child-process test shows both traps:
func TestGOMEMLIMITUnits(t *testing.T) {
if got := mustChild(t, "report", "GOMEMLIMIT=512MiB").MemoryLimit; got != 512<<20 {
t.Errorf("GOMEMLIMIT=512MiB: limit %d, want %d", got, 512<<20)
}
// A bare number is bytes. A downward API value with divisor 1Mi
// would arrive as "512" and leave the runtime 512 bytes.
if got := mustChild(t, "report", "GOMEMLIMIT=512").MemoryLimit; got != 512 {
t.Errorf("GOMEMLIMIT=512: limit %d, want 512 bytes", got)
}
// Kubernetes quantity suffixes are not runtime suffixes: the process
// does not start.
_, stderr, err := child(t, "report", "GOMEMLIMIT=512Mi")
if err == nil || !strings.Contains(stderr, "malformed GOMEMLIMIT") {
t.Errorf("GOMEMLIMIT=512Mi: err %v, stderr %q; want a startup failure", err, stderr)
}
}A Kubernetes quantity such as 512Mi stops the process at startup with "malformed GOMEMLIMIT", and a downward API value with divisor: 1Mi arrives as a bare 512, which the runtime reads as 512 bytes.
The guide is equally clear about when not to use the limit: not to escape OOM kills when a program already runs close to its environment's limit, which trades an OOM risk for a severe slowdown, and not together with GOGC=off when the program shares its memory with other processes. If the limit is set too low, the collector caps its own CPU use at roughly 50% over a 2 * GOMAXPROCS CPU-second window and lets memory exceed the limit rather than stall the program. Our GOGC and GOMEMLIMIT lab measures how the limit changes collection frequency. Go 1.26 made the Green Tea collector the default (release notes); the memory limit API is unchanged.
The lab also reads memory.high, which the kernel documentation describes as a throttle limit: above it the cgroup's processes are throttled and put under heavy reclaim pressure, without an OOM kill. The lower of the two values becomes the ceiling. Kubernetes writes memory.high only when Memory QoS throttling is configured. The feature is beta and enabled by default in 1.37, but its memoryThrottlingFactor now defaults to null, so the kubelet sets no memory.high unless an operator asks for it (Kubernetes blog).

Read cgroup files through fs.FS and test them with fixtures
Reading /sys/fs/cgroup/memory.max directly works in the common case and silently fails in others. The process's cgroup is listed in /proc/self/cgroup, where the cgroup v2 entry is the line that starts with 0::. Inside a private cgroup namespace that line is 0::/, and the container's own cgroup is mounted at /sys/fs/cgroup. In the host's namespace the line holds the full path, such as a cri-containerd-<id>.scope directory under the Pod's slice, and the limit may sit on an ancestor instead of the leaf. The kernel creates memory.max only in non-root cgroups, so the root has none.
The lab therefore walks from the process's cgroup up to the mount point, reads memory.max and memory.high at each level, skips missing files and keeps the lowest number. Memory and CPU are treated differently on purpose: the OOM killer acts at whichever level a limit is reached, so for memory the lowest ancestor matters, while for GOMAXPROCS the lab reports only what the runtime itself reads.
Every reader takes an fs.FS rooted at /. Production code passes os.DirFS("/"), and the tests pass directories under testdata, so no test ever reads the host's /proc or /sys:
func TestReadMemoryCeilingFixtures(t *testing.T) {
tests := []struct {
fixture string
want MemoryCeiling
}{
{"k8s-namespaced", MemoryCeiling{Bytes: 256 << 20, Limited: true, File: "/sys/fs/cgroup/memory.max"}},
{"unlimited", MemoryCeiling{}},
{"host-view", MemoryCeiling{Bytes: 512 << 20, Limited: true,
File: "/sys/fs/cgroup/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod7f3c.slice/memory.max"}},
{"memory-high", MemoryCeiling{Bytes: 966367641, Limited: true, File: "/sys/fs/cgroup/memory.high"}},
{"escaped", MemoryCeiling{Bytes: 128 << 20, Limited: true, File: "/sys/fs/cgroup/memory.max"}},
}
for _, tt := range tests {
t.Run(tt.fixture, func(t *testing.T) {
got, err := ReadMemoryCeiling(os.DirFS("testdata/" + tt.fixture))
if err != nil {
t.Fatal(err)
}
if got != tt.want {
t.Errorf("got %+v, want %+v", got, tt.want)
}
})
}
}The fixtures cover a namespaced container with 256 MiB, an unlimited one, a host view where only the Pod slice carries a 512 MiB limit, a memory.high below memory.max, and a /proc/self/cgroup path that escapes the namespace (0::/../.., where the lab falls back to the mount point). Further tests cover a cgroup v1 file, which yields ErrNoCgroupV2, and a malformed value, which is an error rather than a guess. Restricting the reader to the process's own directory made the host-view case fail, which is exactly the regression the walk exists to prevent.
The parser handles cgroup v2 only. Kubernetes moved cgroup v1 support into maintenance mode in 1.31, and since 1.35 the kubelet's failCgroupV1 setting defaults to true, so the kubelet does not start on a cgroup v1 node unless an administrator overrides it (Kubernetes blog). If you run containers outside Kubernetes, check your hosts before you drop a v1 code path you still need.
Follow an in-place resize
In-place Pod resize has been stable since Kubernetes 1.35: the CPU and memory requests and limits of a running container can change through the Pod's resize subresource, without recreating the Pod. The two runtime settings react differently. GOMAXPROCS follows a new CPU limit by itself, since the runtime checks for changes up to once per second, unless you set it manually. The soft memory limit does not: nothing in the runtime re-reads memory.max, and a GOMEMLIMIT injected through the environment stays fixed for the life of the container.
The lab server re-derives the limit once a minute when it came from the cgroup:
// WatchMemoryLimit calls apply every interval until ctx is done and reports
// each change. The runtime refreshes its GOMAXPROCS default when the CPU
// limit changes, but nothing re-reads memory.max after an in-place resize
// unless the program does it.
func WatchMemoryLimit(ctx context.Context, every time.Duration, last int64,
apply func() (MemLimitDecision, error), changed func(MemLimitDecision, error)) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
d, err := apply()
if err != nil || d.Limit != last {
changed(d, err)
last = d.Limit
}
}
}
}The test runs inside a testing/synctest bubble against a file system whose memory.max changes from 256 MiB to 512 MiB between two ticks. After the first fake minute nothing is reported; after the second, the watcher reports exactly one change, to 483,183,820 bytes, and the last SetMemoryLimit call carries that value. A mutation that skipped the re-read failed with no change reported.
A minute is our choice of interval, not a recommendation from either project. Growing a limit is the easy case. Shrinking it below what the process already uses is a capacity decision, and no watcher can make that safe after the fact, so test it the way you would test any other change to a memory budget.
A multi-stage Dockerfile for a static binary
Multi-stage builds keep the toolchain in one stage and copy only the result into the next. This is the lab's Dockerfile:
# syntax=docker/dockerfile:1
# Build stage: runs on the builder's own platform and cross-compiles.
FROM --platform=$BUILDPLATFORM golang:1.27.4-trixie AS build
WORKDIR /src
# With dependencies, copy go.sum too and add
# RUN --mount=type=cache,target=/go/pkg/mod go mod download
# so this layer is reused until go.mod or go.sum change.
COPY go.mod ./
COPY . .
ARG TARGETOS TARGETARCH
ARG VERSION=dev
RUN --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath -ldflags="-s -X main.version=${VERSION}" \
-o /out/server ./cmd/server
# Runtime stage: CA certificates, tzdata, /tmp and a nonroot user, no shell.
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/server /server
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/server"]The build stage runs on the builder's native platform (--platform=$BUILDPLATFORM) and cross-compiles with the TARGETOS and TARGETARCH arguments that BuildKit sets for each target, which Docker's multi-platform guide recommends over emulation for compute-heavy steps such as compilation. The cache mount keeps the Go build cache between builds on the same builder. The Dockerfile reference notes that cache mounts are not exported with --cache-to, so a CI job on a fresh machine starts with an empty cache. Pin both base images by digest once you have tested them; tags move.
Each build flag has a job. CGO_ENABLED=0 produces a static binary that needs no libc in the image and removes the host C toolchain as an input to the build. -trimpath replaces file system paths with module paths and import paths. -ldflags=-s omits the symbol table and debug information; the linker documentation for Go 1.27 says that -s implies -w, so -s -w is redundant. Stripping costs you debugger symbols and nm output, not stack traces: a stripped test program still printed main.crash with its file and line when it panicked. -X main.version=... writes the release version into a string variable that the server logs at startup.
We cross-compiled the server with exactly these flags under Go 1.27.3 and measured the files: 7,200,928 bytes for linux/amd64 and 6,684,832 bytes for linux/arm64. Without -s, the amd64 binary was 10,407,606 bytes. These are binary sizes. The image adds the distroless base layers, and we did not build it, so we do not quote an image size.
What distroless and scratch take away
The runtime stage uses gcr.io/distroless/static-debian13:nonroot. According to the distroless project, the static image contains CA certificates, an /etc/passwd entry for root, a /tmp directory and tzdata, and the nonroot tag runs as UID 65532. There is no shell, package manager or libc. The images are based on Debian 13 and tagged with a -debian13 suffix; reference it explicitly, because the project says an image without the suffix will move to a newer Debian release in the future.
FROM scratch is smaller still and gives up each of those pieces, so each one needs a decision:
- CA certificates. On Linux,
crypto/x509loads the system roots from the first bundle it finds in a fixed list of files, starting with/etc/ssl/certs/ca-certificates.crt, and honoursSSL_CERT_FILEandSSL_CERT_DIR. In scratch none of those files exist, and verification of every public TLS certificate fails. Copy the bundle from the build stage to that path, or import golang.org/x/crypto/x509roots/fallback, a separate module that embeds a root set for when the operating system provides none; its documentation asks you to keep it up to date. - Time zones.
time.LoadLocationsearches theZONEINFOvariable, the system zoneinfo directories,$GOROOT/lib/time/zoneinfo.zipand finally the copy embedded bytime/tzdata. In scratch only the last can succeed. The package documentation puts its cost at about 450 KB and says to import it from the main package, or to build with-tags timetzdata. The lab server imports it; without the import, the stripped amd64 binary was 413,696 bytes smaller. - A non-root user. scratch has no
/etc/passwd, so use a numericUSER. Kubernetes cares: whenrunAsNonRootis set withoutrunAsUser, the kubelet refuses to start an image whose user is a name, because it cannot verify that the name is not root (kubelet source at v1.37.3). The lab sets bothUSER 65532:65532andrunAsUser: 65532. - A writable /tmp. Code that calls
os.CreateTemp("", ...)needs one. WithreadOnlyRootFilesystem: true, mount anemptyDirvolume there.
Working without a shell also changes operations. kubectl exec has no sh to run, distroless publishes :debug and :debug-nonroot tags with a busybox shell for investigations, and an exec preStop hook that calls sleep fails because there is no sleep binary. The section on signals shows what to use instead.
Build information is the receipt inside the binary
Every Go binary carries its build information, and go version -m prints it without running the program; Go 1.25 added -json for tools. We built the server with the Dockerfile's flags from a scratch Git repository tagged v1.0.0:
$ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -ldflags="-s -X main.version=1.0.0" -o server ./cmd/server
$ go version -m server
server: go1.27.3
path gopherforge.app/lab/gocontainer/cmd/server
mod gopherforge.app/lab/gocontainer v1.0.0
build -buildmode=exe
build -compiler=gc
build -trimpath=true
build CGO_ENABLED=0
build GOARCH=amd64
build GOOS=linux
build GOAMD64=v1
build vcs=git
build vcs.revision=04f10fa27476c357c89a717939f3c660d2f57e1b
build vcs.time=2026-12-03T10:00:00Z
build vcs.modified=falseSince Go 1.24, go build sets the main module's version from the VCS tag or commit and appends +dirty when there are uncommitted changes; a rebuild after editing one file reported v1.0.0+dirty and vcs.modified=true. The vcs settings appear only when the build can see the repository. The lab's .dockerignore excludes .git, as most do, so a build inside the image records (devel) and no revision; our build from a directory without Git showed exactly that. This is why the Dockerfile passes VERSION through -X main.version and the server logs it.
One flag is missing from that output: -ldflags. With -trimpath, the go command deliberately leaves linker flags out of the build information because they can contain system paths (cmd/go source at go1.27.3). Record the injected version somewhere else as well, such as an image label or your release notes.
The same flags make the binary reproducible. The Go blog post on reproducible toolchains states that for programs that do not need cgo, a reproducible build is as simple as CGO_ENABLED=0 go build -trimpath. We built the linux/amd64 server from two different directories: with -trimpath both files had the SHA-256 digest beginning 16c01453, and without it the two digests differed. The image is a separate artifact with its own timestamps. Docker's reproducible builds page recommends pinning base images by digest and setting the SOURCE_DATE_EPOCH build argument, plus the rewrite-timestamp exporter option to normalise file timestamps inside the layers.
SIGTERM reaches process 1, so make process 1 your binary
When a Pod is deleted, the kubelet runs any preStop hook and then has the container runtime send SIGTERM to process 1 in each container. When the grace period runs out, 30 seconds by default, the runtime sends SIGKILL to whatever is still running; a hook that is still running at that moment gets a single 2-second extension (Pod termination). The lifecycle hook documentation adds that the countdown starts before the hook runs, so the hook and the shutdown share one budget.
Process 1 must therefore be your Go binary. The Dockerfile reference warns that the shell form of ENTRYPOINT runs the command as a subcommand of /bin/sh -c, which does not pass signals, so the executable is not PID 1 and never receives the SIGTERM from docker stop. Use the exec form, ENTRYPOINT ["/server"]; a lab test fails if anyone changes it, and distroless has no shell to wrap the command anyway.
In the program, signal.NotifyContext turns SIGTERM into context cancellation, and since Go 1.26 the context's cause names the signal. The lab's real-signal test asserts that context.Cause reads "terminated signal received" and still matches context.Canceled, and the server logs that cause when it stops. The drain itself is short:
// Drain is the shutdown budget. Delay plus Timeout, plus any preStop hook,
// must fit inside the Pod's terminationGracePeriodSeconds.
type Drain struct {
Delay time.Duration // keep serving after the signal while routes update
Timeout time.Duration // upper bound for http.Server.Shutdown
}
// DefaultDrain matches deploy/deployment.yaml: the preStop sleep covers the
// routing delay, so the process itself does not wait before draining.
var DefaultDrain = Drain{Delay: 0, Timeout: 20 * time.Second}
// Shutdown fails readiness, keeps serving for Delay, then lets in-flight
// requests finish within Timeout and closes whatever is left.
func (d Drain) Shutdown(srv *http.Server, h *Health) error {
h.SetReady(false)
time.Sleep(d.Delay)
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
return errors.Join(fmt.Errorf("drain: %w", err), srv.Close())
}
return nil
}Ownership of workers, the order of closing dependencies and why the drain needs a fresh context instead of the cancelled signal context are covered in our graceful shutdown guide. A mutation that passed the cancelled signal context to Shutdown made the lab's SIGTERM test fail with context canceled while a request was still in flight.
The container-specific part is the delay. At the same time as the kubelet starts the shutdown, Kubernetes marks the deleted Pod's endpoints as terminating and not ready, and proxies and load balancers act on that change on their own schedule, so the process should keep serving for a few seconds. Sleep in a preStop hook or in the process, not both, since the two add up. An exec hook that runs sleep needs a binary distroless does not have; the built-in sleep action has been stable since Kubernetes 1.34 and needs nothing from the image. The lab uses the hook in its manifest and keeps a DRAIN_DELAY variable, zero by default, for platforms without hooks.
Probes that tell the truth
The three probes answer three different questions (probe documentation). A failing readiness probe makes the EndpointSlice controller remove the Pod's IP from every matching Service. A failing liveness probe restarts the container. A startup probe holds the other two back until it succeeds, for containers that start slowly. The documentation warns that liveness must indicate an unrecoverable failure such as a deadlock; a poorly chosen one restarts containers under load and spreads the failure to the remaining Pods.
The lab keeps both endpoints narrow. /healthz answers 200 as long as the process can serve HTTP and checks no dependencies, so a slow database never causes a restart loop. /readyz returns 503 until Run has started serving and again from the first moment of shutdown. The documentation also notes that draining on deletion does not strictly need a readiness probe, because Kubernetes marks a terminating endpoint as not ready by itself; the flip still helps any proxy or client that probes the Pod directly, and it makes the shutdown state visible in tests.
A service that needs a dependency to do useful work can report that on /readyz, never on /healthz. The manifest probes readiness every 5 seconds and restarts only after three failed liveness checks 10 seconds apart; a probe's timeout should stay well below its period. Add a startup probe when cold start regularly takes longer than the liveness probe tolerates, rather than inflating initialDelaySeconds.
Test the drain on a fake clock
Shutdown code is usually tested with sleeps or not at all. Go 1.27 makes a better test cheap: httptest.NewTestServer serves over an in-memory network suitable for testing/synctest, and synctest.Sleep advances the bubble's clock and then waits until every other goroutine is blocked (Go 1.27 release notes). This is the lab's timeout test:
func TestDrainTimeoutClosesStuckRequests(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
h := &Health{}
mux := http.NewServeMux()
mux.HandleFunc("GET /stream", func(_ http.ResponseWriter, r *http.Request) {
<-r.Context().Done() // never finishes on its own
})
ts := httptest.NewTestServer(t, mux)
start := time.Now()
clientErr := make(chan error, 1)
go func() {
resp, err := ts.Client().Get("http://example.com/stream")
if err == nil {
resp.Body.Close()
}
clientErr <- err
}()
synctest.Wait()
err := Drain{Delay: 5 * time.Second, Timeout: 20 * time.Second}.Shutdown(ts.Config, h)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Shutdown = %v, want context.DeadlineExceeded", err)
}
if elapsed := time.Since(start); elapsed != 25*time.Second {
t.Errorf("gave up after %v, want exactly delay + timeout = 25s", elapsed)
}
if err := <-clientErr; err == nil {
t.Error("stuck request completed normally; want a closed connection")
}
})
}Inside the bubble the clock moves only when every goroutine is durably blocked, so the drain gives up after exactly 25 seconds of fake time, the stuck request's connection is closed, and the test reports 0.00s of real time. Two companion tests show that probes are still answered during a 5-second delay, with /readyz at 503, and that an 8-second request admitted before shutdown completes with its body while Shutdown returns less than a second after it. One behaviour of the in-memory network differs from TCP: after the listener closes, a new request is left unanswered instead of refused, so the tests bound such requests with a one-second context.
A second file sends a real SIGTERM to the test process with syscall.Kill, after signal.NotifyContext has registered, and orders every step with channels on a loopback listener taken from httptest.NewUnstartedServer. Mutations show what each test guards: removing the delay made the probe request time out, removing the forced Close left the stuck client blocked until synctest reported a deadlock, and shortening the grace period to 20 seconds failed the manifest test described next. Each of the eleven mutations we tried failed at least one test, and the unmodified lab passed go test -race -count=3 and go test -count=20.
Deploy it, then work through the checklist
The manifest ties the pieces together:
apiVersion: apps/v1
kind: Deployment
metadata:
name: gocontainer
labels:
app: gocontainer
spec:
replicas: 2
selector:
matchLabels:
app: gocontainer
template:
metadata:
labels:
app: gocontainer
spec:
# preStop sleep (5s) + drain timeout (20s) must fit, with margin.
terminationGracePeriodSeconds: 30
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: server
image: registry.example.com/gocontainer:1.0.0
ports:
- name: http
containerPort: 8080
resources:
requests:
cpu: 500m
memory: 256Mi
limits:
cpu: "2"
memory: 256Mi
readinessProbe:
httpGet:
path: /readyz
port: http
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 10
failureThreshold: 3
lifecycle:
preStop:
sleep:
seconds: 5
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]A test reads this file and fails if the preStop sleep plus the drain delay and timeout do not fit below terminationGracePeriodSeconds (5 + 0 + 20 = 25 seconds against 30), or if the port, probe paths or non-root settings drift from the code. Replace the image name before applying it to a real cluster. To practise without one, paste the manifest into the simulated cluster of the browser terminal and run kubectl apply -f and kubectl rollout status against it; nothing there touches a real cluster. The Kubernetes course covers Deployments, probes and rollouts step by step.
Before the next release of a containerised Go service, check:
- The main module's
goline is 1.25 or later, andgo version -mshows nocontainermaxprocs=0inDefaultGODEBUG. GOMAXPROCSis not set in the manifest unless you mean it, because setting it stops the automatic updates.- The soft memory limit comes from the container ceiling with 5-10% headroom, any explicit
GOMEMLIMITuses runtime suffixes such asMiB, and the startup log shows both values. - If Pods are resized in place, something re-reads the memory limit.
- The image has CA certificates, tzdata or
time/tzdata, a numeric non-root user and an exec-formENTRYPOINT. - The build uses
CGO_ENABLED=0and-trimpath, base images are pinned by digest, and the version is recorded somewhere other than-ldflags. - The
preStopsleep plus the drain delay and timeout stay below the grace period, and a test says so. - Liveness checks no dependencies, and readiness turns to 503 on SIGTERM.
The gocontainer folder in the lab archive contains the module, the cgroup fixtures, the Dockerfile and the manifest. Run go test -race -count=3 ./... inside it, then change the ENTRYPOINT to shell form and watch a test fail.
Primary sources & editorial method
We checked these primary references on 3 December 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.
- Go 1.25 Release Notes
- Go 1.24 Release Notes
- Go 1.26 Release Notes
- Go 1.27 Release Notes
- Go release history
- Package runtime: GOMAXPROCS
- Package runtime/debug: SetMemoryLimit
- A Guide to the Go Garbage Collector
- Go, Backwards Compatibility, and GODEBUG
- internal/runtime/cgroup/cgroup_linux.go at go1.27.3
- cmd/go/internal/load/pkg.go at go1.27.3
- Perfectly Reproducible, Verified Go Toolchains (The Go Blog)
- Command go
- Command link
- Package time/tzdata
- Package golang.org/x/crypto/x509roots/fallback
- Kubernetes: Resource Management for Pods and Containers
- Kubernetes: Pod termination
- Kubernetes: Container Lifecycle Hooks
- Kubernetes: Liveness, Readiness, and Startup Probes
- Kubernetes: Downward API
- Kubernetes feature gates
- Kubernetes releases
- Kubernetes v1.37: Memory QoS Graduates to Beta
- The Shift to cgroup v2 in Kubernetes: What You Need to Know
- Kubernetes downward API value conversion at v1.37.3
- Kubernetes kubelet runAsNonRoot check at v1.37.3
- Linux kernel: Control Group v2
- Dockerfile reference
- Docker: Multi-stage builds
- Docker: Multi-platform builds
- Docker: Reproducible builds
- GoogleContainerTools/distroless