Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 111 ยท Language Recipes

Containerizing Go and Rust Apps

Containerize Go and Rust apps with multi-stage builds: static binaries, scratch and distroless images, module and crate caching, cross compilation, and pitfalls.

Go and Rust have a gift for Docker: they compile to a single native executable. If that executable does not depend on any shared libraries, your final image can contain nothing but the program. No operating system, no shell, no package manager. The finished image is often smaller than the compiler's own installer, and a Go web server fits in about 8 MB.

This recipe shows the pattern for both languages: build in a big image that has the toolchain, then copy the binary into an almost empty image. You will see what makes a binary "static", how to cache dependencies so rebuilds take seconds, when scratch is a bad idea and distroless is better, how to cross-compile for another CPU, and the traps (a missing /bin/sh, missing certificates, ignored SIGTERM) that bite people the first time. If multi-stage builds are new to you, read Multi-Stage Builds first.

The mental model: compile here, run there

TEXT
   Stage 1: build                         Stage 2: runtime
 +----------------------+              +-------------------+
 | golang:1.25-alpine   |   COPY       | scratch (empty)   |
 | compiler, std lib,   |  --from=     |                   |
 | module cache, source | -----------> |  /server          |
 | (337 MB)             |  one file    |  (the whole image)|
 +----------------------+              +-------------------+
        thrown away                         what you ship

Only the last stage becomes the image. Everything in stage 1 (compiler, sources, caches) stays behind in the build cache. For this to work, the binary must run without the files that stage 1 had: above all, it must not need a dynamic loader or a C library at run time.

Go: a static binary on scratch

Here is the small web server used in this lesson. It answers on / and /health, reads its address from ADDR, and shuts down cleanly when it receives SIGTERM:

Go
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	addr := ":8080"
	if v := os.Getenv("ADDR"); v != "" {
		addr = v
	}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello from Go in a container")
	})
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	srv := &http.Server{Addr: addr, Handler: mux}

	go func() {
		log.Printf("listening on %s", addr)
		if err := srv.ListenAndServe(); err != http.ErrServerClosed {
			log.Fatal(err)
		}
	}()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
	<-stop
	log.Println("shutting down")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_ = srv.Shutdown(ctx)
}

And the Dockerfile:

DOCKERFILE
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY go.mod ./
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/server .

FROM scratch
COPY --from=build /out/server /server
EXPOSE 8080
ENTRYPOINT ["/server"]

Every line has a job:

  • COPY go.mod ./ before the sources: the module list changes rarely, so the go mod download layer stays cached while you edit code. With a go.sum you would copy both files together.
  • --mount=type=cache keeps Go's module cache and build cache between builds, even when a layer is invalidated. See BuildKit and buildx.
  • CGO_ENABLED=0 tells Go not to link against the C library. This is the switch that makes the binary fully static. Without it, anything using net or os/user may be linked to glibc or musl and fail on scratch.
  • -trimpath removes your build directory from the binary (reproducible, nothing leaked) and -ldflags="-s -w" strips the symbol table and debug information, shaving a few megabytes.
  • FROM scratch is the empty image. ENTRYPOINT uses the exec form because there is no shell to interpret a string.

Build it and run it:

CONSOLE
$ docker build -t hello-go .
$ docker run -d --name hello-go -p 127.0.0.1:8080:8080 hello-go
c82abbcb1fae
$ curl -s 127.0.0.1:8080/
Hello from Go in a container
$ curl -s 127.0.0.1:8080/health
ok
$ docker logs hello-go
2026/10/23 15:15:12 listening on :8080

Now the size comparison. The image docker build --target build would give you (the stage that has the whole toolchain) against the shipped image:

CONSOLE
$ docker images --format '{{.Repository}} {{.Size}}'
hello-go-full 337MB
hello-go 8.03MB

Roughly 40 times smaller, and the layer history shows why: there is exactly one real layer, the binary.

CONSOLE
$ docker history hello-go
IMAGE          CREATED         CREATED BY                            SIZE      COMMENT
2d777ebbce65   2 minutes ago   ENTRYPOINT ["/server"]                0B        buildkit.dockerfile.v0
<missing>      2 minutes ago   EXPOSE [8080/tcp]                     0B        buildkit.dockerfile.v0
<missing>      2 minutes ago   COPY /out/server /server # buildkit   5.62MB    buildkit.dockerfile.v0

