Containers and Docker: layers, Dockerfile pitfalls, multi-stage builds, registries

An image is layers plus a manifest, addressed by digest. Build small, pin everything, run as non-root, and never deploy a moving tag.

Read the briefing
About 8 min to read 8 drills

What to remember

  1. Pin by digest; 'latest' is not a version. A scale-up pulls a different build and your rollback has nothing exact to return to.
  2. Order Dockerfile layers by change frequency. Dependencies before source, so a code edit does not re-download the world.
  3. Multi-stage builds keep the toolchain out of production. Compile in one stage, copy the artefact into a minimal runtime. Smaller image, smaller attack surface.
  4. exec in the entrypoint, or PID 1 is a shell. A shell that does not forward SIGTERM means every stop takes the full grace period and then SIGKILL.
  5. A layer is never deleted, only hidden. A secret added and then removed in a later layer is still in the image. Rebuild, do not patch.

The big picture

A container image is a stack of immutable filesystem layers plus a small JSON config, addressed by a content digest and pointed at by mutable tags. Almost every Dockerfile pitfall an interviewer asks about (slow builds, leaked tokens, "we deployed the fix and three nodes still run the old code", a HEALTHCHECK that does nothing on Kubernetes) follows from those two facts, which is why loops use Dockerfiles as a cheap probe of whether you understand the artifact you ship.

The mental model

Picture the image as a git history you can only append to: each instruction commits a diff on top of the previous one, a later "delete" is a new commit that hides a path rather than rewriting the past, and the build cache is a lookup keyed by "same instruction, same inputs, same parent". A tag is a branch name that can be force-moved; a digest is a commit hash. Copy order, secrets, multi-stage builds, and pull policy are all consequences of that picture.

In depth

Layers and the build cache

Each RUN, COPY, and ADD produces a layer: a tarball of the filesystem changes that instruction made, identified by the digest of its contents. Instructions like ENV, USER, EXPOSE, CMD, and HEALTHCHECK change only the image config and add empty layers. The final image is the ordered list of layer digests plus the config, and the manifest that lists them is what repo@sha256:... names.

The cache rule is precise: a layer is reused only when the instruction text is identical, its inputs are unchanged, and every earlier layer was itself a cache hit. For COPY and ADD the inputs are the checksums of the copied files (not their mtimes). For RUN the input is the command string, nothing more: RUN apt-get update && apt-get install -y curl hits the cache forever even when upstream packages change, which is why security rebuilds use --no-cache or a changing ARG. Once one layer misses, everything after it is rebuilt.

Two habits follow. Read docker history <image> bottom-up to see which instruction produced which bytes; a 400 MB COPY . /app means .git or node_modules went in and a .dockerignore is missing. And when a build is slow, ask "which layer misses first, and what input changed?" rather than reaching for --no-cache, which guarantees the slow path. BuildKit (the default builder) adds parallel stages, cache mounts (RUN --mount=type=cache,target=/root/.npm), and remote cache export (--cache-to type=registry), all built on the same rule.

Copy order: volatile inputs last

Because a miss invalidates everything after it, a Dockerfile is ordered by how often each input changes. Dependency manifests change rarely; source changes on every commit. So:

FROM node:20-bookworm-slim@sha256:<digest>
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
USER node
CMD ["node", "server.js"]

The npm ci layer's inputs are the two manifest files; a source edit invalidates only the cheap COPY . . at the end. The anti-pattern, COPY . . followed by the install, makes every build reinstall everything, and it is the single most common finding in take-home Dockerfiles.

.dockerignore is part of the same mechanism: it decides what enters the build context, so node_modules, .git, local .env files, and build outputs never reach a COPY and never bust its checksum. Interviewers follow up with "why did fewer layers not help?": squashing instructions changes layer count, not inputs, so a combined copy-and-install step still has the whole tree as input and still misses on every edit. The tell of understanding is talking about inputs and invalidation, not about the number of layers.

Tags are pointers, digests are content

An image reference is registry/repo:tag or registry/repo@sha256:<digest>. The digest is the hash of the manifest, so it can never name different bytes; a tag is a mutable label that any push can move. latest is just a tag with no semantics, and stable, prod, and v1 are the same kind of thing.

