Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 111 Β· Projects

Project: A Tiny Go Image

Shrink a Go web service from 453 MB to 9 MB with a multi-stage build and a scratch image, then fix certificates, compare bases and harden the container.

Go is the perfect language for small images. It compiles to a single static binary that needs no runtime, no interpreter and no shared libraries, so the final image can contain nothing but that binary. In this project you will build a small Go web service two ways, watch the image shrink from 453 MB to about 9 MB, then deal with the things a tiny image does not give you for free: no shell, no CA certificates, and a healthcheck without curl.

Everything was built and run on Docker 29 with Go 1.25. If you have not met the technique yet, read Multi-Stage Builds first; the general recipe is in Containerizing Go and Rust Apps.

The program

The service answers three routes and shuts down cleanly on SIGTERM. It also understands two sub-commands, healthcheck and fetch, because a scratch image has no curl or wget and we still want a way to test health and outgoing HTTPS from inside the image.

TEXT
hello-api/
  go.mod
  main.go
  Dockerfile
  .dockerignore
TEXT
// go.mod
module hello-api

go 1.25
Go
// main.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"
)

var version = "dev"

func main() {
	if len(os.Args) > 1 {
		os.Exit(runCommand(os.Args[1:]))
	}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello from Go %s\n", runtime.Version())
	})
	mux.HandleFunc("GET /info", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]any{
			"version": version,
			"go":      runtime.Version(),
			"os":      runtime.GOOS,
			"arch":    runtime.GOARCH,
			"uid":     os.Getuid(),
		})
	})
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	srv := &http.Server{Addr: ":8080", Handler: mux}
	go func() {
		log.Printf("listening on %s (version %s)", srv.Addr, version)
		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)
}

// runCommand implements tiny sub-commands so the image needs no curl or shell.
func runCommand(args []string) int {
	switch args[0] {
	case "healthcheck":
		resp, err := http.Get("http://127.0.0.1:8080/healthz")
		if err != nil || resp.StatusCode != 200 {
			return 1
		}
		return 0
	case "fetch":
		if len(args) < 2 {
			fmt.Fprintln(os.Stderr, "usage: fetch URL")
			return 2
		}
		resp, err := http.Get(args[1])
		if err != nil {
			fmt.Fprintln(os.Stderr, "error:", err)
			return 1
		}
		defer resp.Body.Close()
		io.Copy(io.Discard, resp.Body)
		fmt.Println("status:", resp.Status)
		return 0
	}
	fmt.Fprintln(os.Stderr, "unknown command:", args[0])
	return 2
}

var version = "dev" is a package-level variable that we will overwrite at build time without touching the source.

Attempt 1: the obvious Dockerfile

The straightforward approach uses the Go image to build and to run:

DOCKERFILE
# Dockerfile.single
FROM golang:1.25-alpine
WORKDIR /src
COPY go.mod main.go ./
RUN go build -o /app .
USER 10001
CMD ["/app"]

It works, but look at the result:

CONSOLE
$ docker build -f Dockerfile.single -t hello-go:single .
$ docker image ls hello-go:single --format 'table {{.Tag}}\t{{.Size}}'
TAG      SIZE
single   453MB

453 MB to ship a 9 MB program. The rest is the Go compiler, the standard library sources, Alpine's shell and package manager, git and more. Everything in an image is something to download, store, scan for vulnerabilities and, in the worst case, abuse after a break-in.

Attempt 2: build in one stage, run in another

A multi-stage Dockerfile has several FROM lines. Each starts a new stage; only the last one becomes the image. Earlier stages are just workshops, and COPY --from carries finished files out of them.

DOCKERFILE
# Dockerfile
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY go.mod main.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=1.0.0" -o /out/app .

FROM scratch
COPY --from=build /out/app /app
USER 10001:10001
EXPOSE 8080
HEALTHCHECK --interval=5s --timeout=3s --start-period=2s --retries=3 CMD ["/app", "healthcheck"]
ENTRYPOINT ["/app"]

Take it line by line:

  • FROM golang:1.25-alpine AS build names the first stage so we can refer to it.
  • CGO_ENABLED=0 tells Go not to link against C libraries. The result is a fully static binary that does not need a C library (glibc or musl) at run time. Without this, a program that uses the net package may link dynamically and crash with a confusing "not found" error on a minimal image (Choosing a Base Image).
  • -trimpath removes your local build paths from the binary (smaller and reproducible). -ldflags="-s -w" strips the symbol table and debug information. -X main.version=1.0.0 sets the version variable from the build, so /info will report it.
  • FROM scratch is the empty image: no files, no shell, no package manager. Just what you copy in.
  • USER 10001:10001 runs as a numeric non-root user. A scratch image has no /etc/passwd, so a name would not resolve; a number always works (Users and Permissions).
  • HEALTHCHECK ... CMD ["/app", "healthcheck"] uses the binary itself as the checker (HEALTHCHECK).
  • ENTRYPOINT ["/app"] in exec form, so the Go process is PID 1 and receives SIGTERM directly (CMD and ENTRYPOINT).