Sizes depend on the Go version, the packages you import and your platform. Importing net/http alone adds several megabytes. What matters is the order of magnitude: megabytes, not hundreds of megabytes.

What caching buys you

The first build compiled the standard library and your code from scratch. Change one line of main.go and rebuild: the go mod download layer is reused, and the cache mount means Go recompiles only what changed.

CONSOLE
$ echo "// tweak" >> main.go
$ docker build -t hello-go . 2>&1 | grep -E "CACHED|DONE"
#6 CACHED
#7 CACHED
#8 CACHED
#9 DONE 0.9s
#10 DONE 2.2s

The go build step took 2.2 seconds, against 48.9 seconds for the very first, cold build on the same machine. Without the cache mounts, a changed source file would trigger the full 48 seconds again, because the layer cache can only reuse a step whose inputs are unchanged.

Go: the traps of an empty image

scratch is empty in the literal sense. Compare the shell tools you take for granted:

CONSOLE
$ docker exec hello-go ls
OCI runtime exec failed: exec failed: unable to start container process: exec: "ls": executable file not found in $PATH
$ docker exec hello-go sh
OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH

No ls, no sh, no curl, no ps. That is a security feature (an attacker who gets in finds no tools) and an operational headache. For debugging you can run a helper container that shares the network namespace or use docker cp to inspect files; see Debugging Containers.

Four more things your program may silently expect and not find on scratch:

  1. TLS root certificates. Calling any https:// API fails with x509: certificate signed by unknown authority. Copy them from the build stage: COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/. (The golang:1.25-alpine build stage has that file; a plain alpine stage needs apk add ca-certificates first.)
  2. Time zone data. time.LoadLocation("Europe/Berlin") fails without /usr/share/zoneinfo. Either copy the zoneinfo directory from a stage that has it, or import time/tzdata in your program to embed the data.
  3. A user other than root. scratch has no /etc/passwd. You can still say USER 65532:65532 with a numeric ID, which Docker accepts.
  4. A writable /tmp. If your program calls os.CreateTemp, add a tmpfs or a volume (see tmpfs and In-Memory Storage).

Distroless: scratch with the basics included

If you do not want to assemble those pieces by hand, use a distroless base image. It contains only the files a static binary usually needs (certificates, time zones, /etc/passwd with a nonroot user) and still has no shell.

DOCKERFILE
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY go.mod ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server .

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
EXPOSE 8080
ENTRYPOINT ["/server"]

The :nonroot tag makes the process run as UID 65532 automatically:

CONSOLE
$ docker run -d --name hello-go-dl -p 127.0.0.1:8081:8080 hello-go-dl
$ docker top hello-go-dl -o user,pid,comm
USER                PID                 COMMAND
65532               59253               server

The cost is about 6 MB more than scratch (14.2 MB against 8.03 MB in our build). For most production services that is an excellent trade. More on choosing: Choosing a Base Image.

Rust: musl makes it static

Rust's standard toolchain links your program against the system C library by default. On Debian-based images that means glibc (a dynamic dependency). On Alpine it means musl, and the rust:alpine image builds a statically linked executable out of the box. That is the simplest route to a scratch image.

Our sample app uses one dependency, ctrlc, so the build has something to cache:

TOML
[package]
name = "hello"
version = "0.1.0"
edition = "2024"

[dependencies]
ctrlc = { version = "3", features = ["termination"] }

[profile.release]
strip = true
lto = true
codegen-units = 1
Rust
use std::io::{Read, Write};
use std::net::TcpListener;
use std::process;