The kubelet's pull policy decides how much it trusts a tag it has already pulled. IfNotPresent (the default for any tag except latest) uses whatever image is cached under that name, so after a push to api:stable and a rollout restart, nodes that pulled last week keep serving last week's code. Always re-pulls, but the Deployment's pod template did not change, so there is no new revision, nothing to rollout undo to, and no record of which build ran where. The fix is identity, not policy: deploy a per-build tag or, better, the digest, so a new build is a spec change and every node pulls exactly that content.

Digests are also how you answer "what is running?": kubectl get pods -A -o jsonpath='{..imageID}' lists the resolved digests, and registry scanners attach findings to digests, so an inventory is a join between those two lists. Anything keyed on tags cannot answer the question, because base-debian:12 has pointed at many different digests over its life.

Deleted files and secrets still ship

Layers are additive. RUN rm /app/.npmrc in a later instruction writes a whiteout entry that hides the path in the merged view; the 221-byte file is still in the earlier COPY layer, and anyone who can pull the image can docker save it and read the file out of that layer's tar. docker history shows the pattern: the rm layer is 0 B, the COPY layer is not. A secret that was ever in a shipped layer is leaked and must be rotated; deleting it afterwards changes nothing.

ENV and ARG are worse in a different way: they live in the image config, so docker inspect prints them and every container inherits them, and no rm reasoning applies at all. ARG values used in a RUN also end up in the layer's history string.

The two correct tools are BuildKit secret mounts, where the secret exists only for the duration of one RUN and never in a layer:

RUN --mount=type=secret,id=npmrc,target=/app/.npmrc npm ci --omit=dev
# docker build --secret id=npmrc,src=$HOME/.npmrc .

and multi-stage builds, where the stage that saw the secret is not the stage you ship. --mount=type=ssh does the same for private git dependencies. Reviewers grep for ENV .*TOKEN, COPY .npmrc, COPY .env, and curl -H "Authorization" in RUN lines; interviewers hand you a docker history and ask whether the rm line proves anything.

Multi-stage builds and distroless runtimes

Only the final stage's layers become the image. A multi-stage Dockerfile compiles in a builder stage with the full toolchain and copies just the artifact into a minimal runtime stage:

FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/api ./cmd/api

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

The compiler, the source, and any build-time credentials never exist in a shipped layer, and the image shrinks from a gigabyte to tens of megabytes. COPY --from is as much a filter as a copy.

Distroless and scratch bases remove the shell and package manager, which cuts attack surface and removes most base-image CVE noise from scanners. What you give up: no sh to exec into, so debugging moves to kubectl debug -it <pod> --image=busybox --target=<container> (an ephemeral container sharing the PID namespace) or to a separately built :debug tag; you must remember CA certificates, tzdata, and libc compatibility (static linking or a -base image that carries glibc). The decision rule interviewers want: self-contained binaries (Go, a JVM with a bundled runtime) are good candidates; a Python service with many native wheels usually stops at a slim Debian base because distroless buys less and costs more debugging friction.

Root, USER, and HEALTHCHECK on Kubernetes

Without a USER instruction the process runs as uid 0. Namespaces isolate what the process can see, not who it is: root inside the container is root to the host kernel unless user namespaces remap it, so a container escape or a mounted host path is immediately a root problem. Set USER to a non-root account, preferably a numeric uid (USER 10001) so that Kubernetes runAsNonRoot: true and Pod Security admission can verify it without resolving names inside the image; create the user in the Dockerfile if the base image lacks one, and make writable paths owned by it.

HEALTHCHECK --interval=10s CMD curl -f http://localhost:8080/healthz || exit 1 is metadata that the Docker daemon and Compose act on: the daemon runs the command and flips the container's health status, and Compose uses it for depends_on: condition: service_healthy. Kubernetes never executes it. The kubelet's contract is the pod spec: a readinessProbe removes the pod from Service endpoints while it fails, a livenessProbe restarts the container, a startupProbe gates both until a slow process is up. A Compose stack ported to Kubernetes with its HEALTHCHECKs intact has no health signal at all until probes are added, and the usual follow-up is which probe a dependency outage needs (readiness, so 500s stop reaching users; not liveness, since a restart does not fix a downstream). Note also that curl is often absent from slim and distroless images, so even under Docker the check must use something the image contains.

