Christian Lehnert — Linux, Hacking & Faith

Dockerfile Hardening - What Never Belongs in Your Image

Christian Lehnert • 2026-11-29 • ~7 min read

Dockerfile Hardening

Hardening Is Subtraction

When I test a containerized application, the interesting findings are
almost never a clever kernel escape. They are boring. The production
image still contains the full build toolchain. It runs as root. Pulling
it and running docker history shows an API token that was passed as a
build argument. Unpacking the layers finds a .env file that was copied
in with the rest of the repository and deleted two layers later, which
removed it from the final filesystem and from nowhere else.

None of that needs an attacker to be clever. It needs someone to look.
Image hardening is therefore mostly subtraction: every file, binary, and
privilege that is not required at runtime is attack surface, and the
Dockerfile is where you decide what gets in. Everything below is a
build-time decision. Runtime controls come at the end.

Build in One Stage, Ship From Another

The single biggest improvement is a multi-stage build. The first stage
has the compiler, the package manager, the dev dependencies, and your
source. The final stage gets only the artifact.

 1# syntax=docker/dockerfile:1
 2FROM golang:1.25@sha256:... AS build
 3WORKDIR /src
 4COPY go.mod go.sum ./
 5RUN --mount=type=cache,target=/go/pkg/mod go mod download
 6COPY . .
 7RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/app ./cmd/app
 8 
 9FROM gcr.io/distroless/static-debian12:nonroot@sha256:...
10COPY --from=build /out/app /app
11USER 65532:65532
12ENTRYPOINT ["/app"]

The final image contains one static binary, some CA certificates and
timezone data from the base, and nothing else. No shell, no package
manager, no compiler, no source code. An attacker who gets code
execution in this container has no sh, no curl, and no apt to
bootstrap from. They have to bring everything themselves, which is
slower and much louder.

Interpreted languages work the same way. Install dependencies in a
build stage, then copy the installed tree or virtualenv into a slim or
distroless runtime image. You lose more convenience here than with Go,
and you still win.

Pick a Minimal Base and Pin It

The base image is usually the bulk of the CVE count, and most of those
CVEs are in software your app never calls. A distroless or hardened
base removes that software instead of patching it. I covered this in
the Minimus post, so here only the part people skip: pin the base by
digest, not by tag.

A tag like python:3.12-slim is a mutable pointer. It points at a
different image next week, and if the registry or the upstream account
is compromised, it can point at anything. A digest
(@sha256:...) is the content hash of exactly one image. Your build
gets the same bytes every time, and a change to the base becomes a
visible diff in a pull request instead of a silent swap.

The obvious objection is that pinned digests go stale. That is what
Renovate is for. It pins digests, opens a pull request when upstream
publishes a new one, and your CI rebuilds and tests it. Same pattern as
the Renovate for Ansible post: pin everything, let a bot do the
bumping.

Run as a Numeric Non-Root User

Containers run as root by default. Root inside a container is not root
on the host, but it is much closer than it should be. Any container
escape or misconfigured mount is far worse starting from UID 0.

Set a user in the Dockerfile, and make it numeric:

1USER 65532:65532

The numeric part matters. Kubernetes runAsNonRoot: true has to verify
that the image does not run as root, and it can only do that with a
numeric UID. With USER appuser and no runAsUser in the pod spec,
the kubelet cannot resolve the name and refuses to start the container. Distroless images ship a nonroot user
with UID 65532 for exactly this reason. On other bases, create a user
with a fixed UID and use the number.

And make sure that user cannot write to the application files. Copy
them owned by root and readable by everyone, so a compromised process
cannot modify its own code.

Secrets Never Go in a Layer

This is the most common real finding, so it gets its own section.

Every RUN, COPY, and ADD produces a layer, and layers are
immutable. Deleting a file in a later step hides it from the final
filesystem but leaves it in the earlier layer, where anyone who pulls
the image can extract it. Build arguments are no better: values used in
RUN steps show up in the image history. ARG NPM_TOKEN followed by
RUN npm ci ships your token to everyone with pull access to the
registry.

BuildKit solves this with secret mounts. The secret is available for
one RUN step and never written to a layer:

1RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
1docker build --secret id=npmrc,src=$HOME/.npmrc .

Runtime secrets do not belong in the image at all. They come from the
environment at runtime, from a secret store, or, on Azure, from a
managed identity that removes the secret entirely.

Control What Enters the Build

COPY . . copies the whole build context, and the build context is
whatever is in the directory. That includes .git with its full
history, .env files, local SSH or cloud credentials, test data, and
the occasional database dump. A .dockerignore decides what the build
can see, and it should be written as an allowlist where possible:
exclude everything, then include only what the build needs.

Two smaller rules in the same spirit. Use COPY, not ADD, unless you
specifically need what ADD does, because ADD can fetch remote URLs
and silently unpack archives. And when you do install packages in a
Debian-based stage, use --no-install-recommends and clean the package
lists in the same RUN step, because a cleanup in a later layer saves
nothing.

Let CI Enforce It

A hardened Dockerfile is a snapshot. The pipeline is what keeps it
hardened.

Scan every image with Trivy or Grype, and fail the build on fixable
critical vulnerabilities rather than reporting them into a dashboard
nobody reads. Generate an SBOM so you can answer "are we affected" in
minutes when the next big CVE drops. Sign the image with cosign and
verify the signature at deploy time, so the cluster only runs images
your pipeline actually built. And rebuild on a schedule, even without
code changes, because a minimal image with a two-month-old base is no
longer minimal in CVEs.

Where the Image Stops

Image hardening reduces what an attacker can use after getting in. It
does not stop them getting in, and it does not constrain the container
at runtime. That half lives in how the container is started:

1docker run --read-only --cap-drop ALL \
2  --security-opt no-new-privileges \
3  --user 65532:65532 myimage@sha256:...

A read-only root filesystem, no Linux capabilities, no privilege
escalation through setuid binaries, and the same non-root user. In
Kubernetes this is the pod's securityContext. The tank-os post goes
further with egress filtering and an unprivileged agent user, and the
agent-sandbox comparison covers when namespace isolation is not enough
and you need gVisor or a microVM.

The two halves depend on each other. A well-built image is what makes
--read-only and --cap-drop ALL work without breaking the app, and
strict runtime flags are what make a leftover mistake in the image
harder to exploit.

The Takeaway

Treat every file in the final image as something you have to justify.
Build in one stage and ship from another. Start from a minimal base
pinned by digest and let Renovate move it. Run as a numeric non-root
user. Mount secrets at build time instead of copying them, and keep the
build context to an allowlist. Then let CI scan, sign, and rebuild so
the image stays that way. None of this is clever. That is the point:
the findings it prevents are not clever either.

Tagged:
#docker #containers #devops
← Back to posts