Subscribe

Hardening a Go container image: distroless, non-root and read-only

Part 4 of the shorty series: hardening the Go container image. A static binary on distroless instead of scratch or alpine, a numeric non-root user, no shell, a read-only root filesystem, all capabilities dropped and the base image pinned by digest.

Hardening a Go container image: distroless, non-root and read-only

A few years ago I wrote about a multi-stage Dockerfile for a Go web service. Multi-stage gets the Go toolchain out of the final image, which is the big win. But the image from that post still ran as root, had a shell and a package manager, and could write anywhere on its own filesystem. If someone finds a hole in your app, all of that is waiting for them.

In this blog we will harden the shorty image: pick a base image (distroless vs scratch vs alpine), run as a non-root user, make the root filesystem read-only and drop every Linux capability. This is part 4 of the shorty series and follows the Docker Compose stack from part 3. Level is intermediate: you should be OK reading a Dockerfile and running docker compose.

I used Docker 29.8.2 on a Mac (Apple silicon), golang:1.27.4-alpine to build and gcr.io/distroless/static-debian13:nonroot to run.

The Dockerfile

Here is the whole thing first, then the reasons line by line.

# syntax=docker/dockerfile:1

# ---- build stage: full Go toolchain, thrown away at the end ----
FROM golang:1.27.4-alpine AS build
WORKDIR /src

# Download modules first so this layer is cached until go.mod/go.sum change.
COPY go.mod go.sum ./
RUN go mod download

COPY . .
ARG VERSION=dev
# CGO_ENABLED=0 gives a static binary that needs no libc, so it runs on distroless/static.
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/shorty ./cmd/shorty

# ---- runtime stage: no shell, no package manager, non-root ----
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/shorty /shorty
# nonroot is uid 65532 in distroless; numeric so Kubernetes runAsNonRoot can check it.
USER 65532:65532
EXPOSE 8080
# No curl in distroless, so the binary checks itself.
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD ["/shorty", "healthcheck"]
# CMD and no ENTRYPOINT: ECS, Kubernetes and compose can swap in "/shorty migrate up".
CMD ["/shorty", "serve"]

And a .dockerignore, so the build context doesn't drag in .git or a local .env with secrets:

.git
*.md
compose.yaml
seed/
.env

A static binary first

Everything below depends on one line: CGO_ENABLED=0. With cgo off, the Go linker makes a fully static binary. It doesn't need libc, so it runs on an image that has no libc. shorty uses pgx and go-redis, both pure Go, so there's nothing to lose.

The other flags are smaller wins. -trimpath removes my local paths (/Users/...) from the binary. -s -w strips the symbol table and DWARF debug info, which makes the file smaller. -X main.version=... stamps a version so /shorty version can tell you which build is running. Nice to have when you are staring at three ECS tasks wondering which one is old.

distroless vs scratch vs alpine

I built the same binary on three different bases and compared the size docker images reported:

scratch                                    18.3MB
gcr.io/distroless/static-debian13:nonroot  25.6MB
alpine:3.23                                32.8MB

Those numbers comes from the containerd image store (I run Docker through OrbStack on the Mac), which counts a bit more than the unpacked files, so look at the gaps more than the totals. The shorty binary layer alone is 13.5 MB.

scratch is empty. Nothing at all. It's the smallest, and it works for shorty right now. But you have to bring everything yourself: CA certificates (the moment your app calls an HTTPS API you need them), timezone data, and a /etc/passwd if anything wants a user name.

alpine gives you a shell, apk and musl. That is handy for debugging and exactly what an attacker would like to find too. It also brings more packages for your scanner to flag.

distroless/static sits in between. docker history shows what it adds on top of the binary:

13.5MB  COPY /out/shorty /shorty # buildkit
270kB   bazel build //common:cacerts_debian13_arm64_…
4.1kB   bazel build //common:os_release_debian13
4.1kB   bazel build //static:nsswitch

CA certificates, os-release (so scanners know what they are looking at), tzdata, and a /etc/passwd with a nonroot user. No shell, no package manager. About 7 MB more than scratch for me, and I don't have to maintain any of it. That's my default for Go now.

I used the debian13 variant. Older guides say static-debian12, which still exists, but 13 (trixie) is the current Debian.

Running as non-root

By default a container runs as root, uid 0. Yes, it's namespaced, but it's still root inside and container escapes usually start from there. The :nonroot tag of distroless already sets a non-root user, I copied the passwd file out of the image to check what it is:

id=$(docker create shorty:dev)
docker cp "$id:/etc/passwd" ./passwd
docker rm "$id"
cat passwd
root:x:0:0:root:/root:/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/sbin/nologin
nonroot:x:65532:65532:nonroot:/home/nonroot:/sbin/nologin

I still write USER 65532:65532 in my own Dockerfile. Two reasons. It makes the user visible to whoever reads the file, without knowing distroless tags. And Kubernetes runAsNonRoot: true can only check a numeric user. If the image says USER nonroot and the pod spec doesn't set runAsUser, the kubelet can't prove that name isn't root and refuses to start the pod.