Myths and facts

Myth: If a later RUN deletes the file, it is not in the image.

Fact: Layers are additive; the delete adds a whiteout and the bytes stay in the earlier layer, one docker save away. Use a secret mount or a build stage you do not ship, and rotate anything that ever landed in a layer.

Myth: latest means the newest stable release.

Fact: latest is an ordinary mutable tag with no semantics; it is whatever was pushed last under that name, and it may never have been pushed at all.

Myth: Kubernetes runs the Dockerfile HEALTHCHECK.

Fact: The kubelet ignores it entirely and runs only the liveness, readiness, and startup probes in the pod spec.

Myth: Fewer layers make the build cache work better.

Fact: Invalidation is decided by an instruction's inputs, not by the layer count; a merged copy-and-install step still has the whole source tree as input and misses on every edit.

Myth: --no-cache fixes a cache that keeps missing.

Fact: It guarantees the slow path. A cache that misses has an input that changes every build; find that input (usually COPY . . too early) and move it later.

Myth: Setting imagePullPolicy: Always is how you make sure nodes get the new build.

Fact: It makes nodes re-pull a moving tag but leaves the Deployment revision unchanged, so there is no rollback target and no record of what ran. Deploy by digest or immutable tag instead.

How pros do it

  • Pin base images by tag and digest (FROM node:20-bookworm-slim@sha256:...) and let a bot open the bump PRs; never FROM x:latest in a Dockerfile that ships.
  • Order instructions by volatility: manifests, then dependency install, then source; keep .git, node_modules, and local env files out with .dockerignore.
  • Never put a credential in ENV, ARG, or a COPY that a later layer 'removes'; use RUN --mount=type=secret (or type=ssh) and multi-stage builds so no shipped layer ever held it.
  • Set a non-root numeric USER, make writable paths owned by it, and enforce runAsNonRoot in the pod spec; treat root in a container as root on the node.
  • Ship the final stage only: compile in a builder stage, COPY --from the artifact into a slim or distroless runtime, and keep a documented debug path (ephemeral debug container or a :debug tag).
  • Deploy and inventory by digest: CI writes repo@sha256:... into manifests, scanners key on digests, and an admission policy refuses unsigned images or critical findings.
  • On Kubernetes, express health as readiness, liveness, and startup probes in the pod spec; keep HEALTHCHECK only for Docker and Compose users of the same image.

Questions people ask

Why does my build reinstall every dependency when I change one line of source?

Say the cache rule first: a layer is reused only when the instruction and its inputs are unchanged and every earlier layer hit; COPY . . before the install puts the whole tree in the install layer's inputs, so it misses on every commit. Then the fix: copy the manifests, install, then copy the source, with .dockerignore keeping node_modules and .git out; prove it with docker history showing the install layer reused.

Is running as root inside a container actually dangerous?

Yes, and explain it as identity versus view: namespaces isolate what the process sees, not who it is, so root in the container is root to the host kernel unless user namespaces remap it; a mounted host path, a kernel bug, or a misconfigured runtime then hands root on the node to whoever controls the process. Finish with the fix: a non-root numeric USER and runAsNonRoot enforced in the pod spec.

I deleted the token file with rm in the Dockerfile. Is it gone?

No, and say why in one sentence: layers are additive, so the rm adds a whiteout that hides the path while the bytes stay in the layer that copied it, one docker save or registry pull away. Then the order of operations: rotate the token first, then rebuild with RUN --mount=type=secret or a build stage you do not ship.

Should I use imagePullPolicy: Always so nodes always get the newest image?

Only as a stopgap, and say what the real fix is: stop moving tags. Deploy a per-build tag or the digest so a new build changes the pod template, every node pulls that exact content, and rollout undo has something to return to. Caveat to add: Always also makes every pod start depend on the registry being up.

How do I debug a distroless container that has no shell?

Give the command: kubectl debug -it <pod> --image=busybox:1.36 --target=<container> attaches an ephemeral container sharing the process namespace, so ps, ss, and /proc/<pid>/ show the application; many distroless images also publish a :debug tag with busybox. Say that the debug path is decided before the first incident, not during it.

How do I find every running pod built from a vulnerable base image?