fn main() {
    let addr = std::env::var("ADDR").unwrap_or_else(|_| "0.0.0.0:8080".to_string());

    ctrlc::set_handler(|| {
        println!("shutting down");
        process::exit(0);
    })
    .expect("failed to install the signal handler");

    let listener = TcpListener::bind(&addr).expect("cannot bind");
    println!("listening on {addr}");

    for stream in listener.incoming() {
        let mut stream = match stream {
            Ok(s) => s,
            Err(_) => continue,
        };
        let mut buf = [0u8; 1024];
        let n = stream.read(&mut buf).unwrap_or(0);
        let request = String::from_utf8_lossy(&buf[..n]);
        let body = if request.starts_with("GET /health") {
            "ok\n"
        } else {
            "Hello from Rust in a container\n"
        };
        let response = format!(
            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        let _ = stream.write_all(response.as_bytes());
    }
}

(A real service would use a framework such as axum; the standard library keeps this example short.) The Dockerfile:

DOCKERFILE
FROM rust:alpine AS build
WORKDIR /src
COPY Cargo.toml Cargo.lock* ./
COPY src ./src
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/src/target \
    cargo build --release && cp target/release/hello /hello

FROM scratch
COPY --from=build /hello /hello
EXPOSE 8080
ENTRYPOINT ["/hello"]

Two details matter here. The target directory is a cache mount, so it will not exist in the layer afterwards; that is why the same RUN copies the binary out to /hello before the mount disappears. And Cargo.lock* copies the lock file when you have one (always commit it for applications, so builds are reproducible).

CONSOLE
$ docker build -t hello-rust .
#9 0.574     Updating crates.io index
#9 1.718  Downloading crates ...
#9 3.627    Compiling libc v0.2.191
#9 14.74    Compiling hello v0.1.0 (/src)
#9 23.06     Finished `release` profile [optimized] target(s) in 22.64s
$ docker images hello-rust --format '{{.Size}}'
757kB

An image of 757 kB, built from a 1.39 GB toolchain image. After editing src/main.rs, only the final crate is rebuilt, because the dependencies already sit in the cached target directory:

CONSOLE
$ docker build -t hello-rust . 2>&1 | grep -E "Compiling|Finished"
#9 4.070    Compiling hello v0.1.0 (/src)
#9 15.55     Finished `release` profile [optimized] target(s) in 14.74s

The 14.7 seconds are mostly link-time optimization (lto = true); drop it while iterating if you value speed over size.

Run it and stop it

CONSOLE
$ docker run -d --name hello-rust -p 127.0.0.1:8080:8080 hello-rust
$ curl -s 127.0.0.1:8080/
Hello from Rust in a container
$ docker stop hello-rust
hello-rust
$ docker logs hello-rust
listening on 0.0.0.0:8080
shutting down
$ docker inspect -f '{{.State.ExitCode}}' hello-rust
0

It stopped in under two seconds with exit code 0, because the ctrlc crate (with its termination feature) handles SIGTERM.

Your program runs as PID 1 inside the container. On Linux, PID 1 ignores a signal that has no handler, so a Rust program without a SIGTERM handler does not stop on docker stop; Docker waits ten seconds and then sends SIGKILL. Always install a handler (as above), or start the container with --init. Go's runtime is more forgiving, but if you want graceful shutdown (finishing requests), you need signal.Notify as in our example. Details in Signals, PID 1 and --init.

When the binary is not static

The most common failure for newcomers: they build with a glibc toolchain (for example golang on Debian with cgo enabled, or rust:latest) and copy the result onto scratch. The kernel then cannot find the interpreter the binary asks for, and the error message is misleading. Here is the same mistake made with a binary we know is dynamic, Alpine's busybox:

DOCKERFILE
FROM alpine:3 AS src
FROM scratch
COPY --from=src /bin/busybox /busybox
ENTRYPOINT ["/busybox", "echo", "hi"]
CONSOLE
$ docker run --rm dyn-test
exec /busybox: no such file or directory
$ docker run --rm --entrypoint "" alpine:3 sh -c 'ldd /bin/busybox | head -3'
	/lib/ld-musl-x86_64.so.1 (0x7b92533a3000)
	libc.musl-x86_64.so.1 => /lib/ld-musl-x86_64.so.1 (0x7b92533a3000)

"No such file or directory" refers to the loader (/lib/ld-musl-x86_64.so.1), not to your binary. The fix is one of: build a static binary (CGO_ENABLED=0, or musl for Rust), or choose a runtime base that contains the libraries (debian:bookworm-slim, gcr.io/distroless/cc for dynamically linked C runtime). When a Go program truly needs cgo (some SQLite drivers, for example), use the cc distroless variant or a slim Debian image, and match the build and runtime C libraries.

To inspect any binary before shipping it, run ldd or file in the build stage: "statically linked" is the sentence you want.

Cross compilation

Go and Rust can build for a CPU other than the one they run on. That lets you produce an arm64 image (for Apple Silicon laptops or Graviton servers) on an amd64 build machine without slow emulation of the compiler. In Go the recipe is three lines:

DOCKERFILE
FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS build
ARG TARGETOS
ARG TARGETARCH
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w" -o /out/server .

FROM scratch
COPY --from=build /out/server /server
ENTRYPOINT ["/server"]

--platform=$BUILDPLATFORM runs the compiler natively on the build machine; TARGETOS and TARGETARCH are filled in by BuildKit from --platform. We built it for ARM on an x86 machine and checked the result:

CONSOLE
$ docker buildx build --platform linux/arm64 -t hello-go-arm --load .
$ docker image inspect hello-go-arm --format '{{.Os}}/{{.Architecture}}'
linux/arm64
$ docker image inspect hello-go --format '{{.Os}}/{{.Architecture}}'
linux/amd64

The Go build for the foreign architecture took 36 seconds, the same ballpark as a native cold build, since nothing was emulated. Rust cross compilation needs extra targets and linkers and is more involved; many teams instead build natively on each architecture (or use the cargo-zigbuild tool) and combine the results in a multi-platform manifest. See Multi-Platform Images.

Production checklist

  • Use a versioned builder tag (golang:1.25-alpine, not golang:alpine) so builds are repeatable.
  • Commit go.sum / Cargo.lock, and copy them before the sources so the dependency layer stays cached.
  • Keep .dockerignore tight (.git, target/, bin/, *.md): a local Rust target/ directory can be gigabytes and would be sent as build context. See Build Context and .dockerignore.
  • Run as a non-root numeric user (USER 65532:65532 on scratch, :nonroot on distroless). See Users and Permissions.
  • Add a health endpoint and have your orchestrator or Compose call it. On scratch there is no curl for a HEALTHCHECK, so either let your binary check itself (/server -healthcheck) or rely on an external probe. See HEALTHCHECK.
  • Handle SIGTERM for graceful shutdown.

When to use scratch, and when not

Use scratch when your binary is static, you do not need certificates or time zones (or you copy them in), and you are happy to debug from the outside. Use distroless static when you want the same minimalism with the common files included. Use Alpine or Debian slim when you want a shell for operations, need cgo, or your team will exec into containers regularly. There is no shame in a 20 MB image with a shell; the huge win was leaving the 337 MB toolchain behind.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the Go build use CGO_ENABLED=0 before copying the binary onto scratch?

    With cgo disabled Go links everything statically. A dynamically linked binary on scratch fails with 'no such file or directory' because the loader does not exist. Stripping symbols is done by -ldflags, and caching by cache mounts.
  2. 2. A container on scratch prints exec /app: no such file or directory although /app exists in the image. What is the most likely cause?

    The error names the missing interpreter, not your file. We reproduced it by copying Alpine's dynamically linked busybox onto scratch. Fix it with a static build or a base image that contains the libraries.
  3. 3. Why does the Rust Dockerfile copy the binary to /hello in the same RUN command that runs cargo build?

    Cache mounts are not stored in the image layer. After the RUN step the files under /src/target are gone from that layer, so the binary has to be copied to a normal path during the same step.
  4. 4. What happens on docker stop if a Rust program running as PID 1 has no SIGTERM handler and you did not use --init?

    PID 1 ignores signals that have no handler. Docker waits (ten seconds by default) and then sends SIGKILL. Install a handler, as the ctrlc crate does in our example, or use --init.
  5. 5. What does distroless static add compared with scratch?

    Distroless static contains just what a static binary commonly needs. In our build it cost about 6 MB more than scratch and gave us a nonroot user (UID 65532). The cc variant adds the C library.

Summary

  • Compile in a toolchain image, copy the binary into a tiny final stage: 8 MB for a Go web server, under 1 MB for a small Rust one, against hundreds of MB for the toolchain.
  • The binary must be static: CGO_ENABLED=0 for Go, the musl-based rust:alpine for Rust. A dynamic binary on scratch fails with a misleading "no such file or directory".
  • Cache dependencies two ways: copy go.mod/Cargo.toml first, and use cache mounts so recompiles touch only changed code (48.9 s cold against 2.2 s warm for our Go build).
  • scratch has no shell, certificates, time zones or users. Distroless static supplies the basics; Alpine or Debian slim give you a shell.
  • Handle SIGTERM for graceful shutdown, since your binary is PID 1.
  • Cross compile with --platform=$BUILDPLATFORM, TARGETOS and TARGETARCH instead of emulating the compiler.

Next: Containerizing a PHP App