Dockerfile and Image Hardening
The image is the part of a container you control completely, and most container findings start there: a process running as root, a base image full of tools an attacker would love to find (shells, package managers, curl), a latest tag that silently changes, a token baked into a layer. None of these is an exploit by itself; each one decides how far an attacker gets after the application is compromised, and how easy it is to know what you are running. Container Security introduced the basic rules from the builder's side; Tags vs Digests and Scanning with Trivy cover pinning and vulnerability scanning. This lesson takes the reviewer's view: what to look for in a Dockerfile, why each finding matters to an attacker, and how a scanner checks it.
What a reviewer looks for
| Finding | Why it matters after a compromise | Fix |
|---|---|---|
Runs as root (no USER) |
root in the container owns every file in it, can install tools, and is one capability or kernel bug from root on the host | USER with a fixed non-zero UID; files owned by root, read-only to the app |
| Large base with shell and package manager | the attacker gets sh, apt, curl, compilers: a full toolkit |
slim or distroless bases; multi-stage builds that copy only the artefact |
Mutable tag (latest, 3.13) |
the image can change under you; no reproducible review or rollback | pin by digest (@sha256:…), update with a bot |
Secrets in ENV, ARG or copied files |
readable by anyone who can pull the image, forever, from any layer | build secrets (RUN --mount=type=secret), runtime secrets from a manager |
ADD of remote URLs, unpinned downloads |
unverified code in the image | download in a build stage with a checksum check |
Unneeded ports (22) and packages (sudo) |
extra services and privilege tools | remove them; no SSH in containers |
| Writable root filesystem | lets an attacker drop and run binaries | readOnlyRootFilesystem: true at run time, write only to mounted volumes |
Two Dockerfiles, one scanner
The session writes the Dockerfile as first submitted and the reviewed version, and runs Trivy's Dockerfile checks on both. It runs in your sandbox on local files; the digests are placeholders in the right format, not real images.
mkdir before after
cat > before/Dockerfile <<'DF'
FROM python:latest
ENV API_TOKEN=lab-not-a-real-token
ADD https://downloads.lab.test/tool.tar.gz /opt/
RUN apt-get update && apt-get install -y curl sudo
COPY . /app
RUN pip install -r /app/requirements.txt
EXPOSE 22 8000
CMD python /app/main.py
DF
cat > after/Dockerfile <<'DF'
FROM python:3.13-slim@sha256:3b5e2f0c8a1d9e7f6c4b2a0918273645f0e1d2c3b4a5968778695a4b3c2d1e0f AS build
WORKDIR /src
COPY requirements.txt .
RUN pip install --no-cache-dir --target /deps -r requirements.txt
COPY app/ ./app/
FROM gcr.io/distroless/python3-debian12:nonroot@sha256:9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b
WORKDIR /app
COPY --from=build /deps /deps
COPY --from=build /src/app /app
ENV PYTHONPATH=/deps
USER nonroot
EXPOSE 8000
HEALTHCHECK NONE
ENTRYPOINT ["python3", "/app/main.py"]
DF
for d in before after; do
echo "== $d: $(trivy config -q -f json $d | jq '[.Results[].Misconfigurations[]?] | length') findings"
trivy config -q -f json $d | jq -r '[.Results[].Misconfigurations[]?] | sort_by(.ID)[] | " \(.Severity) \(.ID) \(.Title)"'
done== before: 6 findings
MEDIUM DS-0001 ':latest' tag used
HIGH DS-0002 Image user should not be 'root'
MEDIUM DS-0004 Port 22 exposed
LOW DS-0026 No HEALTHCHECK defined
HIGH DS-0029 'apt-get' missing '--no-install-recommends'
CRITICAL DS-0031 Secrets passed via `build-args` or envs or copied secret files
== after: 0 findings
The scanner found six problems in the first version, from the CRITICAL token in an ENV instruction to the missing HEALTHCHECK, and none in the second. Two things it did not flag are worth noticing: the ADD of a remote URL (a reviewer's finding, not a scanner rule here) and the COPY . /app, which copies whatever is in the build context, including .env files and .git, unless a .dockerignore excludes them (.dockerignore). HEALTHCHECK NONE in the hardened file is a deliberate, documented choice: the orchestrator's probes do the job, and distroless has no shell for a check command.
Why "deleted" secrets survive in images
An image is a stack of layers; each instruction adds one, and deleting a file in a later layer only adds a whiteout marker that hides it. The earlier layer, with the file in it, is still part of the image and is downloaded by everyone who pulls it. The program models a three-layer image built by a careless Dockerfile and shows what the running container sees versus what anyone can extract from the layers.
# each layer: files added (path -> content) and whiteouts (paths deleted by this layer)
layers = [
("FROM python:3.13-slim", {"/usr/bin/python3": "<binary>"}, set()),
("COPY deploy-key.pem /root/.ssh/id_ed25519 && RUN git clone ...",
{"/root/.ssh/id_ed25519": "-----BEGIN OPENSSH PRIVATE KEY----- (lab key) ...", "/app/main.py": "print('hi')"}, set()),
("RUN rm /root/.ssh/id_ed25519", {}, {"/root/.ssh/id_ed25519"}),
]
def container_view(layers):
fs = {}
for _, added, whiteouts in layers:
for p in whiteouts:
fs.pop(p, None)
fs.update(added)
return fs
view = container_view(layers)
print("files visible in a running container:", sorted(view))
print("\nwhat `docker save` + untar of each layer reveals:")
for i, (instr, added, whiteouts) in enumerate(layers):
for p, content in added.items():
flag = " <-- SECRET, still in the image" if "PRIVATE KEY" in content else ""
print(f" layer {i} ({instr[:28]}...) {p}{flag}")
for p in whiteouts:
print(f" layer {i} whiteout .wh.{p.rsplit('/', 1)[1]} (hides, doesn't remove)")files visible in a running container: ['/app/main.py', '/usr/bin/python3']
what `docker save` + untar of each layer reveals:
layer 0 (FROM python:3.13-slim...) /usr/bin/python3
layer 1 (COPY deploy-key.pem /root/.s...) /root/.ssh/id_ed25519 <-- SECRET, still in the image
layer 1 (COPY deploy-key.pem /root/.s...) /app/main.py
layer 2 whiteout .wh.id_ed25519 (hides, doesn't remove)
The running container shows no key, and a review that only looks at the final filesystem would miss it. Image secret scanners (trivy image --scanners secret) and tools that unpack every layer find it. The fixes: never COPY secrets into a build stage that ends up in the image; use BuildKit secret mounts (RUN --mount=type=secret,id=deploy_key …), which are never written to a layer; or do the step in a build stage whose layers aren't shipped (multi-stage). And rotate the key: the image has already been pulled.
How image weaknesses are detected
- In the pipeline: Dockerfile checks (
trivy config, hadolint), image vulnerability and secret scans of the built image, an SBOM per image (SBOMs). - In registries: continuous rescans of stored images; policies that flag images without a non-root user or older than N days.
- At admission: reject pods whose images aren't pinned by digest, aren't signed, or come from untrusted registries (Admission Control, Kyverno and policy-controller).
- At runtime: a shell or package manager starting in a container that shouldn't have one is a classic runtime detection (Runtime Detection).
How it is fixed
- Multi-stage builds ending in a minimal base (distroless,
-slim, Alpine, orscratchfor static binaries). - A fixed non-root
USER(numeric UID helps KubernetesrunAsNonRootchecks), files owned by root and not writable by the app. - Pin by digest and let an update bot propose new digests (Update Bots).
- No secrets at build time in layers; build-secret mounts for what the build needs, a secret manager for what the app needs.
- Scan and sign, and enforce both at admission.
Pitfalls
USER rootadded "temporarily" to fix a permission error, and never removed.- Pinning the base by digest but installing unpinned packages in
RUNsteps: the image still changes between builds. - Squashing layers to "remove" secrets and pushing the unsquashed image too.
Practice
1. Which findings would remain in the "before" Dockerfile if you only changed the first line to a digest-pinned python:3.13-slim?
Five: root user, port 22, missing HEALTHCHECK, apt-get without --no-install-recommends, and the CRITICAL secret in ENV. Pinning fixes reproducibility, not privilege or secrets.
2. In the layer model, move the rm into the same instruction as the COPY. Does that help?
A COPY can't delete in the same layer; with RUN cp … && use … && rm … in one RUN, the file never appears in a committed layer, but the key still had to be in the build context and possibly in an earlier COPY. Use a secret mount instead.
3. Why is HEALTHCHECK NONE acceptable in the hardened file?
The container runs on Kubernetes, which ignores Docker's HEALTHCHECK and uses liveness and readiness probes; and the distroless base has no shell or curl to run a check with. Writing NONE documents the decision and satisfies the scanner without adding tools.
Test yourself
Which finding did Trivy rate CRITICAL in the first Dockerfile?
- The latest tag
- A secret passed through ENV
- Port 22
- The missing HEALTHCHECK
Why is a secret deleted in a later layer still a leak?
- It isn't
- The earlier layer still contains the file; the later one only adds a whiteout
- Docker caches it on the host only
- Registries keep a backup
What does pinning a base image by digest give you?
- Fewer vulnerabilities
- An immutable, reviewable base that can't change under the same reference
- A non-root user
- Smaller images
Why do minimal bases matter after a compromise?
- They are faster
- The attacker finds no shell, package manager or download tools to work with
- They have no vulnerabilities
- They disable networking