Answer with a join, not a grep: collect running digests (kubectl get pods -A -o jsonpath='{..imageID}'), then join them to the scanner's per-digest findings and to the base-image digests that carry the CVE. Say why tags cannot answer it (base:12 has pointed at many digests). Fix by rebuild and redeploy, then re-run the same query as the verification.

Does docker build notice when upstream packages change and re-run apt-get update?

No, and give the rule: a RUN layer is keyed on its command text, so it is reused until an earlier layer misses. Offer the options in order of preference: pin the base image by digest and rebuild when the digest changes (so the rebuild is a reviewed event), bump a cache-busting ARG, or --no-cache for a one-off security rebuild.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Quick recall

Interviewer: 'What is a container, actually, to the kernel?' You say: an ordinary process on the shared kernel, with namespaces changing what it sees and cgroups limiting what it uses. Follow-up: you exec in, id says uid 0, and there is no user-namespace remapping. What is that process to the host kernel?

In short

It is root on the host kernel too; namespaces hide things from the process, they do not change who it is.

Accepted

root · root on the host · root on the node

Why

A container is a process on a shared kernel: namespaces change what it can see (its own pid, mount, and network view), cgroups limit what it can use, but a uid is a kernel uid, so root inside the container is root to the host kernel unless user namespaces remap it. That is why a container escape, a mounted host path, or a misconfigured runtime hands over root on the node, and why reviewers look for a non-root USER (numeric, so runAsNonRoot can verify it without resolving names) in every Dockerfile that ships.

The common mistake

Saying the container 'is isolated, so root inside is harmless'. Namespaces isolate the view, not the identity; a mounted host path or a kernel bug hands root on the node to that process.

Read the docs

2 Pick the strongest answer

A Dockerfile does COPY . . and then RUN npm ci. Every one-line source change makes the build re-run npm ci from scratch, adding minutes. What do you change, and why does it work?

  1. Copy only package.json and package-lock.json first, run npm ci, then COPY . . for the rest — the install layer's inputs now change only when the manifest does. The cache key for a COPY includes the checksums of the copied files, and a cache miss invalidates every later layer. Isolating the manifest keeps the expensive install layer's inputs stable.
  2. Build with --no-cache so stale layers stop interfering with the install. --no-cache guarantees the slow path every time; the problem is that the cache is being invalidated, not that it is stale.
  3. Merge the COPY and RUN into one instruction so they are cached as a single unit. Fewer layers do not change what invalidates them; a combined step still has the whole source tree as input and still misses on every edit.
  4. Move RUN npm ci above COPY . . — the cache is keyed on instruction order, not on file contents. The cache does hash file contents for COPY and ADD, which is exactly why the source change busts it; and with no manifest copied yet, the install has nothing to read.
In short

Copy the dependency manifest first, install, then copy the source, so the install layer is reused until the manifest changes.

Why

BuildKit reuses a layer only when the instruction is identical and its inputs are unchanged — for COPY and ADD the inputs are the checksums of the files copied — and once one layer misses, every layer after it is rebuilt. COPY . . puts the entire source tree, which changes on every commit, in front of the dependency install, so the install can never hit. Copying the manifest first gives the install layer inputs that change only when dependencies change; the source copy moves to the end where a miss is cheap. This ordering principle — volatile inputs last — is the single most useful Dockerfile idea and interviewers use it to check you understand the cache as a mechanism rather than a magic speed-up.

The common mistake

Answering in terms of layer count or --no-cache. Fewer layers do not change what invalidates them, and --no-cache guarantees the slow path; the fix is moving the volatile input later.

Read the docs

3 Pick the strongest answer

