Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 147 ยท Advanced Go

Containerizing and Deploying Go Apps

Package a Go service in a tiny container with a multi-stage Dockerfile, a scratch or distroless image, health checks, graceful SIGTERM handling and environment-based configuration.

Go has an unusual advantage for deployment: go build produces one self-contained executable. No interpreter, no virtual machine, no node_modules. That makes Go the best-behaved citizen of the container world. A finished image can be 10 to 20 MB instead of several hundred, it starts in milliseconds, and it has almost nothing in it that an attacker could use.

This lesson walks from source code to a production-ready image: the build flags that make a static binary, a multi-stage Dockerfile, choosing between scratch, distroless and Alpine, health checks that work when the image has no shell, and the application-side habits (configuration from the environment, graceful shutdown on SIGTERM) that orchestrators such as Docker, Kubernetes and Cloud Run expect. The Dockerfile blocks are read-only because this page cannot run a Docker daemon, but all the Go code runs in your browser. If Docker is new to you, the Docker tutorial covers the basics, and its Go recipe is a good companion.

Build a static binary first

A container image is just files. The smallest possible image contains exactly one file: your program. That works only if the program needs nothing else at run time, which means it must not load shared C libraries. Two settings guarantee that:

Terminal
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o app ./cmd/app
  • CGO_ENABLED=0 turns off cgo, so the linker produces a fully static binary that does not depend on glibc. (Some standard-library packages, notably net and os/user, switch to pure-Go implementations automatically.)
  • -trimpath removes your local directory names from the binary, which makes builds reproducible and avoids leaking paths.
  • -ldflags="-s -w" strips the symbol table and debug information, typically saving 25 to 30 percent of the file size. You lose symbolized profiles from the stripped binary, so keep an unstripped build if you rely on them.

You can also cross-compile: GOOS=linux GOARCH=arm64 go build ... produces a Linux ARM binary on a laptop of any kind. See tooling basics.

The multi-stage Dockerfile

The compiler and your source code are needed to build, not to run. A multi-stage Dockerfile uses one image for building and copies only the result into a second, minimal image.

flowchart LR
    SRC["Source + go.mod"] --> B["Stage 1: golang image<br/>download modules, compile"]
    B -->|"COPY --from=build /out/app"| R["Stage 2: scratch<br/>one binary + CA certificates"]
    R --> IMG["Final image ~10 MB"]

Only what you explicitly copy from the build stage reaches the final image. The compiler, the module cache and the source stay behind.

DOCKERFILE
# syntax=docker/dockerfile:1

FROM golang:1.27 AS build
WORKDIR /src

# Copy only the module files first so this layer is cached
# until dependencies change.
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download

COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/app ./cmd/app

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /out/app /app
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/app"]

Why each part is there:

  • Copy go.mod and go.sum before the rest. Docker caches each instruction as a layer. As long as those two files are unchanged, go mod download is reused, and editing a .go file only repeats the compile step.
  • Cache mounts keep the module cache and the build cache between builds on the same machine, so incremental builds take seconds.
  • FROM scratch is an empty image. Nothing exists in it but what you copy in.
  • CA certificates. If your program makes HTTPS calls, it needs a bundle of trusted root certificates to verify servers. scratch has none, so we copy the build image's bundle.
  • USER 65532:65532 runs the program as an unprivileged user (a number is fine; scratch has no /etc/passwd). A compromised process then cannot write to most places or bind privileged ports.
  • Exec-form ENTRYPOINT ["/app"] (a JSON array) runs your binary as process 1 directly, so it receives SIGTERM itself. The string form would wrap it in /bin/sh -c and the shell would swallow the signal. scratch has no shell anyway.

Add a .dockerignore listing .git, local binaries and *.md, so COPY . . does not send junk to the build context.

Choosing the base image

Base Size Has a shell Good for
scratch 0 MB No Static binaries; smallest and most locked down
gcr.io/distroless/static ~2 MB No Static binaries, with CA certificates, timezone data and a non-root user already included
gcr.io/distroless/base ~20 MB No Binaries that need glibc (cgo builds)
alpine ~8 MB Yes (sh) When you want to docker exec in and debug; uses musl libc
debian:stable-slim ~75 MB Yes cgo programs that need a normal glibc environment

For a first deployment, distroless static is the most comfortable: you get certificates, /etc/passwd with a nonroot user and timezone files without having to copy them. Pick scratch when you want the absolute minimum and are happy to copy what you need. Pick Alpine when the team values a shell for debugging more than the smaller attack surface.

Time zones: scratch has no /usr/share/zoneinfo, so time.LoadLocation("Europe/Berlin") fails. Either copy the directory from the build stage or add import _ "time/tzdata" to your program, which embeds the database (about 450 KB) into the binary. See working with time.

Configuration comes from the environment

A container image should be identical in staging and production. What differs, such as the port, database address and log level, arrives through environment variables, a convention from the Twelve-Factor App. Go reads them with os.LookupEnv. Putting the parsing in one function with a lookup parameter keeps it testable, because a test can pass a map instead of touching the real environment.