The copy of go.mod and main.go before the build is deliberate. If your project had dependencies you would copy go.mod and go.sum first, run go mod download, and only then copy the source, so the download layer stays cached (The Build Cache).

Add a .dockerignore so Dockerfiles and git history stay out of the build context (Build Context and .dockerignore):

TEXT
Dockerfile*
.git

Build and compare:

CONSOLE
$ docker build -t hello-go:scratch .
$ docker image ls hello-go --format 'table {{.Tag}}\t{{.Size}}'
TAG       SIZE
scratch   8.98MB
single    453MB

That is about 50 times smaller. Only the build stage is large, and it never ships. You can still inspect it with --target, which stops the build at a named stage:

CONSOLE
$ docker build --target build -t hello-go:build .
$ docker image ls hello-go:build --format '{{.Size}}'
447MB

The final image has a single layer containing the binary:

CONSOLE
$ docker history hello-go:scratch --format 'table {{.CreatedBy}}\t{{.Size}}'
CREATED BY                                      SIZE
ENTRYPOINT ["/app"]                             0B
HEALTHCHECK {Test:[CMD /app healthcheck] Int…   0B
EXPOSE [8080/tcp]                               0B
USER 10001:10001                                0B
COPY /out/app /app # buildkit                   6.28MB

(docker image ls reports 8.98 MB for the whole image and the layer is the 6.28 MB binary; sizes depend on the image store, so compare images with the same tool.)

What the build flags are worth

We can measure the effect of -s -w. Here is the same program built plainly (go build -o /out/app .) and with our flags:

Build Binary size Whole image
go build 9,057,224 bytes 14.1 MB
go build -trimpath -ldflags="-s -w" 6,271,160 bytes 8.98 MB

The stripped binary is about 30% smaller. You lose symbol names in debuggers and some stack-trace detail from external tools (Go's own panic traces still show function names), which is the right trade for a production image.

Run it

CONSOLE
$ docker run -d --name hello -p 127.0.0.1:18155:8080 hello-go:scratch
$ curl -s http://127.0.0.1:18155/
hello from Go go1.25.14
$ curl -s http://127.0.0.1:18155/info
{"arch":"amd64","go":"go1.25.14","os":"linux","uid":10001,"version":"1.0.0"}
$ docker ps --filter name=hello --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
NAMES   IMAGE                STATUS                   PORTS
hello   hello-go:scratch     Up 8 seconds (healthy)   127.0.0.1:18155->8080/tcp

/info confirms three things from inside the container: the version injected by -X, the architecture, and "uid":10001, so the process is not root. (healthy) shows the built-in healthcheck works even though the image has no curl: it runs our own binary.

Stopping it is quick because the program handles SIGTERM and is PID 1:

CONSOLE
$ time docker stop hello
hello

real	0m1.1s
$ docker logs hello
2026/10/23 15:40:04 listening on :8080 (version 1.0.0)
2026/10/23 15:40:20 shutting down
$ docker inspect hello --format '{{.State.ExitCode}}'
0

The price of scratch

A tiny image removes conveniences you may not notice until you need them.

There is no shell

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

This is a security feature: an attacker who gets code execution has no shell, no curl and no package manager to work with. It is also a debugging obstacle. Typical remedies are to attach a temporary debug container to the same namespaces, to build a second debug image variant on alpine, or to use a debug tool such as docker debug (Debugging Containers).

There are no CA certificates

HTTPS clients verify a server's certificate against a list of trusted authorities. scratch has no such list:

CONSOLE
$ docker run --rm hello-go:scratch fetch https://example.com
error: Get "https://example.com": tls: failed to verify certificate: x509: certificate signed by unknown authority
$ docker run --rm hello-go:scratch fetch http://example.com
status: 200 OK

Plain HTTP works, HTTPS fails. This surprises many people the first time their service calls a payment API. The fix is to copy the bundle from the build stage:

DOCKERFILE
FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=build /out/app /app
USER 10001:10001
ENTRYPOINT ["/app"]
CONSOLE
$ docker run --rm hello-go:certs fetch https://example.com
status: 200 OK

The image grows by only 0.3 MB (9.28 MB instead of 8.98 MB). Time zone data is the same story: if your code calls time.LoadLocation("Europe/Berlin") you need /usr/share/zoneinfo in the image, or you can import time/tzdata in your Go code to embed it in the binary.

There is no /etc/passwd

That is why we used a numeric USER. A related trap: a program that needs a writable directory such as /tmp will not find one. Create it in the build stage and copy it over, or mount a tmpfs at run time (tmpfs and In-Memory Storage).

Comparing final-stage choices

scratch is not the only option. We built the same binary on top of three bases:

Final stage Image size Shell CA certs Non-root user ready
scratch 8.98 MB no no (copy them) numeric USER only
scratch + certs 9.28 MB no yes numeric USER only
gcr.io/distroless/static-debian12:nonroot 15.2 MB no yes yes (nonroot)
alpine:3 21.9 MB yes (82 programs in /bin) yes numeric USER only

Distroless static gives you certificates, time zone data and a ready-made nonroot user for about 6 MB. Alpine adds a shell and apk (16 installed packages when we counted), which is wonderful for debugging and one more thing to patch. All three ran our fetch https://example.com successfully, apart from plain scratch.

A reasonable rule: use distroless static as the default for Go services, scratch when you want the absolute minimum and know exactly what the program needs, and alpine when your team really needs a shell in production. See Choosing a Base Image.

Harden the running container

A tiny image combines well with the run-time restrictions from the security lessons. The program needs no write access, no capabilities and little memory, so we can take them all away:

CONSOLE
$ docker run -d --name hello-hard --read-only --cap-drop ALL \
    --security-opt no-new-privileges --memory 32m --pids-limit 50 \
    -p 127.0.0.1:18155:8080 hello-go:scratch
$ curl -s http://127.0.0.1:18155/
hello from Go go1.25.14
$ docker ps --filter name=hello-hard --format '{{.Status}}'
Up 8 seconds (healthy)
$ docker stats --no-stream --format '{{.Name}} {{.MemUsage}} {{.PIDs}}' hello-hard
hello-hard 6.645MiB / 32MiB 8
$ docker inspect hello-hard --format 'RO={{.HostConfig.ReadonlyRootfs}} cap_drop={{.HostConfig.CapDrop}} user={{.Config.User}}'
RO=true cap_drop=[ALL] user=10001:10001

It runs, healthy, on a read-only root filesystem with every Linux capability dropped, using under 7 MiB of memory out of a 32 MiB limit. Few other stacks can do that so easily. Read more in Non-Root Users and Capabilities, seccomp, AppArmor and Read-Only Filesystems and Resource Limits.

What you gained

  • Size. 453 MB to 9 MB: faster pulls, faster deploys, cheaper registry storage.
  • Attack surface. No shell, no package manager, no compiler, nothing to patch except your own binary. A vulnerability scanner has almost nothing to report on a scratch image, but it also cannot see inside a stripped static binary, so keep scanning the Go module dependencies at build time (Image Security and Scanning).
  • Reproducibility. -trimpath and a pinned golang:1.25-alpine tag make rebuilds predictable; pin by digest for stricter guarantees.
  • Speed of start. A single static binary starts in milliseconds.

And what you gave up: easy debugging, certificates and time zones you must add yourself, and the ability to docker exec into the container. Decide with your team where that trade is right, and keep a debug build target around.

Clean up

CONSOLE
$ docker rm -f hello hello-hard
$ docker rmi hello-go:single hello-go:scratch hello-go:certs hello-go:build

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Why is CGO_ENABLED=0 important when building a Go binary for a scratch image?

    With cgo enabled, some programs link dynamically against glibc or musl. On scratch those libraries do not exist, and the container fails to start with a confusing "not found" error. CGO_ENABLED=0 forces a static binary.
  2. 2. Which FROM line produces the final image in a multi-stage Dockerfile?

    Each FROM starts a new stage, and the image you get is the last stage. Earlier stages exist only to produce files for COPY --from. --target stops at a chosen stage instead.
  3. 3. A service built on scratch fails with x509: certificate signed by unknown authority when calling an HTTPS API. What is the fix?

    scratch is empty, so there is no list of trusted certificate authorities. Copy the bundle into /etc/ssl/certs/, or use distroless/static, which already contains it.
  4. 4. Why does the Dockerfile use USER 10001:10001 and not USER appuser?

    User names are looked up in /etc/passwd. An empty image has none, but the kernel works with numeric IDs directly.
  5. 5. How can you check the health of a scratch container that has no curl or wget?

    HEALTHCHECK runs any command that exists in the image. A small sub-command of your own binary that requests /healthz and exits 0 or 1 does the job without extra tools.

Summary

  • A multi-stage build compiles in a large golang stage and ships only the binary: 453 MB became about 9 MB here.
  • Build static binaries with CGO_ENABLED=0; add -trimpath and -ldflags="-s -w" for a smaller binary, and -X main.version=... to stamp a version.
  • scratch has no shell, no CA certificates, no time zone data, no /etc/passwd and no /tmp. Add what you need, use a numeric USER, and build the healthcheck into your binary.
  • distroless/static (about 15 MB) or Alpine (about 22 MB) are friendlier bases when you need certificates, a ready non-root user or a shell.
  • Combine a tiny image with --read-only, --cap-drop ALL, no-new-privileges and memory limits for a very small attack surface.
  • Keep a --target build stage (or a debug variant) for troubleshooting.

Next: Project: A Build and Release Pipeline