Switching a runtime image to distroless is a two-line edit to a Dockerfile and a week of surprises if you do not know what the base removes. gcr.io/distroless/static-debian12 gives you a CA certificate bundle, timezone data, an /etc/passwd entry for UID 65532, and nothing else — no /bin/sh, no apt, no ls, no curl, no libc. Two traps catch almost everyone. Shell-form CMD stops working because there is no shell left to interpret it, and a dynamically linked binary dies with exec /app: no such file or directory on the static variant even though the file is visibly present in the layer. This guide converts a real build, proves the image is smaller and the app still answers, and then shows how to get a working shell into a container that does not ship one.
What you’ll accomplish
- Measure what your current runtime image actually carries, so the reduction is a number and not a feeling.
- Convert a Go service to
gcr.io/distroless/static-debian12:nonrootand a Python service togcr.io/distroless/python3-debian12, running as UID 65532 in both cases. - Understand which distroless variant a binary needs based on how it links:
static,base, orcc. - Prove outbound TLS still works, which is the fastest way to confirm the CA bundle survived the move.
- Debug a running distroless container two ways — the
:debugtag with its busybox shell, and an ephemeral container attached to the running process namespace.
Prerequisites
- Docker Engine 24 or newer with BuildKit enabled. BuildKit is the default builder since 23.0;
docker buildx versionshould print something. Multi-stage builds work without BuildKit, but--mount=type=cacheand parallel stage builds do not. - A working application to convert, and ideally two: one compiled language and one interpreted. The examples use a Go HTTP service and a Python FastAPI service, because the difference between them — static versus dynamic linking — is the single biggest source of distroless failures.
- Push access to a registry, or at least a local daemon you can build against. Nothing here needs a cluster.
- The images live under
gcr.io/distroless/...and are built by the GoogleContainerTools/distroless project. There is no Docker Hub mirror; if your environment only allows one registry, mirror the tags you need before you start. - An honest note: distroless is one option among several.
alpinegives you a 7 MB base that still has a shell andapk, which many teams prefer precisely because it stays debuggable. Chainguard’s Wolfi images are minimal and get faster CVE patching but come with their own registry and rate limits.scratchis smaller still and appropriate for a fully static binary that needs no certificates. Distroless sits in the middle: small, no shell, but with the two files that most services genuinely need (CA certs and tzdata) already in place.
How it works
A multi-stage Dockerfile has more than one FROM. Each FROM opens a stage with its own filesystem; COPY --from=<stage> reaches back into an earlier stage and lifts files out. Only the last stage becomes the image you push. If you want the mechanics of stage graphs, targets and cache behaviour in depth, that is covered separately in multi-stage Docker builds and in the Docker multi-stage documentation. What follows is specifically about what happens when the final stage is distroless.
A distroless layer is not a stripped Debian. It is a hand-assembled tarball containing a specific list: /etc/ssl/certs/ca-certificates.crt from the ca-certificates package, /usr/share/zoneinfo from tzdata, /etc/passwd and /etc/group with root and a nonroot user at UID and GID 65532, /etc/nsswitch.conf, and /tmp. The base variant adds glibc, libssl and openssl’s runtime pieces. The cc variant adds libstdc++ and libgcc on top of that. The static variant adds none of those, which is why it only works for binaries that link nothing at run time.
That list explains the consequences directly. There is no /bin/sh, so CMD npm start — shell form — cannot run: Docker rewrites shell form to /bin/sh -c "npm start" and the exec fails before your process exists. Every CMD and ENTRYPOINT must be exec form, a JSON array of strings. There is no apt, so a RUN apt-get install in the final stage is a build error, not a runtime one. There is no ls, cat or curl, so HEALTHCHECK CMD curl -f http://localhost:8080/healthz fails permanently and reports the container unhealthy forever.
For debugging, every distroless image publishes a parallel :debug tag. gcr.io/distroless/static-debian12:debug-nonroot is the same image plus a busybox userland at /busybox, with /busybox/sh available as a shell. It is a real image you can build and push, which makes it a legitimate escape hatch when you need to inspect a filesystem — and a thing to keep out of production, because you have just put a shell back.
Step-by-step
1. Measure the image you have now. You need a baseline number or the rest of this is unfalsifiable.
docker image ls myapp --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}'
REPOSITORY TAG SIZE
myapp 1.4.0 1.12GB
2. Find out where the weight is. docker history attributes size to the layer that created it.
docker history myapp:1.4.0 --format 'table {{.Size}}\t{{.CreatedBy}}' | head -8
SIZE CREATED BY
12.4MB RUN /bin/sh -c go build -o /app ./cmd/server # buildkit
188MB RUN /bin/sh -c go mod download # buildkit
0B WORKDIR /src
809MB /bin/sh -c #(nop) ADD file:... in /
0B ENV PATH=/usr/local/go/bin:...
The application is 12 MB of a 1.12 GB image. Everything above it is toolchain and base OS.
3. Write the multi-stage Dockerfile for the static case. A Go binary built with CGO_ENABLED=0 links nothing, which makes static-debian12 correct.
# syntax=docker/dockerfile:1
FROM golang:1.24-bookworm AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# CGO_ENABLED=0 is what makes the binary safe for the static variant
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags='-s -w' -o /out/app ./cmd/server
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /out/app /app
USER nonroot:nonroot
EXPOSE 8080
# Exec form is mandatory: there is no /bin/sh to interpret shell form
ENTRYPOINT ["/app"]
4. Write the dynamic case for an interpreted app. The Python variant already sets ENTRYPOINT to the interpreter, so your CMD supplies only the arguments.
# syntax=docker/dockerfile:1
FROM python:3.12-slim-bookworm AS builder
RUN apt-get update && apt-get install -y --no-install-recommends build-essential \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --target=/build/deps -r requirements.txt
FROM gcr.io/distroless/python3-debian12:nonroot
WORKDIR /app
COPY --from=builder /build/deps /app/deps
COPY src/ /app/src/
ENV PYTHONPATH=/app/deps
USER nonroot:nonroot
EXPOSE 8080
# ENTRYPOINT is already the python3 interpreter in this base image
CMD ["-m", "src.main"]
The interpreter is dynamically linked against glibc, which the python3 variant carries. Note that the distroless project marks its language-specific images (Python, Node) as experimental and pins one interpreter version per tag — worth knowing before you standardise on them.
5. Build both and compare.
docker build -t myapp:1.4.0-distroless -f Dockerfile.distroless .
docker image ls myapp --format 'table {{.Tag}}\t{{.Size}}'
TAG SIZE
1.4.0-distroless 14.2MB
1.4.0 1.12GB
6. Confirm there is genuinely no shell. This command is supposed to fail. If it succeeds, you did not land on distroless.
docker run --rm --entrypoint sh myapp:1.4.0-distroless -c 'echo hello'
docker: Error response from daemon: failed to create task for container: failed to
create shim task: OCI runtime create failed: runc create failed: unable to start
container process: exec: "sh": executable file not found in $PATH: unknown.
7. Run it and confirm the app answers.
docker run -d --name myapp -p 8080:8080 myapp:1.4.0-distroless
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/healthz
200
8. Debug with the :debug tag when you need a filesystem view. Make the runtime base a build argument so you never edit the Dockerfile to debug it. The ARG has to sit above the first FROM to be usable in a FROM line:
# syntax=docker/dockerfile:1
ARG RUNTIME=gcr.io/distroless/static-debian12:nonroot
FROM golang:1.24-bookworm AS builder
# ... unchanged builder stage ...
FROM ${RUNTIME}
COPY --from=builder /out/app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]
Now the debug image is a flag, not a diff:
docker build -t myapp:debug \
--build-arg RUNTIME=gcr.io/distroless/static-debian12:debug-nonroot .
docker run --rm --entrypoint /busybox/sh myapp:debug -c 'ls -l / && ls /etc/ssl/certs'
total 12448
-rwxr-xr-x 1 root root 12744704 Jul 30 11:02 app
drwxr-xr-x 2 root root 4096 Jan 1 1970 etc
drwxrwxrwx 2 root root 4096 Jan 1 1970 tmp
drwxr-xr-x 5 root root 4096 Jan 1 1970 usr
ca-certificates.crt
9. Attach to the container you already have, without rebuilding. docker debug mounts a toolbox into a running container and needs no shell inside it. It is a Docker Desktop feature on a paid subscription, so treat it as convenient rather than universal:
docker debug myapp
Attaching to container myapp. Type "exit" to detach.
Builtin commands:
- install [tool1] [tool2] ... Add Nix packages to this debug shell
- entrypoint Print the entrypoint of the container
root@myapp / # ls /
app etc nix tmp usr
On Kubernetes the equivalent is an ephemeral container sharing the target’s namespaces:
kubectl debug -it pod/myapp-7d9f8c4b6-xk2ab --image=busybox:1.36 \
--target=myapp --profile=general -- sh
Targeting container "myapp". If you don't see processes from this container it may
be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-7xk4p.
If you don't see a command prompt, try pressing enter.
/ # ls /proc/1/root/
app etc tmp usr
--target is the part that matters: without it you get a sidecar that shares only the network namespace, and /proc/1 belongs to the debug container instead of your app.
Validate it works
Four checks, in this order.
The process runs as UID 65532, not root. You cannot run id inside the container, so read it from the host:
docker top myapp -o user,pid,args
USER PID COMMAND
65532 48213 /app
The application answers over HTTP. Already covered by step 7, but check a real route, not just the health endpoint:
curl -s http://localhost:8080/api/version
{"version":"1.4.0","commit":"9f2ad41","go":"go1.24.5"}
Outbound TLS resolves and verifies. This is the cheapest proof that the CA bundle is present and readable. Hit an endpoint in your app that makes an HTTPS call out:
curl -s http://localhost:8080/api/upstream-check
{"upstream":"https://api.stripe.com","tls":"ok","chain_verified":true}
If this returns an x509 error, see the troubleshooting entry below — the fix is the base variant, not your code.
The package count dropped. Scan both tags and compare. Details on wiring this into CI are in Docker image security scanning.
trivy image --scanners vuln --severity HIGH,CRITICAL myapp:1.4.0-distroless
myapp:1.4.0-distroless (debian 12.6)
Total: 0 (HIGH: 0, CRITICAL: 0)
app (gobinary)
Total: 1 (HIGH: 1, CRITICAL: 0)
The OS layer reports zero findings because there are two packages in it. What is left is your own dependency tree, which is where it belongs.
Troubleshooting
exec /app: no such file or directory and the file is clearly there. The kernel is reporting a missing interpreter, not a missing file. Your binary is dynamically linked and the static variant has no dynamic loader. Check with docker run --rm --entrypoint /busybox/sh myapp:debug -c 'ldd /app' on the debug tag, or file the binary in the builder stage. Either rebuild with CGO_ENABLED=0, or switch the final FROM to gcr.io/distroless/base-debian12:nonroot (glibc) or gcr.io/distroless/cc-debian12:nonroot (glibc plus libstdc++). The same error appears when the binary was built for a different architecture — an amd64 binary on an arm64 host. Add --platform=$BUILDPLATFORM to the builder FROM and pass GOARCH=$TARGETARCH through.
x509: certificate signed by unknown authority on every outbound call. You landed on a base that has no CA bundle, most often scratch or a hand-rolled minimal image, or you overwrote /etc/ssl/certs. The static, base and cc distroless variants all include ca-certificates.crt. If you are on scratch and want to stay there, copy it from the builder stage explicitly: COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/. If you need an internal CA, append your PEM to that file in the builder stage before copying.
/bin/sh: not found or exec: "npm": executable file not found. Your CMD or ENTRYPOINT is in shell form. CMD node dist/server.js becomes /bin/sh -c "node dist/server.js", which cannot run. Rewrite as CMD ["node", "dist/server.js"]. The same rule kills anything that used shell features: CMD ["sh", "-c", "migrate && serve"] needs to become two containers, an init container, or a small wrapper binary. Environment variable expansion in exec form also stops working, so ENTRYPOINT ["/app", "--port=$PORT"] passes the literal string — read the variable inside your application instead.
permission denied writing to a path. UID 65532 owns nothing on the filesystem. /tmp exists and is world-writable, so temp files are fine. Anything else — a cache directory, a socket path, an SQLite file — needs either a mounted volume with matching ownership, or a COPY --chown=nonroot:nonroot and a RUN mkdir performed in the builder stage and copied across, since you cannot mkdir in the distroless stage.
Timestamps are always UTC even with TZ set. The base images carry /usr/share/zoneinfo, so TZ=America/Montreal works for Go and Python. What is missing is /etc/localtime, which some libraries read directly instead of consulting TZ. If your language runtime reads that file, create the symlink in the builder stage and copy it, or set TZ explicitly in the Dockerfile with ENV TZ=America/Montreal and confirm your logging library honours it.
HEALTHCHECK reports unhealthy forever. Anything shaped like HEALTHCHECK CMD curl -f http://localhost:8080/healthz is dead, because curl and the shell are both gone. Options: drop the Dockerfile healthcheck and use the orchestrator’s HTTP probe (httpGet in a Kubernetes readiness probe, or Compose healthcheck with test: ["CMD", "/app", "-healthcheck"]), or add a -healthcheck flag to your own binary so the check is exec form against a binary that exists.
When this is the wrong approach
Distroless is a poor fit for an application that legitimately shells out. If your service invokes ffmpeg, pg_dump, git, rsync or imagemagick as subprocesses, you will spend more time copying binaries and their transitive libraries into the runtime stage than you save in image size. Use a slim base with the tools installed and pinned.
It also fights a team whose entire debugging habit is kubectl exec -it pod -- bash. That habit is replaceable with ephemeral containers, but the replacement has to be taught, documented, and available in every cluster — ephemeral containers need EphemeralContainers support and RBAC that many managed clusters restrict. If an on-call engineer at 3 a.m. cannot get into a container, you have moved risk rather than reduced it.
Skip it if you have no scanner in CI. Minimal bases pay off through a smaller package inventory, and the only way to notice when someone quietly adds apt-get install to a builder stage that then copies /usr wholesale is automated scanning on every build. Without that feedback loop the image drifts back to where it started within a quarter.
Finally, check that the base is actually your size problem. If your image is 900 MB because node_modules is 700 MB, or because a model checkpoint got baked into a layer, moving from debian:bookworm to distroless saves 80 MB and solves nothing. Read docker history first — the numbers tell you where to spend the effort.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.