A Deployment points at registry.example.com/api:stable with imagePullPolicy: IfNotPresent. The team pushes a fix to the stable tag and runs kubectl rollout restart. Pods on three of eight nodes still serve the old code. What happened, and what is the durable fix?

  1. A tag is a mutable pointer, and IfNotPresent trusts whatever image a node already has cached under that tag; nodes that had pulled stable before kept the old image. Deploy immutable tags or a digest (@sha256:...) so a new build is a spec change and every node pulls exactly that content. Identity in the spec, not pull policy, is the fix: an immutable reference makes the rollout deterministic and the rollback history meaningful.
  2. Layers are content-addressed, so two images with the same tag must have the same content; the stale nodes have corrupted caches. Layers and manifests are content-addressed by digest; tags are names that can point anywhere and be moved at will.
  3. The registry caches the old manifest for the tag; wait for its TTL to expire and restart again. Registries serve the current manifest for a tag immediately; the stale copy is on the node, where the kubelet chose not to pull.
  4. Set imagePullPolicy: Always; tracking a moving tag is the right way to ship a release. Always makes nodes re-pull, but the Deployment spec is unchanged, so there is no revision to roll back to and no record of which build ran where. It hides the symptom and keeps the disease.
In short

IfNotPresent reused the old image cached under the stable tag; deploy by digest or an immutable tag so every node pulls the new build.

Why

An image has two kinds of names. repo@sha256:... is a content address — the digest of the manifest — and can never refer to different bytes. repo:tag is a label that a push can move. IfNotPresent asks the kubelet to pull only when no image with that name is present, so a node that pulled stable last week is satisfied by last week's bytes. The fix is not Always (which papers over it at the cost of a registry dependency on every start) but immutable references: a per-build tag or the digest, so a new build changes the pod template, which is what a Deployment rollout, rollout undo, and a scanner report all key on.

Read the docs

4 Read the output

The .npmrc held a private registry token. The author points at the rm -f /app/.npmrc layer as proof it never shipped. Are they right? Which of these is correct?

$ docker history shop/api:1.8.0
IMAGE          CREATED       CREATED BY                                            SIZE      COMMENT
9c1f2a7d3b44   3 weeks ago   CMD ["node" "server.js"]                              0B        buildkit.dockerfile.v0
<missing>      3 weeks ago   USER node                                             0B        buildkit.dockerfile.v0
<missing>      3 weeks ago   RUN /bin/sh -c rm -f /app/.npmrc # buildkit           0B        buildkit.dockerfile.v0
<missing>      3 weeks ago   COPY . /app # buildkit                                412MB     buildkit.dockerfile.v0
<missing>      3 weeks ago   RUN /bin/sh -c npm ci --omit=dev # buildkit           188MB     buildkit.dockerfile.v0
<missing>      3 weeks ago   COPY .npmrc /app/.npmrc # buildkit                    221B      buildkit.dockerfile.v0
<missing>      3 weeks ago   COPY package.json package-lock.json /app/ # buildkit  6.1kB     buildkit.dockerfile.v0
<missing>      3 weeks ago   WORKDIR /app                                          0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   /bin/sh -c #(nop)  CMD ["node"]                       0B
<missing>      5 weeks ago   /bin/sh -c #(nop)  ENV NODE_VERSION=20.11.1           0B
<missing>      5 weeks ago   /bin/sh -c #(nop) ADD file:8f2a... in /               74.8MB
  1. Containers only see the layers above USER, so the token is unreachable at runtime. A container sees the union of every layer, and anyone who can pull the image gets every layer regardless of what a running process can see.
  2. The 0B size of the rm layer proves the file is no longer in the image. 0B means the layer added no file content. A deletion is metadata (a whiteout entry); the original 221B still sits in the COPY layer below.
  3. The token ships in the image: the 221B COPY layer still contains .npmrc, and the rm layer is 0B because it only records a whiteout. Separately, 412MB for COPY . /app means node_modules or .git from the developer's checkout was copied in — a .dockerignore is missing. Layers are additive; a delete in a later layer hides the file from the merged view but leaves the bytes in the earlier layer, retrievable with docker save or any registry pull.
  4. npm consumed the token during the build, so it was never persisted anywhere. COPY writes the file into a layer no matter what later instructions do with it; only a BuildKit secret mount (or a build stage that is not shipped) keeps it out.
In short

The token still ships: the rm layer only hides the file, and the 221B COPY layer still holds it.

Why

Read docker history bottom-up as a stack of filesystem diffs. A later rm cannot reach into an earlier layer; it adds a whiteout so the merged filesystem hides the path, which is why that layer costs 0B and why the secret is still one docker save away. The right tools are RUN --mount=type=secret,id=npmrc,target=/app/.npmrc npm ci with docker build --secret id=npmrc,src=$HOME/.npmrc, or a multi-stage build where the stage that saw the secret is not the stage you ship. The 412MB COPY is the second finding: a whole checkout including node_modules went into the image before npm ci replaced it, so the image carries two copies of the dependencies and the build cache misses on every commit.