With the compose stack up, docker top shows the process really runs as 65532:

docker top shorty-api-1 -o user,pid,comm
USER                PID                 COMMAND
65532               37556               shorty

shorty listens on 8080, so it never needed root to bind a port anyway.

No shell

docker compose exec api sh
OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH

That's the point, but it changes two habits.

First, health checks. Most Dockerfiles do HEALTHCHECK CMD curl -f http://localhost:8080/healthz. See, there is no curl. So shorty has a healthcheck subcommand that does the GET in Go and exits 0 or 1. Ten lines of code, and docker compose ps showed Up 13 seconds (healthy). One thing to know: ECS ignores the Dockerfile HEALTHCHECK, you set the same command in the task definition's healthCheck.

Second, debugging. You can't exec in and poke around. When I need that, I run a throwaway debug container that shares the target's network and PID namespace (docker run --rm -it --pid container:<name> --network container:<name> busybox), or kubectl debug with an ephemeral container on Kubernetes. Both attach a separate image that has tools. distroless also has :debug tags with a busybox shell, but I keep those out of anything that gets deployed.

Read-only root filesystem

shorty writes nothing to disk. Logs go to stdout, data to Postgres, cache to Redis. So the container's filesystem can be read-only, and anything that gets code execution in it can't drop a file or change the binary.

In compose it is one line only on the api service:

    read_only: true
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]

If your app does need a scratch directory (some libraries write to /tmp), keep the root read-only and mount a tmpfs only there:

    tmpfs:
      - /tmp:size=16m

Basically, the best way to find out is to turn it on and run your tests. If something tries to write, you'll get read-only file system in the logs straight away.

Dropping capabilities

Root in Linux is split into about 40 capabilities: NET_RAW for raw sockets, CHOWN, SETUID, NET_BIND_SERVICE for ports below 1024, and so on. Docker gives every container a default set of about 14 of them. A Go web server on port 8080 needs none. cap_drop: [ALL] removes them all.

no-new-privileges stops a process from gaining more privileges than its parent through setuid binaries. distroless has no setuid binaries to begin with, so this is belt and braces. It costs nothing.

I checked the running container to make sure compose really applied them:

docker inspect shorty-api-1 --format 'ro={{.HostConfig.ReadonlyRootfs}} capdrop={{.HostConfig.CapDrop}} user={{.Config.User}} secopt={{.HostConfig.SecurityOpt}}'
ro=true capdrop=[ALL] user=65532:65532 secopt=[no-new-privileges:true]

The same flags work with plain docker run:

docker run --rm --read-only --cap-drop ALL --security-opt no-new-privileges:true shorty:dev /shorty version
dev

The same thing in Kubernetes and ECS

These settings belong to whoever runs the container, not to the image. The image only makes them possible. In Kubernetes they go in the securityContext:

apiVersion: v1
kind: Pod
metadata:
  name: shorty
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 65532
    runAsGroup: 65532
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: shorty
      image: shorty:dev
      ports:
        - containerPort: 8080
      securityContext:
        readOnlyRootFilesystem: true
        allowPrivilegeEscalation: false
        capabilities:
          drop: ["ALL"]

allowPrivilegeEscalation: false is Kubernetes' name for no-new-privileges. If you followed the kind cluster post, you can add this block to the shorty pod there. I didn't have a cluster running on this Mac today, so I haven't applied this exact pod, but these fields pass the "restricted" Pod Security Standard as far as I know.

In an ECS task definition the container definition takes "user": "65532", "readonlyRootFilesystem": true and "linuxParameters": {"capabilities": {"drop": ["ALL"]}}. The shorty ECS post later in the series will use them. If ECS is new to you, start with ECS explained.

Pin the base image

:nonroot is a moving tag. To make builds repeatable, pin it by digest. I looked up the current one:

docker buildx imagetools inspect gcr.io/distroless/static-debian13:nonroot | head -3
Name:      gcr.io/distroless/static-debian13:nonroot
MediaType: application/vnd.oci.image.index.v1+json
Digest:    sha256:aafe993665bf6200db38a02c11a9351e782a84b6a45e7f33b6695638c88e3931
FROM gcr.io/distroless/static-debian13:nonroot@sha256:aafe993665bf6200db38a02c11a9351e782a84b6a45e7f33b6695638c88e3931

Now the catch with pinning is that you stop getting fixes. So something has to bump the digest, Dependabot or Renovate can do that for Dockerfiles. A base image this small rarely has findings, but your Go dependencies still can, and govulncheck covers that side.

Checking it all together

The compose run from part 3 already used this image with these three lines. I created a link, followed redirects, stopped the api to check the click flush and tore everything down. Nothing needed a shell, root or a writable disk. The only code I had to add for hardening was the healthcheck subcommand.

Next in the series the image goes into CI and gets pushed to a registry, so this is the image every later post deploys.