Go Config from the environment, health endpoints and a probe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both programs on this page start with //go:debug httpmuxgo121=0, which switches on the method patterns (GET /healthz) for a single file compiled without a go.mod; inside a module that declares go 1.22 or newer, leave that line out.

Notice the split between two kinds of check. A liveness check answers "is the process alive?" and should almost never fail; if it does, the platform restarts the container. A readiness check answers "should I receive traffic right now?" and legitimately flips to failing while the app warms up its caches or drains before shutdown. Mixing them up causes restart loops: a database blip must make the pod unready, not kill it.

Health checks without curl

Docker has a HEALTHCHECK instruction, and Kubernetes has probes (httpGet, tcpSocket, exec). With Kubernetes or Cloud Run, the platform makes the HTTP call itself and your image needs nothing extra. For plain Docker or Compose, HEALTHCHECK runs a command inside the container, and a scratch image has no curl. The solution is to teach your own binary a healthcheck mode, like the probe function above:

Go
func main() {
	if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
		os.Exit(probe("http://127.0.0.1:8080/healthz"))
	}
	// ... start the server
}
DOCKERFILE
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD ["/app", "healthcheck"]

Docker marks the container unhealthy after three failures in a row. Compose can then wait for it with depends_on: condition: service_healthy; see Compose health dependencies and the HEALTHCHECK lesson.

Graceful shutdown on SIGTERM

When a platform stops a container it sends SIGTERM, waits a grace period (10 seconds in Docker, 30 in Kubernetes by default), then sends SIGKILL. A good Go service uses that window to finish what it started. The sequence is:

sequenceDiagram
    participant P as Platform
    participant A as App
    participant L as Load balancer
    P->>A: SIGTERM
    A->>A: readiness = false
    L->>A: GET /readyz (503)
    Note over L: stops sending new requests
    A->>A: wait a short drain delay
    A->>A: srv.Shutdown(ctx): finish in-flight requests
    A-->>P: exit 0

Flip readiness first so the load balancer stops routing traffic, then let in-flight requests finish.

signal.NotifyContext turns the signal into a cancelled context, which composes nicely with everything else you have learned about context. The example below simulates the signal by cancelling the context by hand, so it behaves identically in the browser:

Go The SIGTERM shutdown sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Three rules to remember. Always give Shutdown a timeout shorter than the platform's grace period, so you exit by yourself instead of being killed. Make main return after run returns so deferred cleanup (closing database pools, flushing logs) happens. And log to stdout/stderr rather than files: the runtime collects container output for you (see logging).

Production details worth knowing

  • Tag images with the Git commit or a semantic version, never rely on latest in deployments.
  • Embed the version at build time: -ldflags="-X main.version=$(git describe --tags)" sets a string variable your /version endpoint can return.
  • Memory limits. The runtime sizes its heap from the machine, not the container. Set GOMEMLIMIT to roughly 90 percent of the container limit so the garbage collector works harder before the kernel kills you; see garbage collection. Recent Go versions also adapt GOMAXPROCS to the container's CPU limit.
  • Scan and sign. Run an image scanner in CI. A scratch image has little to find, but your Go dependencies still can have vulnerabilities, so run govulncheck ./... as covered in vet and linting.
  • Multi-platform. docker buildx build --platform linux/amd64,linux/arm64 builds one image tag for both Intel and ARM servers; see multi-platform builds.
  • Secrets such as passwords belong in the platform's secret store, passed as environment variables or mounted files, never baked into layers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a multi-stage build produce a smaller final image?

    Each FROM starts a new image. The build stage can be huge, but the final stage contains only what you copy into it, such as the static binary and CA certificates.
  2. 2. What does CGO_ENABLED=0 give you?

    Without cgo the linker produces a static executable and the net package uses its pure-Go resolver. That is what allows the binary to run in an image with no libraries at all.
  3. 3. A scratch-based image cannot run HEALTHCHECK CMD curl -f http://localhost:8080/healthz. What is the usual fix?

    scratch has no shell or curl. A few lines of Go in your own binary do the probe, and the HEALTHCHECK instruction runs it in exec form.
  4. 4. What should the app do first when it receives SIGTERM?

    Failing readiness tells the load balancer to stop sending new requests. Shutdown with a timeout then lets running requests complete before the process exits.

Summary

  • Build with CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" to get a small static binary.
  • A multi-stage Dockerfile compiles in a golang image and copies the binary into scratch or distroless; copy go.mod first and use cache mounts for fast rebuilds.
  • Run as a non-root user, use exec-form ENTRYPOINT, and copy CA certificates (and time zone data) when you need them.
  • Read configuration from environment variables; keep liveness and readiness separate and give the binary a healthcheck mode.
  • Handle SIGTERM with signal.NotifyContext, flip readiness, and call Shutdown with a timeout shorter than the platform's grace period.

Next: Go and WebAssembly.