Read the docs

5 Find what's broken

This Dockerfile builds and the service runs. You are reviewing it: which three lines do you block on, and what does each become?

FROM node:latest
WORKDIR /app
ENV NPM_TOKEN=example-not-a-real-token
COPY . .
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc \
 && npm ci --omit=dev \
 && rm .npmrc
EXPOSE 8080
USER node
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/healthz || exit 1
CMD ["node", "server.js"]
In short

The three faults are node:latest (line 1), the token in ENV (line 3), and COPY . . before the install (line 4).

What's broken
  • Line 1: node:latest is a mutable tag: the base image — and therefore the Node major version — can change between two builds of the same commit.
  • Line 3: The registry token is baked into the image configuration as an ENV; it is visible with docker inspect and present in every running container's environment.
  • Line 4: The whole source tree is copied before the dependency install, so every source edit invalidates the npm ci layer.
Why

Three separate mechanisms, one file. A tag is a pointer (line 1), so latest makes the build non-reproducible even with an identical Dockerfile. ENV values become part of the image config, not a layer (line 3), so the usual "delete it in a later RUN" reasoning does not even apply — the token is in docker inspect output for the life of the image. Copy order (line 4) is the cache-invalidation pattern. The distractors are correct as written: rm .npmrc on line 7 runs inside the same RUN as the write, so that file never lands in a layer (the ENV is still the leak); USER node on line 9 is what a reviewer wants to see; the HEALTHCHECK on line 10 is fine for Docker and Compose and merely ignored by Kubernetes.

Read the docs

6 Answer out loud

What does a multi-stage build actually do, and when would you move a service to a distroless base image? Tell me what you give up. Two to five sentences.

In short

A strong answer says only the final stage ships, and distroless removes the shell, so debugging needs an ephemeral debug container.

What a strong answer does
  • mechanism: Only the final stage's layers ship; COPY --from carries the compiled artifact; toolchain, source, and build-time secrets never enter the runtime image; distroless removes shell and package manager so attack surface and scanner findings drop.
  • tradeoffs: No shell or package manager (debug via ephemeral debug containers or a separate debug tag), must remember CA certificates, tzdata, and libc compatibility or static linking, weaker fit for interpreted runtimes with native extensions; says when not to bother.
  • communication: Mechanism, then a decision rule for when to adopt, then the costs, with an example of where it does not pay.
Why

Interviewers want the mechanism — that an image is the layers of its final stage only, so COPY --from is a filter as much as a copy — followed by a decision rule rather than a slogan. Distroless is a good trade when the runtime is self-contained and the CVE list is base-image noise; it is a poor trade when you would spend the saved attack surface on debugging friction, and the honest answer names the debugging story (ephemeral debug containers) rather than pretending there is none.

Read the docs

7 Scenario: what do you do next?

Security forwards a critical CVE in a system library shipped by the debian:12 image family. Your platform runs about 60 services across three Kubernetes clusters; all images live in one private registry with an integrated scanner, and most Dockerfiles start FROM internal/base-debian:12, a tag your platform team rebuilds weekly.

