TExcelTAD

A Distroless Image

linkly compiles to one binary, which makes its image almost trivial: build in a full Go image, copy the binary into an image that contains nothing else. This lesson writes that Dockerfile, checks the one property it depends on (a static binary), scans it, and builds and runs it on your machine. The Docker course covers multi-stage builds, non-root users and distroless images in general; here they come together for one service.

The Dockerfile

dockerfile
# syntax=docker/dockerfile:1
FROM golang:1.27.3 AS build
WORKDIR /src
# 1. dependencies first: this layer is cached until go.mod or go.sum change
COPY go.mod go.sum ./
RUN go mod download
# 2. then the source
COPY *.go ./
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/linkly .

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

And a .dockerignore, so the build context doesn't ship your Git history, local binaries or editor files to the builder:

text
.git
linkly
dist/
chart/
*.md

Line by line, the decisions:

Line Why
golang:1.27.3 the same Go version as go.mod and CI; pin the tag (and in production the digest, golang:1.27.3@sha256:…) so a rebuild next month uses the same compiler
COPY go.mod go.sum + go mod download before COPY *.go a code change doesn't invalidate the dependency layer: rebuilds take seconds
CGO_ENABLED=0 a static binary that needs no C library; the reason is in the session below
-trimpath removes your machine's file paths from the binary (reproducible builds, no leaked home directory)
-ldflags "-s -w" drops the symbol table and DWARF debug info: a smaller image; stack traces still work
-X main.version=${VERSION} stamps the version CI passes as a build argument; it shows up in linkly_build_info and the startup log
distroless/static-debian12:nonroot CA certificates, /etc/passwd with a nonroot user (UID 65532), timezone data, and no shell or package manager
USER nonroot:nonroot explicit, so scanners and readers don't have to know the base image's default; the chart's runAsNonRoot: true checks it again
exec-form ENTRYPOINT linkly is PID 1 and receives SIGTERM directly (a shell-form entrypoint would wrap it in /bin/sh, which doesn't exist here anyway)

There is no HEALTHCHECK: Kubernetes ignores it and uses the chart's probes, and distroless has no curl to run one with.

Why the binary must be static

The sandbox has no Docker daemon, but it can show the property the final stage depends on. The session builds a tiny program that, like linkly, imports net, once with the defaults and once with the Dockerfile's flags, and compares them:

bash · try it yourself
mkdir hello && cd hello
cat > main.go <<'GO'
package main

import (
	"fmt"
	"net"
)

var version = "dev"

func main() {
	addrs, _ := net.LookupHost("localhost")
	fmt.Println("version", version, "- localhost resolves to", addrs)
}
GO
go mod init example.com/hello >/dev/null 2>&1
go build -o hello-default .
CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=1.4.0" -o hello-static .
for b in hello-default hello-static; do echo "$b: $(file -b $b | tr ',' '\n' | grep -E 'linked' | xargs)"; done
echo "--- shared libraries hello-default needs:"
ldd hello-default | awk '{print $1}'
echo "--- hello-static:"
ldd hello-static
ls -l hello-default hello-static | awk '{print $5, $9}'
./hello-static
go version -m hello-static | grep -E 'CGO_ENABLED|trimpath'
hello-default: dynamically linked
hello-static: statically linked
--- shared libraries hello-default needs:
linux-vdso.so.1
libc.so.6
/lib64/ld-linux-x86-64.so.2
--- hello-static:
	not a dynamic executable
3370160 hello-default
2158752 hello-static
version 1.4.0 - localhost resolves to [127.0.0.1 ::1]
	build	-trimpath=true
	build	CGO_ENABLED=0

With the defaults, a program that uses net is dynamically linked against glibc (Go's cgo DNS resolver), because the sandbox, like most build machines, has a C compiler. Copy that binary into distroless/static and it fails at start with a confusing no such file or directory: the file exists, its interpreter /lib64/ld-linux-x86-64.so.2 doesn't. CGO_ENABLED=0 switches to Go's pure-Go resolver and produces a static binary, a third smaller after -s -w. linkly's own build info in The Source said CGO_ENABLED=1, which is why the Dockerfile sets it explicitly. (-ldflags is no longer listed in the build information of a -trimpath build; the stamped version still is in the binary.)

Scanning the Dockerfile

Trivy checks a Dockerfile against its built-in misconfiguration rules (root user, latest tags, ADD from URLs, secrets in ENV, …) without building anything:

bash · try it yourself
cat > Dockerfile <<'X'
# syntax=docker/dockerfile:1
FROM golang:1.27.3 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/linkly .

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/linkly /linkly
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/linkly"]
X
scan() { trivy config -q -f json . | jq -r '.Results[] | "checks passed: \(.MisconfSummary.Successes), failed: \(.MisconfSummary.Failures)", (.Misconfigurations[]? | "  \(.Severity) \(.ID) \(.Title)")'; }
scan
echo "--- after documenting the exception:"
printf '# Kubernetes uses the chart probes; distroless has no shell for a HEALTHCHECK.\nDS-0026\n' > .trivyignore
scan
echo "--- a careless variant:"
sed -i -e 's/:nonroot$/:latest/' -e '/^USER/d' Dockerfile
scan
checks passed: 26, failed: 1
  LOW DS-0026 No HEALTHCHECK defined
--- after documenting the exception:
checks passed: 26, failed: 0
--- a careless variant:
checks passed: 24, failed: 2
  MEDIUM DS-0001 ':latest' tag used
  HIGH DS-0002 Image user should not be 'root'

The only finding on the real Dockerfile is the missing HEALTHCHECK, which is a deliberate choice, so it goes into .trivyignore with a comment saying why: an ignore file without reasons turns into a place where findings go to be forgotten. The careless variant fails two checks at once: the latest tag (MEDIUM) and running as root (HIGH), because without a USER line the container runs as whatever the base image says, and latest doesn't say nonroot. The CI workflow runs this scan on every pull request.

Build and run it (sample)

On your machine, from the linkly repository:

bash
$ docker build --build-arg VERSION=1.4.0 -t linkly:1.4.0 .
...
 => [build 4/6] RUN go mod download
 => [build 6/6] RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=1.4.0" -o /out/linkly .
 => [stage-1 2/2] COPY --from=build /out/linkly /linkly
 => exporting to image
 => => naming to docker.io/library/linkly:1.4.0

$ docker images linkly
REPOSITORY   TAG     IMAGE ID       CREATED          SIZE
linkly       1.4.0   3f1c9b7e2a4d   12 seconds ago   20.1MB

$ docker run --rm --network host -e DATABASE_URL='postgres://linkly:linkly@localhost:5432/linkly?sslmode=disable' \
    -e REDIS_ADDR=localhost:6379 linkly:1.4.0
{"time":"2026-01-15T10:00:00.12Z","level":"INFO","msg":"listening","addr":":8080","version":"1.4.0"}

$ docker run --rm --entrypoint sh linkly:1.4.0
docker: Error response from daemon: ... exec: "sh": executable file not found in $PATH

The image is roughly the binary plus a couple of megabytes of base: compare that with several hundred megabytes for the golang build stage. The last command is the point of distroless: there is no shell for an attacker (or you) to exec into. To debug a running pod, use an ephemeral debug container instead: kubectl debug -it <pod> --image=busybox:1.37 --target=linkly shares the process namespace without changing the image.

For the local track, load the image straight into the kind cluster (no registry needed) or push it to the local registry from CI Against a Local Registry:

bash
kind load docker-image linkly:1.4.0 --name linkly

Note: On Apple silicon or other ARM machines, docker build produces an arm64 image, which runs on a local kind cluster but not on amd64 cloud nodes. CI builds the release images; for a multi-architecture image use docker buildx build --platform linux/amd64,linux/arm64 (Go cross-compiles without cgo, another reason for CGO_ENABLED=0).

Test yourself

A default go build of linkly is copied into distroless/static and fails to start with "no such file or directory". Why?

  1. The binary is too large
  2. It is dynamically linked and the image has no dynamic loader or glibc
  3. distroless forbids Go binaries
  4. The ENTRYPOINT is in shell form

Why are go.mod and go.sum copied and downloaded before the source files?

  1. Go requires that order
  2. So the dependency layer stays cached when only the code changes
  3. To make the image smaller
  4. To verify checksums twice

How do you get a shell next to a distroless container that is misbehaving in a pod?

  1. kubectl exec -it pod -- sh
  2. Rebuild the image with busybox
  3. kubectl debug with an ephemeral container targeting the linkly container
  4. SSH into the node