Step 1. Within the hour the CISO wants to know how many running services are affected. What do you do first?

  1. Collect the image digests actually running (each pod's status.containerStatuses[].imageID across the three clusters) and join them to the scanner's per-digest findings and to the list of base-image digests that carry the CVE. Tags cannot answer the question — base-debian:12 has pointed at many digests. Running digests joined to scan results is the only exact inventory.
  2. Restart every Deployment so nodes pull fresh images. A restart with the same digest changes nothing, and with a mutable tag you would not know what you got. Inventory before action.
  3. grep every repository for FROM internal/base-debian:12. That tells you what would be affected at the next build, not what is running now; services built before and after the vulnerable base look identical in source.
  4. Email all service owners and ask whether they use Debian. Slow and unreliable when the answer is already in the cluster and the registry.

Step 2. The join says 41 of 60 services run a digest built from a vulnerable base; 9 are internet-facing. The platform team has already pushed a patched base-debian:12. What is the fix path?

  1. Restart the pods so the containers pick up the patched base layer. A container's layers are fixed when the image is built; a new base tag does nothing until each image is rebuilt on top of it.
  2. Rebuild the 41 images from the patched base (by digest), promote them through the normal pipeline, roll out the 9 internet-facing services first and the rest after, then re-run the digest join to confirm zero remaining. Images are immutable, so the fix is rebuild and redeploy — staged by exposure and verified with the same query that produced the inventory.
  3. Switch every Dockerfile to FROM debian:12 directly so upstream fixes arrive automatically. Fixes still arrive only when someone rebuilds, and you lose the hardened internal base and the single place to patch.
  4. Exec into the running containers and upgrade the library with the package manager. Lost at the next restart, invisible to the scanner and to anyone reading the Dockerfile, and forty-one services of hand patching is not repeatable.

Step 3. Everything is patched by end of day. What do you propose so the next base-image CVE is a non-event?

  1. Repeat this inventory by hand once a quarter. Too slow for a critical CVE and manual steps decay; the goal is a response that runs without you.
  2. Ask teams to use FROM debian:latest so they always receive the newest fixes. latest is mutable and irreproducible, still only helps when someone rebuilds, and makes the inventory problem worse.
  3. Move every service to scratch images. Not viable for most runtimes and it creates no process; minimal bases where they fit are a tactic, not the mechanism.
  4. Pin base images by digest with a bot that opens rebuild PRs when the base changes, a scheduled rebuild-and-rescan of every service, and an admission policy that refuses images with critical findings or without a valid signature. Turns today's manual join and rebuild into a standing mechanism, and moves enforcement to deploy time where it cannot be skipped.
In short

List the running image digests, join them to the scanner results, rebuild the affected images from the patched base, then pin bases by digest.

Why

The scenario tests whether you treat images as immutable, digest-addressed artifacts. Inventory by digest, not tag; fix by rebuild and redeploy, not by patching running containers; verify with the same digest query; then convert the response into pinned bases, automated rebuilds, and an admission gate. Candidates who reach for "restart the pods" have not internalized that a container's filesystem is fixed at build time.

8 Pick the strongest answer

You add HEALTHCHECK --interval=10s CMD curl -f http://localhost:8080/healthz || exit 1 to a service's Dockerfile and ship it to Kubernetes. During a dependency outage the process stays up but returns 500s; pods keep receiving traffic and nothing restarts. Why did the HEALTHCHECK not help you?

  1. Docker marked the container unhealthy, but Kubernetes only acts on containers that exit. Kubernetes does not consult any runtime health status; there is no 'unhealthy' state for it to read or ignore.
  2. HEALTHCHECK only runs when the container is started with docker run --health-cmd. Under Docker the Dockerfile HEALTHCHECK is honoured by default and the CLI flag overrides it; the issue is that Kubernetes does not run it at all.
  3. curl is missing from the image, so the check fails open and the container stays marked healthy. A failing HEALTHCHECK command marks a Docker container unhealthy, never healthy — and on Kubernetes it is not executed in the first place.
  4. Kubernetes ignores the image's HEALTHCHECK entirely; the kubelet runs only the liveness, readiness, and startup probes declared in the pod spec, so traffic gating and restarts have to be defined there. HEALTHCHECK is a Docker Engine and Compose feature. Kubernetes has its own probe model and never executes the image's check.
In short

Kubernetes never runs the image's HEALTHCHECK; health must be declared as probes in the pod spec.

Why

HEALTHCHECK is metadata that the Docker daemon (and Compose, for depends_on: condition: service_healthy) acts on by running the command on an interval and flipping the container's health status. Kubernetes never runs it: the kubelet's contract is the pod spec, where a readiness probe removes a pod from Service endpoints while it fails and a liveness probe restarts the container. A team that ports a Compose stack and keeps its HEALTHCHECKs has no health signal at all until it adds probes. The interview follow-up is usually which probe this failure needed — readiness, so the 500s stop reaching users, not liveness, since restarting does not fix a downstream outage.

Read the docs

Next lesson AWS core: IAM, VPC, compute and load balancing, S3, RDS, EKS specifics
Drill · Containers and Docker
0:00

Loading…