▚ The Software Engineer's Field Manual
Chapter E9 · Primer + senior drill

Docker & Containers — Primer + 150-Question Drill

"A container is not a small virtual machine. It is an ordinary Linux process wearing a disguise — and every hard Docker question is really a question about the disguise."

150 questions · answers collapsed For: ~9-year engineers prepping the senior round Heavy on: namespaces · layers · PID 1 · JVM limits · Compose · hardening

01 · Why this primer existsYou Ship Containers Daily — Nobody Ever Showed You the Process Behind the Whale

A container is not a small virtual machine. It is one ordinary Linux process, fenced off by two kernel features and given a filesystem assembled from stacked layers.

You have typed docker build and docker run more times than you can count. Your services go to production as images, your local database is a container, your CI pipeline is a Dockerfile.

And yet the senior interview keeps finding the same gap: what is actually running when a container runs? Why did the container die with exit code 137 while the Java heap was fine? Why does the app reach Postgres on your laptop but not in the compose stack? Why did the image grow to 1.4 GB, and which line of the Dockerfile did it? These are not trivia.

They test whether you understand the machine that wraps every service you own — and the machine is smaller than it looks.

A container is a normal Linux process with three things done to it: it is given a private view of the system (namespaces), a budget for CPU and memory (cgroups), and a stacked read-only filesystem with a thin writable sheet on top (overlay).

Once you can see those three things, most Docker mysteries stop being mysteries.

Interviews probe this in three ways. The first is the mechanism question: "walk me through what happens when I type docker run nginx", or "what is the difference between a container and a VM, really".

The second is the on-call scenario: a container is killed, an image is bloated, a build passes locally and fails in CI, logs vanish after a restart.

The third is design: "design the image build pipeline for forty services", "design secrets handling for containers", "design a base-image strategy with a 48-hour patching promise". A senior candidate answers all three from the same small set of ideas, and says the trade-offs out loud.

The page has two halves.

The primer (sections 02–06) teaches the internals in plain words: what a container is and how the Docker Engine is layered (CLI, daemon, containerd, runc); images, layers, the build cache and multi-stage Dockerfiles for a Spring Boot service and a Python service; running containers — PID 1, signals, resource limits and how the JVM sees them; networking, volumes and Docker Compose for a local stack; and production concerns — registries, scanning, signing, hardening and the honest list of cases where Docker is the wrong tool.

The drill (sections 07–10) is 150 questions: knowledge questions that ask "why", production scenarios that must be answered in diagnosis order, and design questions that must be answered with requirements, a design, and the things you would refuse to do.

Every answer is collapsed behind a Reveal answer control. Say your answer out loud first — full sentences, as if the interviewer were across the table — then reveal and compare. The habit of committing before checking is the whole trick.

Read the primer first; the drill assumes it.

Where a topic belongs to a neighbouring appendix, this page links there instead of repeating it: orchestration of many containers lives in E10 · Kubernetes, the application side of layered jars and actuator health endpoints lives in E4 · Spring Boot, JVM memory and garbage-collector tuning lives in E3 · Java Interview Drill, and the database questions that containers make worse (durability on overlay filesystems, connection pools per replica) live in E8 · Database Primer.

Version facts are stated as of August 2026: Docker Engine 29.x is current (28.x is still supported), Docker Compose is the v2 plugin (docker compose, version 2.4x), and BuildKit is the default builder.

02 · The primerWhat a Container Actually Is — Namespaces, cgroups, and a Stack of Folders

Three kernel mechanisms make a container: namespaces decide what a process can see, cgroups decide how much it can use, and an overlay filesystem gives it a root directory made of read-only layers plus one writable one.

Start with a number that should feel wrong if you think containers are small virtual machines. A virtual machine takes 20 to 60 seconds to boot, because it boots a whole operating system.

A container starts in 50 to 300 milliseconds, and a container that runs echo hi is finished before you can blink. The reason is that no operating system boots at all.

The container's process is started by the host's kernel — the same kernel that runs your shell — exactly like any other process, and then that process is shown a lie: that it is alone on the machine.

Here is the bridge to what you already know. When you run a Java application, the operating system gives it a process ID, an environment, a working directory, open file descriptors, and access to the whole filesystem and network.

A container is that same process with a narrower view. It still has a process ID, but its process ID number 1 is your application, not the machine's init.

It still has a filesystem, but the root of that filesystem is a folder the Docker daemon prepared. It still has a network interface, but the interface is a virtual cable plugged into a virtual switch. Nothing is emulated.

The kernel is simply keeping a separate set of bookkeeping tables for this process and its children.

The three Linux features, in plain words

Namespaces are the lie about visibility. A namespace is a kernel feature that gives a group of processes their own private copy of one particular system resource. There are eight kinds, and you only need to know what each one hides.

The pid namespace gives the container its own process-ID numbering, so the first process inside becomes PID 1 and it cannot see host processes at all.

The mnt (mount) namespace gives it a private list of mounted filesystems, which is how / inside the container can be a different folder from / on the host.

The net namespace gives it private network interfaces, IP addresses, routing table and port numbers — this is why two containers can both listen on port 8080 without conflict. The uts namespace gives it a private hostname. The ipc namespace separates shared memory segments.

The user namespace lets user ID 0 inside map to an unprivileged user ID outside; Docker does not use it by default, which is the root of many security questions later.

The cgroup namespace hides the host's cgroup tree, and the time namespace lets a container have a different clock offset.

You can try one without Docker: unshare --pid --fork --mount-proc bash puts you in a new pid namespace, and ps inside shows only bash as PID 1.

Control groups, or cgroups, are the budget. A cgroup is a kernel accounting object that tracks and limits how much CPU, memory, disk bandwidth and process count a group of processes may use.

On every modern distribution the kernel exposes them as a directory tree under /sys/fs/cgroup (this is cgroup v2, the default since roughly 2021; Docker Engine 29 requires it).

When you write docker run --memory=512m, the daemon creates a directory for the container and writes 536870912 into the file memory.max inside it. When you write --cpus=1.5, it writes 150000 100000 into cpu.max, meaning "150 milliseconds of CPU time per 100-millisecond period". The kernel enforces both.

If the container's memory use crosses memory.max and the kernel cannot reclaim page cache to make room, the OOM killer — the kernel routine that ends a process when memory runs out — kills a process in that cgroup, usually your application.

The container then exits with code 137, which is 128 plus signal 9. Remember that number; it is the single most-asked Docker scenario.

The overlay filesystem is the stack of folders. An image is a list of read-only layers, each one a folder of files.

When a container starts, the daemon asks the kernel's overlay2 driver to stack those folders on top of each other (the lowerdir) and to put one empty writable folder on top (the upperdir), with a scratch folder the driver needs for its own bookkeeping (the workdir).

The merged view is what the container sees as /. Reading a file finds the topmost copy. Writing to a file that lives in a lower layer triggers copy-up: the whole file is copied into the upper folder first, then modified there.

Deleting a file from a lower layer does not remove it; the driver writes a special marker called a whiteout in the upper folder that hides it. Two consequences follow that interviews love.

First, everything written inside a container without a volume goes into the upper folder, which is deleted with the container — that is why "logs disappear after restart".

Second, a Dockerfile line that deletes a large file added by an earlier line does not shrink the image, because the earlier layer still contains the file; only the whiteout is added.

One shared host Linux kernel — no guest OS, nothing emulated java -jar app.jar an ordinary process (PID 1 inside) Namespaces private pid, net, mnt, uts, ipc, user views = what it can SEE cgroup v2 memory.max = 512 MiB cpu.max = 150000 100000 = what it can USE overlay2 filesystem read-only image layers below, one writable layer on top = what its / LOOKS like placed in charged to chrooted into enforced by
Fig. E9.1 — A container is one ordinary process (the accented box) with three kernel features applied: namespaces decide what it can see, a cgroup decides what it can use, and an overlay mount decides what its root filesystem looks like. All three are enforced by the single host kernel, which is why there is no boot and no hypervisor.

Containers versus virtual machines — the honest comparison

A virtual machine runs a complete guest kernel on top of a hypervisor, a piece of software that pretends to be hardware. The guest kernel cannot see the host at all, which is a strong security boundary: to escape, an attacker must find a bug in the hypervisor, and those are rare. A container shares the host kernel. Its boundary is the kernel's own namespace and permission code, which is a far larger surface — every system call the container makes is handled by the host kernel. This is why "containers are isolated" is only half true. They are isolated enough for your own services, and not isolated enough for untrusted third-party code without extra help. The extra help exists: gVisor (Google's user-space kernel that intercepts system calls before they reach the real kernel) and Kata Containers (a lightweight VM per container) both plug into Docker as alternative runtimes. The trade is startup time and some performance for a VM-grade boundary. The default runtime, runc, gives you speed and density; you choose the others when you do not trust what you run.

What docker run actually does, step by step

The Docker Engine is not one program. It is a chain of four, and knowing the chain lets you answer "what happens when the daemon restarts" and "why does Kubernetes not need Docker at all".

The Docker CLI is a thin client: docker run turns into HTTP requests to the daemon over the Unix socket /var/run/docker.sock.

The daemon, dockerd, owns images, networks, volumes and the API. It does not start containers itself; it hands the job to containerd, a smaller daemon whose only job is managing container lifecycles and image layers on disk.

containerd in turn starts a tiny per-container process called a shim, and the shim invokes runc, the reference implementation of the OCI runtime specification.

runc reads a JSON description of the container, creates the namespaces and cgroup, mounts the overlay root, and calls execve to replace itself with your application. Then runc exits.

The shim stays behind holding the container's standard output and exit status, which is why you can restart dockerd without killing running containers. Kubernetes talks to containerd directly and skips dockerd entirely — that is the whole story behind "Kubernetes removed Docker", covered in E10.

Two specifications make all of this interchangeable. The OCI image specification (Open Container Initiative, the standards body Docker and others founded in 2015) says what an image is: a manifest listing layer blobs and a config blob, each addressed by its SHA-256 digest.

The OCI runtime specification says what a runtime must accept: a root filesystem folder plus a config.json describing namespaces, cgroup limits, mounts, environment and the command.

Because both are open, an image built by Docker runs under Podman, containerd, or CRI-O without change, and a runtime can be swapped from runc to gVisor with one daemon flag.

docker CLI thin client dockerd API, images, nets containerd lifecycle, layers shim holds stdio, exit code runc OCI runtime REST over unix socket gRPC spawns execs java -jar app.jar in namespaces + cgroup + overlay execve, runc exits parent, survives dockerd restart Kubernetes' kubelet talks to containerd directly here
Fig. E9.2 — The chain behind docker run. The CLI only talks HTTP to dockerd; dockerd delegates to containerd; containerd spawns a shim that runs runc; runc sets up the isolation and replaces itself with your application. The shim is the container's real parent, which is why containers survive a daemon restart and why Kubernetes can skip dockerd altogether.

Watch it happen

Step-by-step: what inspect-container.sh does, in plain English
  1. Start an nginx container in the background with a 256 MiB memory limit and one and a half CPUs, named web so later commands can refer to it.
  2. Ask the daemon for the container's process ID as seen from the host, using Go template syntax to pull one field out of docker inspect.
  3. List the namespaces that process lives in by reading the symbolic links under /proc/PID/ns; each link shows an inode number, and two processes in the same namespace show the same number.
  4. Read the cgroup files the daemon wrote, to prove the limits are just numbers in files.
  5. Ask the daemon where the overlay folders live, to show the image layers and the writable layer are ordinary directories.
  6. Remove the container so the writable layer is discarded.
inspect-container.shruns offline
#!/usr/bin/env bash
# Requires: Docker Engine on Linux (cgroup v2), run as a user in the docker group.
set -euo pipefail

docker run -d --name web --memory=256m --cpus=1.5 nginx:1.27-alpine

PID=$(docker inspect --format '{{.State.Pid}}' web)
echo "host PID of the container's PID 1: $PID"

echo "--- namespaces of that process (inode numbers)"
sudo ls -l /proc/"$PID"/ns

echo "--- cgroup limits the daemon wrote"
CG=$(cat /proc/"$PID"/cgroup | cut -d: -f3)
cat /sys/fs/cgroup"$CG"/memory.max
cat /sys/fs/cgroup"$CG"/cpu.max

echo "--- overlay folders that make up / inside the container"
docker inspect --format '{{json .GraphDriver.Data}}' web | tr ',' '\n'

docker rm -f web >/dev/null
terminal output
host PID of the container's PID 1: 41872
--- namespaces of that process (inode numbers)
lrwxrwxrwx 1 root root 0 Aug 28 10:02 cgroup -> 'cgroup:[4026532871]'
lrwxrwxrwx 1 root root 0 Aug 28 10:02 ipc -> 'ipc:[4026532869]'
lrwxrwxrwx 1 root root 0 Aug 28 10:02 mnt -> 'mnt:[4026532867]'
lrwxrwxrwx 1 root root 0 Aug 28 10:02 net -> 'net:[4026532872]'
lrwxrwxrwx 1 root root 0 Aug 28 10:02 pid -> 'pid:[4026532870]'
lrwxrwxrwx 1 root root 0 Aug 28 10:02 user -> 'user:[4026531837]'
lrwxrwxrwx 1 root root 0 Aug 28 10:02 uts -> 'uts:[4026532868]'
--- cgroup limits the daemon wrote
268435456
150000 100000
--- overlay folders that make up / inside the container
{"LowerDir":"/var/lib/docker/overlay2/l/QX7A...:/var/lib/docker/overlay2/l/K2MB...:/var/lib/docker/overlay2/l/P9RT..."
"MergedDir":"/var/lib/docker/overlay2/6f1c.../merged"
"UpperDir":"/var/lib/docker/overlay2/6f1c.../diff"
"WorkDir":"/var/lib/docker/overlay2/6f1c.../work"}

Read the output slowly, because it is the whole chapter in twelve lines. The first line says that the process which believes it is PID 1 is, from the host's point of view, PID 41872 — one process among thousands. The namespace listing shows seven links; six of them (cgroup, ipc, mnt, net, pid, uts) have inode numbers in the 4026532xxx range that differ from your shell's, meaning the kernel created fresh namespaces for this container. The user line is the exception: its number, 4026531837, is the host's own initial user namespace. That single line is why root inside a default Docker container is root on the host, which the security chapter returns to. The two cgroup files hold exactly the numbers we asked for: 268435456 bytes is 256 MiB, and 150000 100000 means 150 milliseconds of CPU per 100-millisecond period, which is 1.5 CPUs. Finally the overlay data shows three read-only lower folders (the three layers of the nginx alpine image), a merged folder that is the container's root, a diff folder that is the writable layer, and the driver's work folder. Nothing here is a disk image or a virtual machine. It is folders, numbers in files, and a process.

🧠 Brain power

Before reading on: a colleague runs docker exec web free -m inside the 256 MiB container and it prints the host's full 64 GB. Is the memory limit broken? Where does free get its numbers, and which of the three kernel features is responsible for the confusion?

Reveal the answer

The limit is fine. free reads /proc/meminfo, and the proc filesystem is not memory-namespaced — there is no "memory namespace" at all, only a cgroup budget. So every container sees the host's meminfo.

The container will still be killed when its cgroup crosses 256 MiB; it simply cannot see that fact through free. The truthful number is in /sys/fs/cgroup/memory.max inside the container.

This is exactly why older Java versions sized their heap from the host and were OOM-killed: they asked /proc instead of the cgroup. Modern JVMs (JDK 10 and later) read the cgroup file.

Tools such as lxcfs can fake a namespaced meminfo, but the real fix is to make your runtime cgroup-aware.

There are no dumb questions

If the kernel is shared, how can I run an Ubuntu container on a Fedora host?
Because "Ubuntu" in an image means Ubuntu's user-space files — its shell, its package manager, its C library and its directory layout — not Ubuntu's kernel. Every process asks the kernel for services through system calls, and Linux system calls are stable across distributions. So an Ubuntu filesystem runs perfectly on a Fedora kernel. What you cannot do is run a Windows container on a Linux kernel, or a Linux container natively on macOS; Docker Desktop on a Mac quietly runs a small Linux virtual machine and puts all your containers inside it, which is why bind mounts on a Mac are slower than on Linux.
Why is it called a "container" if nothing is contained in a box?
The word is a shipping metaphor: standard-shaped boxes that any crane can lift, regardless of what is inside. The technical reality is closer to "a process with a restricted view". Holding both pictures at once is useful. The shipping picture explains why images are portable. The process picture explains every failure mode: it dies like a process, it is scheduled like a process, and it escapes like a process.
Does the container have its own IP address if it is just a process?
Yes, through the network namespace. The daemon creates a pair of virtual Ethernet devices — think of a patch cable with two ends — puts one end inside the container's namespace as eth0 and plugs the other end into a virtual bridge on the host called docker0. The container gets an address such as 172.17.0.2 on that bridge. Traffic to the outside world is translated by the host's firewall rules. The networking chapter covers what this means for reaching other containers and for publishing ports.
What is the difference between Docker and containerd and Podman?
Docker is the whole product: CLI, daemon, build tooling, Compose and Desktop. containerd is the lifecycle daemon that Docker uses underneath and that Kubernetes uses directly. Podman is a Red Hat project that offers a Docker-compatible CLI without a long-running daemon and runs rootless by default; it uses the same OCI images and, since it speaks the same specifications, most Dockerfiles and commands work unchanged. In a senior interview, being able to place the three on the Fig. E9.2 chain is enough.

Quick reference — What a container is

namespaces
What a process can see. Eight of them: pid, mnt, net, uts, ipc, user, cgroup, time.
cgroups
How much it can use — CPU, memory, IO. cgroup v2 is the current interface.
The OOM killer
Exceed the memory limit and the kernel kills the process. Exit code 137. This is not the JVM's OutOfMemoryError, and the two need different fixes.
overlay filesystem
lowerdir (the read-only image layers) plus upperdir (your writable layer). A write copies the file up first — copy-on-write.
The one-sentence answer
A container is a normal process with a restricted view and a resource budget. There is no virtual machine anywhere.

03 · The primerImages, Layers & Dockerfiles — Why the Build Takes 12 Minutes and the Image Weighs 1.4 GB

An image is a stack of read-only layers, and every instruction in your Dockerfile makes one. Build speed and image size are both decided by the order you write those instructions in.

Here is the scenario that appears in some form in almost every senior Docker interview. A team's Spring Boot service ships as a 1.4 GB image. Every commit triggers a 12-minute build.

Every deploy pulls 1.4 GB to each of 30 nodes, so a rollout of one service moves 42 GB across the network and takes eight minutes before the first pod is even scheduled. The Dockerfile is nine lines long and looks reasonable.

The fix, once you understand layers, takes an afternoon and gives a 180 MB image that builds in 90 seconds when only application code changed. This chapter is that afternoon.

Bridge from what you know: an image is to a container what a class is to an object, and more precisely what a compiled jar is to a running JVM. It is immutable, it can be copied, and many containers can run from one image.

The one idea that jars do not prepare you for is that an image is not one file.

It is an ordered list of layers, and each layer is a compressed tar archive holding only the files that one Dockerfile instruction added, changed or deleted, identified by the SHA-256 digest of its contents.

Two images that share the same first five layers share those five archives on disk and in the registry. Pulling the second image transfers only the layers you do not already have.

What each Dockerfile instruction does to the layers

A Dockerfile is a script read top to bottom by the builder. Some instructions create a new filesystem layer; the rest only change the image's metadata (the config blob). FROM picks the starting stack of layers, usually a published base image.

RUN executes a command inside a temporary container built from the layers so far and snapshots whatever files changed as a new layer — so RUN apt-get install followed on a separate line by RUN rm -rf /var/lib/apt/lists produces a large layer and then a whiteout, and the image does not shrink; the cleanup must happen in the same RUN.

COPY copies files from your build context (the folder you pass to docker build) into a new layer; ADD does the same but also unpacks local tar files and fetches URLs, which is why the convention is to use COPY unless you specifically need those tricks.

WORKDIR, ENV, EXPOSE, USER, LABEL, ENTRYPOINT and CMD only write metadata; they cost nothing at runtime. ARG declares a build-time variable that is not present in the running container — though its value is recorded in the image history, so it must never carry a secret.

The build cache is the mechanism behind fast rebuilds, and it is simpler than people fear. The builder walks the instructions in order. For each one it asks: have I already built this exact instruction on top of this exact parent layer?

For RUN the key is the command text. For COPY the key is a checksum of the copied files' contents and permissions. If the answer is yes, the cached layer is reused and the builder moves on.

The moment one instruction misses, every instruction after it is rebuilt, because each layer depends on its parent. That single rule explains the 12-minute build: a COPY . . near the top of the file changes on every commit, so the expensive dependency download below it runs every time.

The fix is ordering. Put the things that change rarely first (base image, system packages, dependency manifests, dependency download) and the things that change often last (your source code). A Maven pom.xml changes once a week; src/ changes every commit.

Copy the pom.xml alone, download dependencies, and only then copy the source.

Bad order: COPY . . before dependencies FROM eclipse-temurin:21-jdk · cached COPY . . · source changed → MISS RUN mvn dependency:go-offline · rebuilt RUN mvn package · rebuilt 3 layers rebuilt, ~11 min, 900 MB of deps Good order: manifests first, source last FROM eclipse-temurin:21-jdk · cached COPY pom.xml . · unchanged → HIT RUN mvn dependency:go-offline · HIT COPY src ./src · changed → MISS RUN mvn package · rebuilt, 60 s build order build order only 2 layers rebuilt after a code change
Fig. E9.3 — The cache rule: layers are reused from the bottom up until the first instruction whose input changed, and everything above that is rebuilt. Moving COPY . . below the dependency download turns an 11-minute rebuild into a 60-second one, because the 900 MB dependency layer is now a cache hit on every code-only commit.

The bad Dockerfile, and why it is bad

Step-by-step: what Dockerfile.bad does, in plain English
  1. Start from the full JDK image with Maven on top: 700 MB before a single line of your code, and a compiler ships to production.
  2. Copy the entire project folder — including .git, target/, and IDE files — into one layer that changes on every commit.
  3. Run the full Maven build, which downloads every dependency again because the previous layer missed.
  4. Run the built jar as root, in shell form, so the JVM is a child of /bin/sh and never receives the stop signal directly.
Dockerfile.badruns offline
FROM maven:3.9-eclipse-temurin-21
WORKDIR /app
COPY . .
RUN mvn package -DskipTests
CMD java -jar target/orders-service-1.0.0.jar

Count the sins. The base image carries a full JDK, Maven and its cache, so the runtime image is 700 MB before your jar arrives and it ships a compiler that an attacker could use. COPY . . sits above the build, so the cache is useless on every commit and Maven re-downloads dependencies. There is no .dockerignore, so the build context includes .git and the last target/ folder, and the context upload alone can take a minute. The process runs as root. The CMD is in shell form — a bare string — which the builder wraps as /bin/sh -c "java -jar …", so PID 1 is a shell, and when Docker sends the stop signal the shell receives it and the JVM does not. That last one is a production incident waiting for a deploy, and the next chapter explains it fully.

The good Dockerfile: multi-stage, layered jar, non-root

A multi-stage build lets one Dockerfile contain several FROM sections. Each is a separate stage with its own layers; a later stage can copy files out of an earlier one with COPY --from. Only the final stage becomes the image.

So you build with a fat JDK-plus-Maven image and run with a slim JRE image, and the build tools never reach production. Spring Boot adds one more trick.

A fat jar changes completely whenever any byte in it changes, so a one-line code change invalidates a 60 MB layer. The Spring Boot layered jar feature (E4 covers the application side) can extract the jar into four folders: dependencies, spring-boot-loader, snapshot-dependencies and application.

Copy those in that order and a code change rebuilds only the last, few-hundred-kilobyte layer, and a deploy pulls only that layer to each node.

Step-by-step: what Dockerfile (Spring Boot) does, in plain English
  1. The syntax line asks BuildKit to use the current Dockerfile front-end so cache mounts and heredocs are available.
  2. Stage build starts from a pinned Maven-plus-JDK image and copies only the Maven wrapper and pom.xml first.
  3. The dependency download runs with a cache mount — a folder BuildKit keeps between builds outside any layer — so Maven's local repository persists without bloating the image.
  4. Only now is the source copied and the jar packaged; a code change invalidates from here down and nothing above.
  5. Stage extract uses Spring Boot's tools mode to split the jar into its four layer folders.
  6. The final stage starts from a pinned JRE-only image, creates an unprivileged user, and copies the four folders in slowest-changing to fastest-changing order.
  7. Health and port metadata are declared; the JVM is told to size itself from the cgroup limit; the entrypoint is in exec form so the JVM is PID 1 and receives signals.
Dockerfileruns offline
# syntax=docker/dockerfile:1

# ---------- stage 1: build the jar (never ships) ----------
FROM maven:3.9.9-eclipse-temurin-21 AS build
WORKDIR /workspace
# Manifests first: this layer only changes when dependencies change.
COPY pom.xml mvnw ./
COPY .mvn .mvn
RUN --mount=type=cache,target=/root/.m2 \
    ./mvnw -q -B dependency:go-offline
# Source last: a code change invalidates only from here down.
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 \
    ./mvnw -q -B package -DskipTests

# ---------- stage 2: split the fat jar into layers ----------
FROM eclipse-temurin:21-jre AS extract
WORKDIR /extract
COPY --from=build /workspace/target/orders-service-1.0.0.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination out

# ---------- stage 3: the runtime image ----------
FROM eclipse-temurin:21-jre-jammy
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
# Slowest-changing first, so deploys pull only the top layer on a code change.
COPY --from=extract --chown=app:app /extract/out/dependencies/ ./
COPY --from=extract --chown=app:app /extract/out/spring-boot-loader/ ./
COPY --from=extract --chown=app:app /extract/out/snapshot-dependencies/ ./
COPY --from=extract --chown=app:app /extract/out/application/ ./
USER app
EXPOSE 8080
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom"
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD ["java", "-cp", "/app", "org.springframework.boot.loader.launch.JarLauncher", "--spring.main.web-application-type=none", "--healthcheck"] 
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

One honest note on the HEALTHCHECK line: a JRE image has no curl, so the example shows the shape of an exec-form check, but in practice teams either add a tiny static curl binary in the runtime stage or leave HEALTHCHECK out and let the orchestrator probe /actuator/health over HTTP, which is what E10 recommends. What matters for the interview is the reasoning: the build tools stay in stage one, the runtime stage is a JRE, the process is not root, the JVM reads its memory budget from the cgroup, and the entrypoint is a JSON array so java is PID 1.

Step-by-step: what .dockerignore does, in plain English
  1. Every pattern listed is excluded from the build context sent to the daemon, so the upload is small and a change in these files cannot invalidate a COPY cache entry.
  2. The version-control folder and build output are the two biggest offenders and the two most common sources of "works locally, fails in CI" cache surprises.
  3. Local secret files are excluded so they can never be copied into a layer by accident.
.dockerignoreruns offline
.git
.gitignore
target/
build/
*.log
.idea/
*.iml
.env
*.pem
Dockerfile*
compose*.yaml

A Python service, built the same way

Step-by-step: what Dockerfile.python does, in plain English
  1. Stage deps starts from a slim Debian-based Python image and installs uv, the fast Python package installer, by copying its static binary from the official image.
  2. The lock file and project file are copied first and dependencies are installed into a virtual environment at /venv; a cache mount keeps downloaded wheels between builds.
  3. The runtime stage starts from the same slim base without any build tools, copies only the finished virtual environment, then the application source.
  4. Two environment variables make Python print logs immediately and skip writing bytecode files into a read-only layer.
  5. The service runs as an unprivileged user with the exec-form entrypoint so the server process is PID 1.
Dockerfile.pythonruns offline
# syntax=docker/dockerfile:1

FROM python:3.12-slim-bookworm AS deps
COPY --from=ghcr.io/astral-sh/uv:0.8 /uv /usr/local/bin/uv
WORKDIR /build
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv venv /venv && \
    UV_PROJECT_ENVIRONMENT=/venv uv sync --frozen --no-dev --no-install-project

FROM python:3.12-slim-bookworm
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PATH="/venv/bin:$PATH"
RUN useradd --system --uid 10001 --no-create-home app
WORKDIR /app
COPY --from=deps /venv /venv
COPY --chown=app:app src ./src
USER app
EXPOSE 8000
ENTRYPOINT ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]

Build both and compare sizes with docker image ls. The bad Spring Boot image is around 720 MB; the good one is around 280 MB with the full Temurin JRE, and drops under 200 MB if you build a trimmed runtime with jlink in the extract stage. The Python image lands near 150 MB. The more important number is what changes per commit: in the good images a code change produces a new top layer of a few hundred kilobytes, and that is all the registry stores and all the nodes pull.

Choosing a base image

The base image is a security and a compatibility decision as much as a size one, and this is where the alpine trap lives.

Alpine images are tiny (about 8 MB) because they use musl, a minimal C library, instead of glibc, the C library every mainstream Linux program is built against.

The JVM runs on musl only through special builds, DNS resolution behaves differently, and many Python packages ship precompiled wheels (binary packages) only for glibc, so on Alpine pip falls back to compiling them from source, which is slow and needs a compiler in the image.

Distroless images (Google's gcr.io/distroless) contain a glibc runtime and nothing else — no shell, no package manager — which shrinks the attack surface dramatically but means docker exec … sh does not work and debugging needs a separate tool container.

Chainguard and its Wolfi base take the same idea with daily rebuilds and low CVE counts. The Debian -slim and Ubuntu-based Temurin images are the safe default: glibc, a shell for debugging, and a familiar package manager.

Choosing a base image for a JVM or Python service (as of Aug 2026)
Choose…When…Watch out for
eclipse-temurin:21-jre-jammy or -nobleDefault for Spring Boot; you want glibc, a shell, and vendor-supported JRE buildsAbout 250 MB; rebuild monthly to pick up OS patches
python:3.12-slim-bookwormDefault for Python services; wheels install without compilingStill Debian: scan and rebuild regularly
Distroless (gcr.io/distroless/java21-debian12)Hardened production; no shell and no package manager wanted on purposeNo docker exec sh; debug with an ephemeral tool container; cannot run entrypoint shell scripts
Chainguard / Wolfi imagesYou need near-zero CVE counts for compliance and are willing to pay or track their tagsDifferent package tooling (apk on Wolfi); free tags are latest-only
AlpineStatic Go binaries, simple shell tooling, sidecarsmusl: JVM needs musl builds, DNS quirks, Python wheels recompile; not worth the 200 MB for a JVM app
jlink custom runtime on a -slim baseYou need a small JVM image but still want glibc and a shellMust list modules correctly (jdeps); rebuild when the JDK patches

Tags, digests and reproducibility

A tag such as eclipse-temurin:21-jre is a movable label; the publisher re-points it at a new build whenever they patch the OS underneath.

That is convenient and dangerous: the same Dockerfile built on Monday and Friday can produce different images, and latest is the extreme case — a tag that means "whatever was pushed most recently".

A digest is the SHA-256 of the manifest, written eclipse-temurin@sha256:9f3c…, and it can never point at anything else. Production Dockerfiles pin base images by digest and let a bot (Renovate, Dependabot) open pull requests that bump the digest, so patching is deliberate and reviewed.

Your own images get two labels: an immutable tag equal to the git commit SHA, and the digest that docker build --push prints, which is what deploy manifests should reference.

docker buildx build --platform linux/amd64,linux/arm64 produces a manifest list — one tag pointing at one image per CPU architecture — which is how a single tag runs on both x86 nodes and Graviton or Apple silicon.

Finally, BuildKit, the builder that has been Docker's default since Engine 23 and is at version 0.3x as of August 2026, is what makes the good Dockerfile possible. It runs independent stages in parallel, skips stages the final image does not need, supports --mount=type=cache for package caches, --mount=type=secret for build-time credentials that never land in a layer, and exports its cache to a registry (--cache-to type=registry,ref=…) so a fresh CI runner can still hit the cache. Every build in this chapter assumes it.

Quick reference — Images, layers, Dockerfiles

layer
One per Dockerfile instruction, read-only, content-addressed and shared between images.
The build cache rule
A changed instruction invalidates every layer after it. So put what changes rarely (dependency install) before what changes every commit (your source).
multi-stage build
Build in a fat image, copy only the artefact into a slim one. The compiler never ships.
layered jar
Boot's split of a fat jar into dependencies and application classes, so a code change only rebuilds the small layer.
Alpine and musl
Alpine uses musl, not glibc. That breaks pre-built Python wheels and some JVM assumptions. Small is not free.
Distroless
No shell, no package manager. Smaller attack surface, and no docker exec to debug with — that trade is the point.
tag vs digest
A tag can be moved. A digest cannot. Build once, promote by digest is what makes staging and production genuinely the same image.

04 · The primerRunning Containers — PID 1, Signals, Limits, and the JVM That Ignored Them

Your process is PID 1, which means the kernel treats it specially: it must handle signals itself and reap orphaned children, or shutdown hangs and zombies accumulate.

Two incidents, both real in shape. First: a service with --memory=2g runs fine for four hours, then dies with exit code 137 and no stack trace, no Java OutOfMemoryError, nothing in the application log.

Second: every deploy of another service takes exactly 10 seconds longer than it should, and a few in-flight requests fail each time. Both are the same lesson in different clothes: inside a container, your application is PID 1, and PID 1 is a job with rules.

And both are answerable with numbers from the cgroup and a couple of JVM flags.

PID 1 and the stop signal

On a normal Linux system, PID 1 is init (usually systemd), and it has two special duties.

It reaps orphans: when a process exits, its parent must collect the exit status, and if the parent is gone the kernel hands the dead child to PID 1 to collect.

A dead-but-uncollected process is a zombie; it holds a process-table slot and nothing else, but enough of them exhaust the container's pids.max.

PID 1 also has unusual signal handling: the kernel ignores any signal for which PID 1 has not installed a handler, so a bare SIGTERM to a naive PID 1 does nothing.

Inside a container, your application is PID 1, and it usually does neither duty. Now look at what docker stop does: it sends SIGTERM to PID 1, waits 10 seconds (the -t grace period; orchestrators use 30 seconds by default), and then sends SIGKILL.

If the entrypoint was written in shell form, PID 1 is /bin/sh, which does not forward signals to its child, so the JVM never hears the SIGTERM.

The shell sits there for 10 seconds, then everything is killed, mid-request, with connections open and shutdown hooks never run. That is the second incident.

The fixes, in order of preference: write ENTRYPOINT in exec form (a JSON array) so the application itself is PID 1; if you must have a wrapper script, end it with exec java … so the shell replaces itself with the JVM instead of forking it; and run with --init, which inserts tini, a 20-kilobyte init that reaps zombies and forwards signals, as PID 1.

The JVM handles SIGTERM gracefully — Spring Boot runs its shutdown hooks, and with server.shutdown=graceful it stops accepting connections and finishes in-flight requests within spring.lifecycle.timeout-per-shutdown-phase. All of that is wasted if the signal never arrives.

Memory limits and how the JVM sees them

Now the first incident.

A container's memory budget is the cgroup's memory.max, and it counts everything the process group uses: the Java heap, the metaspace where class metadata lives, thread stacks (about 1 MB each by default, so 300 threads is 300 MB), direct byte buffers used by Netty and NIO, the JIT compiler's code cache, and even the page cache for files the container reads.

When the total crosses the limit, the kernel's OOM killer sends SIGKILL — signal 9 — and the container exits with 128 + 9 = 137. The JVM never sees it coming.

There is no OutOfMemoryError, because the heap was not full; the process as a whole was too big.

The JVM's behaviour depends on its version and flags. Since JDK 10 the JVM is container-aware: it reads memory.max and cpu.max from the cgroup instead of the host's totals (-XX:+UseContainerSupport, on by default).

With no explicit heap flag, the default maximum heap is 25 percent of the container's memory, which is safe but wasteful — a 2 GB container gets a 512 MB heap.

The senior setting is -XX:MaxRAMPercentage=75, which gives the heap 75 percent and leaves 25 percent for metaspace, threads, buffers and the code cache. A hard -Xmx works too but must be recomputed every time the limit changes, so it drifts out of sync.

Add -XX:+ExitOnOutOfMemoryError so a genuine heap exhaustion ends the process cleanly for the restart policy instead of leaving a half-dead JVM. The full flags, the reasoning about how much non-heap headroom a Netty or Kafka client needs, and how to read Native Memory Tracking output belong to E3.

cgroup memory.max = 2048 MiB (everything in the container counts) Java heap · MaxRAMPercentage=75 → 1536 MiB OutOfMemoryError happens HERE, visibly, with a stack trace non-heap 512 MiB metaspace · threads direct buffers · code cache kernel OOM killer · SIGKILL · exit 137 no Java stack trace, nothing in app logs Old JVM or -Xmx sized from a 64 GB host: heap thinks it may grow to 16 GiB → crosses 2048 MiB after hours → 137 with no warning grows into the limit Prevention: JDK 17+/21, -XX:MaxRAMPercentage=75, -XX:+ExitOnOutOfMemoryError, cap threads and direct memory, watch container_memory_working_set_bytes.
Fig. E9.4 — A 2 GiB memory limit seen from the JVM's side. With MaxRAMPercentage=75 the heap stops at 1536 MiB and any exhaustion is a visible OutOfMemoryError; the remaining 512 MiB carries metaspace, thread stacks, direct buffers and the code cache. A JVM that sized itself from the host grows straight through the dashed line, and the kernel — not Java — ends it with signal 9.

CPU limits: quota, not cores

--cpus=1.5 does not give the container one and a half cores. It gives it a quota: 150 ms of CPU time in every 100 ms period, spread across however many cores the scheduler likes. When the quota is used up, every thread in the container is paused until the next period — this is throttling, visible as nr_throttled in the cgroup's cpu.stat. A JVM with 16 garbage-collector threads on a 16-core host, running under --cpus=1, burns its 100 ms quota in about 6 ms of wall time when all threads run, then stalls for 94 ms. Startup takes 40 seconds instead of 8 and latency shows strange 100 ms steps. The container-aware JVM helps by setting ActiveProcessorCount from the quota (rounded up), so it creates fewer threads. The remaining senior advice is to prefer requests without hard CPU limits where the orchestrator allows it, or set the limit at 2 or more so parallel garbage collection has room; E10 continues that argument.

Logs, health and restarts

A container has no log files, or should not. The convention is that the application writes to standard output and standard error, and the daemon's logging driver captures the stream.

The default driver, json-file, writes to a file under /var/lib/docker/containers/<id>/ which is what docker logs reads — and which is deleted with the container, so anything written to a file inside the writable layer is gone after docker rm or a recreate.

Two settings matter: rotation (--log-opt max-size=50m --log-opt max-file=5, or the local driver which rotates by default) so a chatty container cannot fill the disk, and a shipper (Fluent Bit, Vector, the cloud agent) reading those files to a central store so logs survive the container.

A HEALTHCHECK lets the daemon mark a container unhealthy and lets Compose wait for dependencies with condition: service_healthy; a restart policy (--restart=unless-stopped or on-failure:5) tells the daemon to bring a dead container back.

Environment variables set with -e are visible to anyone who can run docker inspect, which is why secrets go in files with tight permissions — the production chapter comes back to that.

Step-by-step: what run-and-observe.sh does, in plain English
  1. Run the orders service with a 2 GiB memory limit, 2 CPUs, tini as PID 1, a non-root user id, log rotation and a restart policy — the flags a production-ish docker run should always carry.
  2. Print the JVM's own view of its memory and CPU budget by asking it to dump the ergonomic values, proving it read the cgroup and not the host.
  3. Show the cgroup's live memory usage and throttling counters from inside the container, which is what a monitoring agent reads.
  4. Stop the container and time it; with exec-form entrypoint and graceful shutdown it should return in well under the 30-second grace period.
  5. Read the exit code so the difference between 143 (clean SIGTERM) and 137 (killed) is visible.
run-and-observe.shruns offline
#!/usr/bin/env bash
set -euo pipefail

docker run -d --name orders \
  --memory=2g --memory-swap=2g --cpus=2 --pids-limit=512 \
  --init --user 10001:10001 --read-only --tmpfs /tmp:rw,size=256m \
  --log-driver=local --log-opt max-size=50m --log-opt max-file=5 \
  --restart=unless-stopped \
  -p 127.0.0.1:8080:8080 \
  orders-service:1.0.0

echo "--- what the JVM believes its budget is"
docker exec orders java -XX:+PrintFlagsFinal -version 2>/dev/null \
  | grep -E 'MaxHeapSize|MaxRAMPercentage|ActiveProcessorCount'

echo "--- what the cgroup says right now"
docker exec orders sh -c 'cat /sys/fs/cgroup/memory.current; cat /sys/fs/cgroup/memory.max; grep -E "nr_periods|nr_throttled" /sys/fs/cgroup/cpu.stat'

echo "--- graceful stop, timed"
time docker stop -t 30 orders
docker inspect --format 'exit code: {{.State.ExitCode}}' orders
docker rm orders >/dev/null
terminal output
--- what the JVM believes its budget is
   size_t MaxHeapSize                     = 1610612736    {product} {ergonomic}
   double MaxRAMPercentage                = 75.000000     {product} {command line}
     uint ActiveProcessorCount            = 2             {product} {ergonomic}
--- what the cgroup says right now
412839936
2147483648
nr_periods 1843
nr_throttled 0
--- graceful stop, timed
orders

real    0m2.417s
exit code: 143

Read it line by line. MaxHeapSize is 1,610,612,736 bytes, which is exactly 75 percent of 2 GiB: the JVM read memory.max and applied the percentage, and the {ergonomic} tag confirms it computed the value rather than being handed -Xmx. ActiveProcessorCount is 2, matching --cpus=2, so the garbage collector and common thread pools are sized for two cores, not for the 32-core host. The cgroup's memory.current shows 412,839,936 bytes — about 394 MiB — in use against a limit of 2,147,483,648, which is the number that monitoring should alert on at 85 percent, long before the kernel gets involved. nr_throttled 0 after 1,843 scheduler periods means the CPU quota has never been exhausted; a large non-zero number here is the fingerprint of the 40-second-startup problem. The stop took 2.4 seconds, not 30, and the exit code is 143 — 128 plus 15, the SIGTERM number — meaning the JVM received the signal directly, ran its shutdown hooks and exited on its own. A 137 on that last line, with a fast stop, would mean the signal was swallowed and the daemon had to kill the process.

🧠 Brain power

Before reading on: the team sets -Xmx1900m in a 2 GiB container "to use all the memory" and is proud of it. The service still dies with 137 after six hours under load. Where did the memory go, and why is the fix a smaller heap?

Reveal the answer

The heap is only one tenant of the cgroup.

With 1900 MiB reserved for heap, only 148 MiB is left for everything else: metaspace (typically 80 to 150 MiB for a Spring Boot service), thread stacks (200 threads times 1 MiB), the JIT code cache (up to 240 MiB by default), and direct buffers that Netty allocates off-heap.

Under load those grow, the process crosses 2048 MiB, and the kernel kills it — with no OutOfMemoryError, because the heap never filled. The fix is -XX:MaxRAMPercentage=70 or so, leaving roughly 600 MiB of non-heap room, plus -XX:MaxDirectMemorySize and a capped thread pool.

Use Native Memory Tracking (-XX:NativeMemoryTracking=summary) once to see the real split, then size from evidence.

Quick reference — Running containers

PID 1
No default signal handlers, and it must reap orphans. A process that ignores SIGTERM as PID 1 gets SIGKILLed after the grace period.
shell vs exec form
CMD foo runs under /bin/sh -c, so the shell is PID 1 and your process never sees the signal. CMD ["foo"] makes your process PID 1. Use exec form.
tini
A tiny init that forwards signals and reaps zombies, for when your process cannot do it itself.
container-aware JVM
Since JDK 10 the JVM reads cgroup limits. Size with -XX:MaxRAMPercentage, never a hard -Xmx.
CPU throttling
A CPU limit is enforced by the scheduler in 100 ms periods. Your process is not slow — it is stopped. Look at throttled_time, not at CPU percentage.

05 · The primerNetworking, Storage & Compose — Why the App Cannot Reach the Database

Containers get their own network namespace and, by default, nothing survives their deletion. Networking and storage are both about deliberately punching holes in that isolation.

The most common Docker ticket in any team is some version of "the app cannot reach the database container". The application log says Connection refused: localhost:5432. Postgres is running. docker ps shows both containers up. The developer can connect from their laptop with psql -h localhost.

Everything looks fine and nothing works. The explanation is one sentence once you have the network namespace picture from chapter 02: each container has its own localhost, so localhost:5432 inside the app container is the app container's own loopback interface, where nothing is listening.

The database is at a different address, reachable by its container name on a shared network. This chapter builds that picture, then the storage one, then puts both into a Compose file you can run.

The three network modes you will actually use

Every container is attached to one or more networks, and a network is a virtual switch with its own address range.

The default is bridge: the daemon creates a Linux bridge called docker0 on the host with the range 172.17.0.0/16, gives each container a virtual cable (a veth pair: one end is eth0 inside the container, the other is plugged into the bridge), and hands out addresses.

Containers on the same bridge can reach each other by IP. Two facts about the default bridge trip people up. First, it has no name resolution: you cannot reach another container by its name there.

Second, it is shared by every container that did not ask for a network, so there is no isolation between them.

A user-defined bridge (docker network create backend) fixes both: the daemon runs an embedded DNS server at 127.0.0.11 inside each container, resolving container names and Compose service names to their current addresses, and only containers you attach can talk to each other.

This is why Compose creates a network per project and why you connect to postgres:5432, not an IP.

Host mode (--network host) skips the network namespace entirely: the container uses the host's interfaces and ports directly.

It is the fastest option and the least isolated; you use it for monitoring agents and for latency-critical services where the port translation cost matters, and you cannot run two of anything on the same port.

None gives the container only a loopback interface — a batch job that must never talk to the network. Overlay networks, which stretch a virtual switch across many hosts, belong to Swarm and are replaced by the cluster networking in E10.

Publishing a port is the bit that connects the outside world to the bridge.

-p 8080:80 tells the daemon to write a firewall rule (iptables or nftables destination translation) so traffic arriving at the host's port 8080 on any interface is forwarded to the container's port 80. Three consequences follow.

The container must listen on 0.0.0.0, not 127.0.0.1, or the forwarded packets arrive at an interface nothing is bound to — the second most common "cannot reach" ticket.

A published port is reachable from other machines by default, because 0.0.0.0 is the default bind; write -p 127.0.0.1:8080:80 for local-only.

And on Linux the daemon's rules run before the host's ufw rules, so a published port silently bypasses the host firewall — a security review item, and the reason production hosts publish only through a reverse proxy.

Linux host user-defined bridge "backend" · 172.20.0.0/16 · DNS at 127.0.0.11 container "app" eth0 172.20.0.3 lo 127.0.0.1 (its own!) listens 0.0.0.0:8080 container "postgres" eth0 172.20.0.2 lo 127.0.0.1 (separate) listens 0.0.0.0:5432 veth veth postgres:5432 localhost:5432 = refused client host:8080 DNAT rule: -p 8080:8080
Fig. E9.5 — Two containers on a user-defined bridge. Each has its own loopback, so localhost:5432 from "app" is refused; the working path (accented) resolves the name "postgres" through the embedded DNS to 172.20.0.2. A published port is a firewall translation rule on the host that forwards into the container, which must therefore listen on 0.0.0.0.

Volumes, bind mounts and tmpfs

Chapter 02 showed that everything a container writes goes to the overlay's upper folder and dies with the container. Anything that must outlive the container needs a mount, and there are three kinds. A bind mount (-v /home/me/project:/app or the clearer --mount type=bind,source=…,target=…) exposes a host folder inside the container at a chosen path. It is what you use for source code in development, and its two pitfalls are file ownership (files created inside as uid 0 appear as root-owned on the host, and a non-root container cannot write to a host folder it does not own) and performance on Docker Desktop, where every file operation crosses the VM boundary. A named volume (-v pgdata:/var/lib/postgresql/data) is a folder the daemon manages under /var/lib/docker/volumes/, created on first use, populated from the image's content at that path, and kept until you explicitly docker volume rm it. This is the right home for database data: native filesystem speed, no overlay copy-up on every write, and fsync behaves as the database expects. A tmpfs mount (--tmpfs /tmp) is memory-backed, disappears with the container and never touches disk — ideal for scratch space and secrets in a read-only container. One trap to name in interviews: a VOLUME instruction in a Dockerfile (the official Postgres image has one) creates an anonymous volume on every docker run if you do not supply a named one, and those pile up silently until docker volume prune.

Running a database in a container is fine in development and for tests. In production it is a judgment call that E8's durability chapter informs: the container is a process, the volume is a normal directory, and the durability guarantees are exactly those of the underlying disk — no better, no worse. What the container does not give you is backups, failover, or storage that follows the container to another host; those are orchestration and storage-platform problems, which is why most teams use a managed database in production and containers for everything stateless.

Docker Compose: the whole local stack in one file

Docker Compose is the tool for describing several containers, their networks and volumes in one YAML file and starting them with one command. As of August 2026 it is the v2 plugin — invoked as docker compose with a space, version 2.4x — and the file is named compose.yaml with no version: key (the old docker-compose binary with a hyphen and the version: "3.8" line are the tutorial fossil record). The file below runs the orders service from chapter 03 with Postgres and Redis, waits for the database to be healthy before starting the app, persists the data, and rebuilds or restarts the app when source changes.

Step-by-step: what compose.yaml does, in plain English
  1. The app service is built from the Dockerfile in this folder; the image name is set so docker compose build tags it predictably.
  2. It publishes port 8080 on the loopback interface only and points Spring at the other services by their service names, which the embedded DNS resolves.
  3. The database password is read from an environment file that is not committed, rather than written into the YAML.
  4. depends_on with condition: service_healthy makes Compose wait for the health checks of Postgres and Redis before starting the app, which removes the "app crashed because the database was not ready" race.
  5. Resource limits and a restart policy mirror what production would set, so a memory leak shows up on the laptop.
  6. The develop.watch section tells docker compose watch to rebuild the image when source changes and to sync static resources into the running container without a rebuild.
  7. Postgres runs a pinned major version on a named volume and exposes a health check using its own pg_isready tool; Redis does the same with redis-cli ping.
  8. Both data services are on the backend network only and publish no ports, so nothing on the laptop's network can reach them directly; the named volumes are declared at the bottom so they survive docker compose down.
compose.yamlruns offline
name: orders

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    image: orders-service:dev
    ports:
      - "127.0.0.1:8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/orders
      SPRING_DATASOURCE_USERNAME: orders
      SPRING_DATA_REDIS_HOST: redis
      JAVA_TOOL_OPTIONS: "-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
    env_file:
      - .env            # holds SPRING_DATASOURCE_PASSWORD=...
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    deploy:
      resources:
        limits:
          memory: 1g
          cpus: "2"
    init: true
    restart: unless-stopped
    networks:
      - backend
    develop:
      watch:
        - action: rebuild
          path: ./src/main/java
        - action: sync
          path: ./src/main/resources/static
          target: /app/BOOT-INF/classes/static

  postgres:
    image: postgres:17.5
    environment:
      POSTGRES_DB: orders
      POSTGRES_USER: orders
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U orders -d orders"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s
    deploy:
      resources:
        limits:
          memory: 512m
    restart: unless-stopped
    networks:
      - backend

  redis:
    image: redis:7.4-alpine
    command: ["redis-server", "--maxmemory", "128mb", "--maxmemory-policy", "allkeys-lru"]
    volumes:
      - redisdata:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped
    networks:
      - backend

secrets:
  db_password:
    file: ./secrets/db_password.txt

volumes:
  pgdata:
  redisdata:

networks:
  backend:
terminal session
$ docker compose up --build -d --wait
[+] Building 64.2s (24/24) FINISHED
[+] Running 6/6
 ✔ Network orders_backend       Created
 ✔ Volume "orders_pgdata"       Created
 ✔ Volume "orders_redisdata"    Created
 ✔ Container orders-postgres-1  Healthy
 ✔ Container orders-redis-1     Healthy
 ✔ Container orders-app-1       Started

$ docker compose ps
NAME                IMAGE                 STATUS                   PORTS
orders-app-1        orders-service:dev    Up 41 seconds (healthy)  127.0.0.1:8080->8080/tcp
orders-postgres-1   postgres:17.5         Up 52 seconds (healthy)  5432/tcp
orders-redis-1      redis:7.4-alpine      Up 52 seconds (healthy)  6379/tcp

$ docker compose exec app getent hosts postgres
172.20.0.2      postgres

$ docker compose down
[+] Running 4/4
 ✔ Container orders-app-1       Removed
 ✔ Container orders-postgres-1  Removed
 ✔ Container orders-redis-1     Removed
 ✔ Network orders_backend       Removed
$ docker volume ls --filter name=orders
DRIVER    VOLUME NAME
local     orders_pgdata
local     orders_redisdata

Read the session as a story. up --build -d --wait built the image, created one network and two volumes named after the project, and then — because of the health-gated depends_on — reported Postgres and Redis as Healthy before the app was even Started; without that condition the app would have been started at the same instant as the database and its first connection attempt would have failed. In compose ps, only the app has a host port, and it is bound to 127.0.0.1; the data services show 5432/tcp and 6379/tcp without a host address, meaning they are reachable only inside the backend network. The getent hosts postgres line, run inside the app container, proves the name resolution: the embedded DNS returned 172.20.0.2, which is the database container's address on the bridge. Finally, down removed containers and the network but the volume list still shows both data volumes; the data is safe until someone runs down -v or volume rm, which is precisely the difference between a restart and a wipe.

Boardroom translation

"Containers are a packaging standard, and the return on investment comes from two numbers.

First, environment drift: today a bug that only reproduces in production costs us on average two engineer-days to chase, and roughly a third of those are configuration differences between a laptop, CI and the server.

A Compose file that runs the whole stack identically everywhere removes that category.

Second, deploy speed and node density: a 1.4 GB image pulled to 30 nodes is 42 GB per rollout and eight minutes of waiting; the layered build in this chapter makes a code-only deploy a few-hundred-kilobyte pull and lets us pack three to four times as many services on the same hosts because each one carries a right-sized memory budget instead of a whole VM. The cost is discipline — a base-image patching rota, image scanning in CI, and a hardening baseline — which is about one engineer-week to set up and a few hours a month to run.

Ask the team for two numbers per service: image size and time from commit to a pullable image. If either is not measured, the pipeline is not finished."

Quick reference — Networking and storage

bridge
The default. Each container gets a veth pair into a virtual switch.
user-defined bridge
What you actually want: containers resolve each other by name. The default bridge does not do DNS.
host / none
host skips the network namespace entirely — no isolation, no port mapping. none gives no network at all.
bind mount vs named volume
A bind mount maps a host path in, with host permissions and host paths — good for development. A named volume is managed by Docker and portable — good for data.
tmpfs
In memory, gone on stop. For secrets and scratch space you do not want on disk.

06 · The primerProduction & Security — Registries, Scanning, Signing, Hardening, and When Not to Use Docker

What separates a container that runs from one you can ship: an image identified by digest rather than tag, scanned and signed, running as a non-root user with the capabilities it actually needs.

A number to anchor this chapter: a freshly built Spring Boot image on an unpatched ubuntu:22.04 base from six months ago will show around 150 to 300 known vulnerabilities in a scanner, of which perhaps five are critical, and almost all of them live in the operating-system layer rather than in your code.

That statistic is the reason every serious container platform has three pipeline stages that an interviewer will ask you to design: a registry with a retention policy, a scanner with a gate, and a rebuild schedule for base images.

A fourth — signing and provenance — has become standard in regulated organisations since 2023. The chapter walks them in the order a build travels.

Registries and the pipeline

A registry is an HTTP service that stores images by name, tag and digest, speaking the OCI distribution API: it stores each layer as a blob addressed by its digest, so pushing an image whose first ten layers already exist transfers only the new ones. Docker Hub is the public default and enforces pull rate limits on anonymous and free accounts — the classic "every deploy fails at 09:00 with 429 toomanyrequests" incident — so production nodes pull from a private registry (ECR, Artifact Registry, ACR, GHCR, Harbor) that either mirrors or proxies upstream. A pull-through cache in each region keeps a copy of every image the fleet has ever pulled, so a Hub outage or a rate limit does not stop a node from rebooting.

The pipeline itself follows one rule: build once, promote by digest. CI builds the image on a commit, tags it with the git SHA, pushes it, and records the digest. Every later environment — staging, production — deploys that same digest; nothing is rebuilt per environment.

Rebuilding for production means production runs something that was never tested. Build steps run inside BuildKit with a registry cache (--cache-from type=registry,ref=…:buildcache --cache-to type=registry,ref=…:buildcache,mode=max) so a fresh runner still hits the cache.

Rootless BuildKit or a remote BuildKit daemon replaces the old docker-in-docker pattern, which required a privileged container and was the one place many CI systems handed root on the runner to every pipeline.

git commit sha 9f3c1a buildx build registry cache, multi-arch scan + SBOM trivy, syft · gate on critical sign + attest cosign keyless, provenance registry tag :9f3c1a · digest sha256:… the SAME digest is deployed everywhere — never rebuilt per environment dev image@sha256:… staging image@sha256:… production admission verifies signature promote promote promotion = pointing an environment at an already-tested digest, not building again
Fig. E9.6 — The image supply chain. One build per commit produces one digest; it is scanned and signed once, stored in the registry (accented), and then promoted through environments by reference. Nothing is rebuilt downstream, so what production runs is byte-for-byte what staging tested, and an admission policy can refuse any digest without a valid signature.

Scanning, SBOMs and signing

A scanner such as Trivy (open source, version 0.6x as of Aug 2026), Grype or Docker Scout unpacks the image, lists every OS package and every language dependency it finds (jars, wheels, npm packages), and matches them against vulnerability databases. It produces a list of CVEs with severities. The senior points about scanners are about noise and policy, not about running them. Most findings are in the base image, so rebuilding on a patched base fixes dozens at once. A CVE in a library your code never calls is still a finding; the fix is a documented exception with an expiry date (Trivy's .trivyignore supports exp: dates), never a permanent silence. The CI gate should block on critical and high with a fix available, and report the rest, or teams learn to ignore the whole report.

A software bill of materials (SBOM) is the scanner's inventory saved as a document (SPDX or CycloneDX format), generated at build time by Syft or by docker buildx build --sbom=true and stored beside the image as an attestation — a signed statement attached to the digest.

It answers the question that matters most on the worst day of the year: "a zero-day just dropped in library X; which of our 40 services contain it?" With SBOMs in the registry that is one query; without them it is a rebuild-and-rescan of everything.

Signing with cosign (Sigstore) attaches a cryptographic signature to the digest; keyless mode uses the CI job's short-lived identity token instead of a key file you must guard. Provenance (--provenance=true, the SLSA format) records which repository, commit and builder produced the image.

The payoff is an admission rule in the cluster — "only run images signed by our CI, from our organisation's repositories" — which E10 shows how to enforce.

The hardening baseline

A default Docker container runs as root, in the host's user namespace, with a default set of Linux capabilities (the fine-grained pieces root's power is split into, such as NET_BIND_SERVICE for ports under 1024 or SYS_ADMIN for mounting filesystems), under a default seccomp profile (a filter that blocks about 44 dangerous system calls out of roughly 350), with a writable root filesystem and no process limit.

Each of those defaults has a stricter setting, and the baseline is the list you would put in a policy. Run as a non-root user (USER in the Dockerfile, --user at run time).

Drop every capability and add back only what the process needs (--cap-drop=ALL --cap-add=NET_BIND_SERVICE, or better, listen on 8080 and add nothing). Make the root filesystem read-only with a tmpfs for /tmp. Forbid privilege escalation (--security-opt no-new-privileges). Cap processes (--pids-limit) and memory.

Never mount /var/run/docker.sock into a container that does not need to manage containers, because whoever controls the socket controls the daemon, which runs as root; and never use --privileged, which disables every isolation feature at once.

Finally, consider rootless Docker, where the daemon itself runs as an unprivileged user inside a user namespace: a container escape then lands on an ordinary user account, not root.

It costs a few features (no port under 1024 without sysctl changes, slower networking through slirp4netns or pasta) and is now the recommended mode for developer machines and CI runners.

Step-by-step: what ci-build.sh does, in plain English
  1. Derive the image reference from the registry and the short git SHA, so every build has an immutable tag.
  2. Build for both CPU architectures with BuildKit, pulling and pushing the layer cache from a dedicated registry tag, generating SBOM and provenance attestations, and pushing the result; the digest is written to a metadata file.
  3. Read the digest back from that file: from here on the pipeline refers only to the digest.
  4. Scan the pushed image with Trivy and fail the job only for critical or high severity findings that have a fix available, ignoring unfixed ones.
  5. Sign the digest keylessly with cosign using the CI job's identity; a later admission policy verifies this.
  6. Write the digest to the job's output so the deployment step can promote it without rebuilding.
ci-build.shruns offline
#!/usr/bin/env bash
# Runs in CI with: docker buildx (BuildKit), trivy, cosign. Registry login done earlier.
set -euo pipefail

REGISTRY="registry.example.com/platform"
SHA="$(git rev-parse --short=12 HEAD)"
IMAGE="$REGISTRY/orders-service"

docker buildx build \
  --platform linux/amd64,linux/arm64 \
  --cache-from "type=registry,ref=$IMAGE:buildcache" \
  --cache-to   "type=registry,ref=$IMAGE:buildcache,mode=max" \
  --sbom=true --provenance=true \
  --tag "$IMAGE:$SHA" \
  --metadata-file build-meta.json \
  --push .

DIGEST="$(python3 -c 'import json;print(json.load(open("build-meta.json"))["containerimage.digest"])')"
echo "built $IMAGE@$DIGEST"

trivy image --severity CRITICAL,HIGH --ignore-unfixed --exit-code 1 "$IMAGE@$DIGEST"

COSIGN_YES=true cosign sign "$IMAGE@$DIGEST"

echo "image_digest=$DIGEST" >> "${GITHUB_OUTPUT:-/dev/stdout}"

The script is short because the hard decisions are in the flags. The two --cache lines are what make a cold CI runner build in two minutes instead of twelve; mode=max exports the cache of every stage, not just the final one, so the Maven dependency layer from stage one is reusable. --sbom=true --provenance=true attaches the inventory and the build record to the digest as attestations for free. The scan runs against the digest that was pushed, never against a local tag that might differ, and --ignore-unfixed is the policy choice that keeps the gate credible: a finding nobody can fix yet should be tracked, not block. The signature is over the digest too, so retagging the image later does not break verification — the signature follows the content, not the name.

When Docker is not the answer

A senior answer includes the cases where containers add cost without benefit, and the interviewer will listen for them.

A single static binary — a Go service, a Rust tool — deployed by copying one file and a systemd unit to a VM is simpler than an image, a registry and a runtime, if there is only one of it and no fleet.

Serverless platforms (Lambda, Cloud Run, Azure Functions) accept containers but often run source or zip deployments with less operational surface; use the container form only when you need a custom runtime or system libraries.

Desktop and GUI applications, kernel modules, and workloads that need specific hardware access are awkward in containers. A database in production usually wants a managed service or a VM with a real disk, not a container with a volume.

And a team of three shipping one monolith to one server does not need Compose, a registry and a scanning pipeline on day one; it needs a good deploy script.

The value of containers scales with the number of services, the number of environments, and the number of people who must run the same thing; below a threshold of roughly three services and two environments, the honest answer is "not yet".

Containerise it, or not? (as of Aug 2026)
SituationChoose containers when…Choose something else when…
Backend services in a fleetMore than a handful of services, several environments, or Kubernetes already in useOne service on one VM: a static binary or jar plus a systemd unit
Local development stackThe app needs a database, cache and broker that must match production versionsA pure-library project with no external services: a virtual environment or Maven is enough
DatabasesDevelopment, CI, integration tests, and short-lived environmentsProduction data with real durability and failover needs: managed service or VM with a real disk
Serverless functionsYou need custom system libraries, a specific JDK or a large runtimePlain source or zip deploys are supported and smaller to operate
Untrusted third-party codeYou run it under gVisor or Kata, not plain runcA plain container is not a security boundary you should bet on; use VMs or a sandbox runtime
CI build agentsEphemeral, reproducible agents with a pinned toolchain per jobBuilds that need Docker-in-Docker with --privileged: use rootless BuildKit or a remote builder instead
🧠 Brain power

Before the drill: a colleague argues that because the CI runner already runs in a container, the safest way to build images is to mount /var/run/docker.sock into it "so we reuse the host daemon and avoid docker-in-docker". What does that mount actually grant, and what would you propose instead?

Reveal the answer

The socket is the daemon's API, and the daemon runs as root on the host.

Anyone who can write to the socket can run docker run -v /:/host --privileged and own the machine — so every pipeline that runs on that runner, including a pull request from a fork, has root on the CI host.

It is not a build convenience; it is an unauthenticated root shell.

The alternatives are a rootless BuildKit daemon reachable over a mutually authenticated TCP endpoint (docker buildx create --driver remote), a per-job rootless BuildKit container, or a builder such as buildah that does not need a daemon at all.

All three build the same images without granting root to the job.

07 · DrillContainer Internals & Images — Q1–Q40

Senior Docker rounds rarely ask you to write a Dockerfile.

They ask what a container actually is, what happens in the two hundred milliseconds after you type docker run, and why an image that "should be 200 MB" is 1.4 GB. These forty questions drill the kernel features underneath — namespaces, cgroups, overlay filesystems — then the OCI image format, layer identity, pull mechanics, and the daemon-to-runc chain.

Every answer names the exact command or file you would look at, because "I would check the cgroup" is a junior answer and "I would read /sys/fs/cgroup/memory.max" is a senior one. Say the answer out loud before you reveal it.

Drill · Namespaces, cgroups & what a container really is

These questions test whether you can explain a container as a normal Linux process with a restricted view of the machine — and name the kernel feature responsible for each restriction.

Q1. "What is a container, in kernel terms? Name each Linux namespace and say what a process stops seeing when it is placed in one."

Reveal answer

The real test Whether you say "a process" rather than "a lightweight VM", and whether you can name the seven namespaces without pausing.

Strong answer A container is an ordinary Linux process, or a tree of processes, that the kernel has given a restricted view of the machine and a capped share of its resources. There is no container object in the kernel.

The restricted view comes from namespaces — a kernel feature that gives a process its own private copy of one kind of system resource. There are seven that matter.

The pid namespace gives the process its own process-ID numbering, so the first process inside sees itself as PID 1. The net namespace gives it its own network interfaces, routing table, and port space, which is why two containers can both listen on port 8080.

The mnt namespace gives it its own mount table, so its root directory is the image's filesystem. The uts namespace gives it its own hostname. The ipc namespace isolates shared memory and semaphores.

The user namespace maps user IDs, so root inside can be an unprivileged user outside. The cgroup namespace hides the host's cgroup tree. The resource cap comes from cgroups, a separate feature I would explain next.

You can build a crude container with no Docker at all: unshare --pid --net --mount --fork chroot rootfs /bin/sh creates a process in fresh namespaces with a new root directory.

Land it Docker did not invent isolation — it packaged namespaces, cgroups, and an overlay filesystem behind one command, and every debugging skill follows from knowing which of the three you are looking at.

Likely follow-ups
"You said there are seven namespaces. Is that still the full list, and which one does Docker not use by default?"

As of Aug 2026 the Linux kernel has eight: the seven I named plus the time namespace, added in kernel 5.6, which lets a process see a different monotonic and boot-time clock offset.

Docker does not create a time namespace, and it also does not create a user namespace by default. Every other one — pid, net, mnt, uts, ipc, cgroup — is created for every container.

That default matters: without a user namespace, UID 0 inside the container is UID 0 on the host, protected only by dropped capabilities and seccomp. You turn the user namespace on either with userns-remap in daemon.json or by running rootless.

You can check what a running container actually got with ls -l /proc/<pid>/ns/ on the host and comparing the inode numbers with those of PID 1; a namespace the container shares with the host shows the same inode.

"How would you prove, on a live host, that a given container process is in its own network namespace?"

I would get the host PID with docker inspect --format '{{.State.Pid}}' web, then compare readlink /proc/<pid>/ns/net with readlink /proc/1/ns/net. Each prints something like net:[4026532281]; different numbers mean different namespaces.

Then I would enter it with nsenter -t <pid> -n ip addr and see only lo and one eth0 instead of the host's interfaces.

A third check is ss -lntp inside versus outside: the container's listening port appears inside and, unless published, not in the host's namespace.

If the container was started with --network host, all three checks show the host's values, which is exactly the situation where two containers cannot both bind 8080. The lsns command lists every namespace on the host with its owning PID and is the quickest overview.

"What does a process still share with the host even inside all those namespaces?"

It shares the kernel itself, and therefore everything the kernel does not namespace. The system clock and time zone are shared, which is why date inside a container matches the host.

Kernel parameters under /proc/sys are mostly shared, so a container cannot raise vm.max_map_count for Elasticsearch without the host doing it, and Docker only lets you set namespaced sysctls like net.core.somaxconn with --sysctl.

Loaded kernel modules, the page cache, the scheduler and its run queues, and the set of CPUs are shared. Hardware and device nodes are shared unless hidden. Most importantly, /proc/meminfo and /proc/cpuinfo report host totals, which is the trap behind the JVM heap sizing scenario.

Anything that reads those files, from free to nproc on older builds, sees the whole machine, not the cgroup.

"If namespaces give the view and cgroups give the limit, what gives the filesystem?"

The mount namespace only gives a private mount table; something still has to put a root filesystem in it.

That is the job of the storage driver, overlay2 on every current host, which stacks the image's read-only layers with an empty writable directory using the kernel's OverlayFS and mounts the merged result.

runc then calls pivot_root, not chroot, to make that merged directory the process's root, because pivot_root detaches the old root entirely and closes the classic chroot escape.

After that it mounts /proc, /sys, /dev and a tmpfs for /dev/shm inside the new root, masks sensitive paths such as /proc/kcore, and marks parts of /proc and /sys read-only.

So the honest three-part answer is namespaces for the view, cgroups for the limits, and OverlayFS plus pivot_root for the root filesystem.

Q2. "Walk me through exactly what happens, step by step, when I type docker run -d -p 8080:80 nginx."

Reveal answer

The real test Whether you can separate the image work from the process work, and name the component that does each step.

Strong answer I would describe it as a chain of components, each doing one job.

  1. The docker command-line tool sends an HTTP request to the daemon, dockerd, over the Unix socket at /var/run/docker.sock. The CLI itself does nothing else.
  2. dockerd resolves the name nginx to docker.io/library/nginx:latest and checks whether the image is present locally. If not, it pulls the manifest, then each missing layer blob, from the registry.
  3. dockerd asks containerd — the lower-level container manager it delegates to — to create a container. containerd's snapshotter prepares the filesystem: it stacks the image layers with overlay2 and adds an empty writable layer on top.
  4. dockerd sets up networking: it creates a virtual Ethernet pair, puts one end in a new network namespace, attaches the other to the docker0 bridge, and writes an iptables or nftables rule so host port 8080 forwards to container port 80.
  5. containerd writes an OCI runtime config.json describing the namespaces, cgroup limits, mounts, and capabilities, then starts a containerd-shim process for this container.
  6. The shim invokes runc, which creates the namespaces and cgroup, applies the mounts, drops capabilities, and calls execve on the image's entrypoint. runc then exits, leaving the shim as the parent.
  7. Because of -d, the CLI prints the container ID and returns. The shim keeps the process's standard output and exit status so the daemon can be restarted without killing the container.

Land it The sentence that marks a senior is "runc exits after the process starts" — it means the runtime is a setup tool, not a supervisor, and explains why containers survive daemon restarts.

Likely follow-ups
"Where exactly is the port 8080 to 80 mapping implemented, and how would you inspect it?"

Two pieces cooperate. The daemon starts a small user-space process called docker-proxy that listens on host port 8080 and copies bytes to the container's IP on port 80; it exists mainly so that connections from the host itself to localhost work.

The fast path is a kernel NAT rule: in the nat table's DOCKER chain, a DNAT rule rewrites the destination of packets arriving for port 8080 to 172.17.0.2:80.

I inspect it with iptables -t nat -L DOCKER -n, or on a Docker Engine 28-or-newer host that has switched to nftables, nft list table ip docker. docker port web shows the mapping from Docker's view.

Because the DNAT happens before the host firewall's INPUT chain, a published port bypasses ufw rules, which surprises people; the fix is to bind to a specific address with -p 127.0.0.1:8080:80.

"The pull succeeds but the container exits immediately. Where do you look, in order?"

First docker ps -a for the exit code, because the code narrows the cause before I read a single log line: 127 means the entrypoint was not found, 126 means it was not executable, 1 is an application error, and 137 or 139 mean a signal.

Second, docker logs web, which for a fast-exiting container is usually one line naming a missing file or a bad config value.

Third, docker inspect --format '{{.Config.Entrypoint}} {{.Config.Cmd}}' to see what actually ran, since an override on the command line replaces CMD. Fourth, I run it interactively with a shell override, docker run -it --entrypoint sh nginx, and execute the entrypoint by hand to see the error with a terminal attached.

If the image is distroless there is no shell, so I use docker debug or export the filesystem. A common cause for nginx specifically is a mounted config file with a syntax error, which nginx reports and exits with code 1.

"What is different in that sequence when the daemon uses the containerd image store instead of the classic graph driver?"

With the classic setup dockerd owns the image metadata in /var/lib/docker/image and asks containerd only to run the container. With the containerd image store, enabled by "features": {"containerd-snapshotter": true} in daemon.json and the default for fresh Docker Desktop installs since 2024, containerd owns the images too.

The pull is then done by containerd's own transfer service and the layers land in its snapshotter under /var/lib/containerd.

Three visible differences: the daemon can store a full multi-platform index locally, so docker build --platform a,b --load works without a push; lazy-pulling snapshotters such as stargz or Nydus become usable, so a container can start before all layers arrive; and docker image ls shows one row per platform variant.

The cost is a migration, since existing images in the old store are not visible after the switch and must be re-pulled.

"You said runc exits after starting the process. What keeps the container's stdout from being lost when dockerd restarts?"

The shim does. When containerd creates a container it starts containerd-shim-runc-v2, a small process that becomes the parent of the container's PID 1 and holds the read ends of its stdout and stderr pipes plus the pseudo-terminal if -t was used.

dockerd does not hold those file descriptors directly; it subscribes to the shim through containerd. So when dockerd is restarted, the pipes are still open in the shim, the process keeps running, and the shim buffers output until a consumer reconnects.

This only works if "live-restore": true is set in daemon.json; without it, dockerd stops every container on shutdown.

Live restore also has limits: it survives a daemon restart but not a containerd restart if the shim is killed, and the daemon cannot be upgraded across a major version this way. You verify it with docker info | grep -i 'live restore'.

Q3 · Scenario. "You start a Java service with docker run --memory=512m. Inside the container, free -m reports 64 GB total, and the JVM sizes its heap to 16 GB and gets OOM-killed within a minute. What is going on and how do you fix it?"

Reveal answer

The real test Whether you know that /proc is not namespaced, and that cgroup limits and what a process sees are two different things.

Strong answer I would diagnose in this order:

  1. Confirm the limit is really applied. Inside the container, cat /sys/fs/cgroup/memory.max should print 536870912. On the host, docker inspect --format '{{.HostConfig.Memory}}' shows the same number. If it prints max, the flag never landed.
  2. Confirm the kill reason: docker inspect --format '{{.State.OOMKilled}}' prints true, and dmesg on the host shows "Memory cgroup out of memory".
  3. The cause is that free reads /proc/meminfo, and the proc filesystem is not namespaced. It reports the host's 64 GB regardless of cgroup limits. Old JVMs, and any tool that reads /proc/meminfo or calls sysconf, size themselves to the host, not the cgroup.
  4. Ranked causes: the JVM is older than 8u191 or 10 and does not read cgroups at all; or it is modern but someone set -Xmx explicitly to a host-sized value; or the JVM is modern but runs on a cgroup v2 host with a JDK before 15, which only understood cgroup v1 paths.
  5. Fix: run a JDK 17 or newer, which reads memory.max directly and applies -XX:MaxRAMPercentage, defaulting to 25 percent. Set -XX:MaxRAMPercentage=75 so a 512 MB limit gives roughly a 384 MB heap. Verify with java -XX:+PrintFlagsFinal -version | grep MaxHeapSize inside the container.
  6. Prevention: for non-JVM tools that still read /proc, mount lxcfs, a user-space filesystem that rewrites /proc/meminfo and /proc/cpuinfo to reflect cgroup limits. Add a startup check that logs the cgroup limit next to the configured heap.

Land it A cgroup limit is a fence the kernel enforces, not a fact the process is told — any runtime that guesses its size from /proc will guess the host, and you must make it read the fence.

Likely follow-ups
"You upgraded to JDK 21 and it still sized the heap to 16 GB. What next?"

I would stop trusting assumptions and ask the JVM what it saw.

java -Xlog:os+container=trace -version inside the container prints every cgroup file the JVM tried to read and the value it got; if it prints "Unable to open cgroup memory limit file" or reports the limit as unlimited, the limit is not visible to it.

The usual reasons are that the container was started with --cgroupns=host or a cgroup v1 host with an unusual mount, that /sys/fs/cgroup is not mounted at all in a very stripped image, or that someone set -XX:-UseContainerSupport or an explicit -Xmx in JAVA_TOOL_OPTIONS that overrides the percentage.

I would check docker inspect --format '{{.Config.Env}}' and cat /proc/1/environ | tr '\0' '\n' for hidden options. If the JVM sees the limit but the heap is still wrong, -XX:+PrintFlagsFinal | grep -E 'MaxHeapSize|MaxRAMPercentage' shows which flag won.

"Why 75 percent and not 90? What is in the other quarter?"

The heap is only one tenant of the container's memory, and the OOM killer counts all of them.

Outside the heap the JVM allocates metaspace for class metadata, typically 50 to 150 MB for a Spring application; a thread stack of 1 MB per thread, so 200 threads is 200 MB; the JIT code cache up to 240 MB; direct byte buffers used by Netty and NIO; garbage collector bookkeeping, which for G1 is roughly 5 to 10 percent of heap; and the page cache for files the process reads, which the cgroup also charges.

At 512 MB total, 75 percent leaves 128 MB for all of that, which is tight but workable for a small service; at 4 GB, 75 percent leaves a comfortable gigabyte.

The right number therefore depends on thread count and native usage, and I would measure it with -XX:NativeMemoryTracking=summary and jcmd 1 VM.native_memory before choosing anything above 75.

"Does the same problem apply to CPU, and how does the JVM decide how many garbage-collector threads to start?"

Yes, and it is subtler because CPU limits are a quota, not a count.

The JVM computes availableProcessors from the cgroup: with cpu.max set to a quota, it divides quota by period and rounds up, so --cpus=1.5 yields 2; with only --cpuset-cpus it counts the allowed cores; with only shares it ignores them since JDK 19 and uses the host count.

That number sizes the common fork-join pool, the number of G1 parallel GC threads, and Tomcat's default thread pool through libraries that call Runtime.availableProcessors().

A JVM that believes it has 64 CPUs on a --cpus=1 container starts dozens of GC threads that then throttle each other against a 100-millisecond quota.

I check it with jshell or java -XshowSettings:system -version, which prints the detected container CPU and memory values, and override with -XX:ActiveProcessorCount=2 when the quota is fractional.

"How would you catch this class of bug before production rather than after the first OOM kill?"

I would make the JVM print its own view at startup and assert on it in a container test.

The service logs Runtime.maxMemory(), availableProcessors(), and the raw contents of /sys/fs/cgroup/memory.max as its first line; an on-call engineer then sees the mismatch without SSH. In CI, a Testcontainers test starts the image with --memory=512m and reads that log line, failing if the reported max heap exceeds 80 percent of the limit or is below 50 percent.

I would also add -XX:+ExitOnOutOfMemoryError so a genuine heap exhaustion fails fast rather than thrashing, and a Prometheus alert on container_memory_working_set_bytes above 85 percent of the limit.

Finally the base-image policy pins a JDK line new enough to read cgroup v2, which as of Aug 2026 means anything from 17 onward, and forbids -Xmx in Dockerfiles in favour of the percentage flag.

Q4. "Explain cgroups v2. What do the cpu, memory, and pids controllers actually do when a container hits its limit?"

Reveal answer

Strong answer A control group, or cgroup, is a kernel feature that groups processes and meters or limits the resources the whole group can consume.

Version 2, which has been the default on every mainstream distribution since around 2022 and is what Docker Engine 29 expects, exposes one unified tree under /sys/fs/cgroup, with each container a directory like /sys/fs/cgroup/system.slice/docker-<id>.scope. Each controller is a file or two in that directory.

The memory controller has memory.max, a hard ceiling in bytes; when the group's usage reaches it, the kernel first reclaims page cache, and if it still cannot free enough, the OOM killer terminates a process in the group, usually the largest.

memory.high is a softer line that throttles allocation rather than killing.

The cpu controller has cpu.max, written as a quota and a period, for example 150000 100000 for --cpus=1.5: the group may run 150 milliseconds of CPU time per 100 millisecond window, and once it uses that, every thread is paused until the next window.

That pause is throttling, visible in cpu.stat as nr_throttled, and it is why a service under a tight CPU limit shows latency spikes rather than slow CPU. The pids controller has pids.max; at the limit, fork fails with "resource temporarily unavailable", which is the defence against fork bombs. --pids-limit=256 sets it.

Land it Memory limits kill and CPU limits throttle — the first shows up as restarts, the second as p99 latency, and knowing which file to read tells you which one you are looking at.

Likely follow-ups
"What was actually wrong with cgroups v1 that justified a rewrite?"

Version 1 had one hierarchy per controller, so a process could be in one cpu group and a completely different memory group, and tools disagreed about which tree was authoritative. It allowed processes in interior nodes of the tree, which made accounting ambiguous.

The memory controller did not charge page cache and kernel memory consistently, so a container could hit its limit from cache it never explicitly allocated, and swap accounting was a separate opt-in. Threads of one process could be split across groups.

Version 2 fixes all of that with a single unified tree, a rule that only leaf groups contain processes, a memory controller that charges every page including cache and kernel memory to one group, and controllers enabled per subtree through cgroup.subtree_control.

It also added pressure stall information, the memory.pressure and cpu.pressure files, which tell you how long tasks waited for a resource — the best early-warning metric a container has.

"How do you read these files for a specific container from the host, and what tool are you actually running?"

On a systemd host with the default cgroup driver, each container is a scope unit at /sys/fs/cgroup/system.slice/docker-<full-id>.scope/, and I can cat memory.current memory.max cpu.stat pids.current there directly. With the cgroupfs driver instead, the path is /sys/fs/cgroup/docker/<id>/.

docker stats is reading exactly these files once a second and computing percentages, so its numbers are cgroup numbers, not process numbers. systemd-cgtop gives a live top-style view per unit.

Two gotchas: memory.current includes page cache, so a container reading a big file looks heavier than its resident set, and the right number for "how close to a kill" is memory.current minus the inactive_file line in memory.stat, which is what Kubernetes calls working set.

Inside the container, the same files appear at /sys/fs/cgroup/ because the cgroup namespace rebases the view.

"What does memory.high do that memory.max does not, and when would you set it?"

memory.max is a cliff: the kernel reclaims, and if reclaim fails it kills. memory.high is a slope: once usage crosses it, allocating processes in the group are put into direct reclaim and slowed down proportionally, but nothing is killed.

The effect is that a leaking process gets slower rather than dying, which buys time for an alert to fire and a human to look.

Docker exposes it only indirectly through --memory-reservation, which on v2 maps to memory.low rather than high; Kubernetes started setting memory.high under the MemoryQoS feature gate.

I would set it in a platform where restarts are more expensive than slowness, for example a stateful service with long warm-up, and pair it with a pressure alert on memory.pressure.

I would not set it for latency-sensitive request handlers, because throttled allocation shows up as tail latency that is very hard to attribute.

"A container has cpu.max of 100000 100000 and shows 40 percent CPU in the dashboard, yet nr_throttled climbs. How is that possible?"

Because the quota is enforced per 100-millisecond period, and average utilisation hides bursts.

A JVM with 16 threads that all wake up together on a request can consume 100 milliseconds of CPU time in 6 milliseconds of wall time, hit the quota, and sleep for the remaining 94 milliseconds of the period.

Over a minute that looks like 40 percent average while every request pays a pause. I would confirm it with cpu.stat: nr_periods, nr_throttled, and throttled_usec; a throttled fraction above 10 percent means the quota is biting.

Fixes in order: reduce parallelism to match the quota with -XX:ActiveProcessorCount and bounded pools; raise the limit or remove it and rely on requests plus cpu.weight for fairness; or use cpu.max.burst, available since kernel 5.14, which lets unused quota from previous periods be spent on a burst. Kubernetes only exposes the first two.

Q5. "Containers versus virtual machines: what is actually shared, what is the real security boundary, and when is a container not enough?"

Reveal answer

The real test Whether you say "shared kernel" as a security statement, not just a performance one.

Strong answer A virtual machine runs its own kernel on top of a hypervisor — software that presents fake hardware to a guest operating system. Every VM boots an operating system, which costs seconds and hundreds of megabytes of memory. A container shares the host's kernel.

Every system call a containerized process makes goes straight into the same kernel that runs every other container and the host.

That sharing is why containers start in milliseconds and pack densely, and it is also the security story: the boundary between two containers is the correctness of the Linux kernel's namespace and cgroup code, plus whatever attack surface the roughly 350 system calls expose.

A kernel bug reachable from an unprivileged system call is a container escape. Docker narrows that surface with a default seccomp profile — a filter that blocks about 40 dangerous system calls — and by dropping most capabilities, but it cannot remove the shared kernel.

A VM's boundary is the hypervisor, which exposes a far smaller interface, so escapes are rarer and much harder. When the code inside is untrusted — customer-submitted functions, CI jobs from public pull requests, multi-tenant platforms — a plain container is not enough.

The middle options are gVisor, which puts a user-space kernel written in Go between the container and the real kernel, and Kata Containers, which runs each container inside a tiny lightweight VM while keeping the OCI interface.

Both cost some performance; both give a boundary you can defend to an auditor.

Land it Trusted code from your own team belongs in runc; code from people you would not give a shell to belongs behind a second kernel, and that decision should be explicit, not accidental.

Likely follow-ups
"Give me a concrete container escape and say what would have stopped it."

The classic is CVE-2019-5736 in runc: a container process could overwrite the host's runc binary through /proc/self/exe while runc was attaching to it, so the next docker exec by an administrator ran attacker code as host root.

It required the container to run as UID 0 and needed an administrator to exec in.

Rootless mode or a user namespace would have limited the damage to an unprivileged user; a read-only, memfd-sealed runc binary, which is the fix that shipped, closes it; running as a non-root user in the image would have blocked the write.

The broader pattern of the 2024 "Leaky Vessels" bugs was similar: race conditions in runc and BuildKit around file descriptors and mounts during setup.

The lessons I draw are that the kernel is not the only escape surface — the runtime's own setup code is — and that a second boundary such as gVisor or a microVM is what turns any single such bug from an escape into an inconvenience.

"What does the default seccomp profile actually block, and when have you had to loosen it?"

Docker's default profile is an allowlist of roughly 300 of the kernel's 400-plus system calls, blocking the ones that touch kernel state a container should never touch: mount, reboot, kexec_load, init_module, ptrace on older kernels, keyctl, unshare and clone with namespace flags, bpf, and the like.

I have loosened it in three situations. Running strace or a Java flight recorder attach inside a container needs ptrace, so I add --cap-add=SYS_PTRACE, which the profile keys on.

Rootless Podman-in-a-container or Docker-in-Docker needs unshare and mount, which I refuse in production and permit only in isolated CI runners. And some older glibc builds hit a blocked clone3 on new kernels, fixed by upgrading Docker rather than the profile.

To see what a workload needs, I run it once with --security-opt seccomp=unconfined under strace -f -c and build a custom profile from the syscall list.

"Why does the industry still run most workloads on plain containers if the boundary is that thin?"

Because the threat model for first-party code is not escape; it is blast radius and resource fairness, and containers deliver those cheaply.

If my own team wrote the code, an attacker who is already executing inside the container has already compromised my service, and the incremental damage of reaching the host is real but secondary compared with the data the service itself can reach.

Density is also money: a microVM per container costs 30 MB of memory and loses shared page cache, which on a 500-node fleet is a noticeable bill. So the sensible policy is a trust gradient.

First-party code runs on runc with non-root users, capability drops, a read-only root filesystem, and the default seccomp profile. Third-party or customer-adjacent code, such as plugins or CI from forks, runs behind gVisor. Genuinely hostile multi-tenant code runs in microVMs.

Most organisations only have the first category and are right to use plain containers for it.

"How does gVisor actually intercept system calls, and what is its performance cost made of?"

gVisor's Sentry is a Go program that implements the Linux system call interface itself.

The container's process runs under a platform that traps every syscall to the Sentry: the ptrace platform, slow but universal, or the KVM platform, which runs the Sentry as a tiny guest so traps are hardware assisted, or the newer systrap platform based on seccomp notifications.

The Sentry then services the call from its own kernel implementation — its own network stack, its own file system layer over a restricted Gofer process — and touches the host kernel through only about 50 syscalls.

The cost is therefore two things: the trap itself, a few microseconds per syscall instead of a few hundred nanoseconds, and the user-space reimplementation, which is slower than the kernel for networking and file I/O. CPU-bound code that makes few syscalls runs at near-native speed; a database or a network proxy can lose 30 to 50 percent. That is why it is a per-workload choice.

Q6. "Inside a container your app reports as PID 1, but on the host it has a different PID, and kill -TERM 1 from the host does nothing to it. Explain the two separate mechanisms at work and the right way to signal a container."

Reveal answer

The real test Whether you separate "PID numbers are per namespace" from "PID 1 has special signal rules" — they are two different facts and both are in play.

Strong answer Two independent mechanisms combine here. The first is the pid namespace: it gives each container its own process-ID numbering, so the app is PID 1 inside its namespace and something like PID 48213 in the host's.

docker inspect --format '{{.State.Pid}}' <container> prints the host number, and cat /proc/48213/status | grep NSpid prints both, host first then namespaced. So kill -TERM 1 on the host targets the host's own init process, not the app, which is why nothing happened.

The second mechanism is a special kernel rule for PID 1 inside a namespace: the kernel does not deliver default signal actions to PID 1, so an application that never installed a SIGTERM handler simply ignores TERM. That is why docker stop waits 10 seconds and then sends SIGKILL, and why zombie child processes accumulate under an app that never reaps them.

The correct ways to signal a container are docker kill --signal=TERM <container>, or docker stop -t 30 for an orderly shutdown, or, from host tooling, kill -TERM 48213 using the PID from inspect.

To make TERM actually work, run the app under a tiny init that forwards signals and reaps zombies — docker run --init injects tini, or you set ENTRYPOINT ["tini","--","java",...].

For a JVM, its shutdown hook handles TERM, but only when the JVM is PID 1 directly and not behind a /bin/sh that the shell form of CMD inserts and that swallows the signal.

Land it PID numbers are per namespace and PID 1 is exempt from default signals — those two facts together explain almost every "my container will not stop cleanly" ticket.

Likely follow-ups
"You said PID 1 ignores signals it has no handler for. Does that apply to SIGKILL too?"

No, and the distinction matters. The kernel rule is that a signal whose disposition is the default action is not delivered to the init process of a PID namespace.

SIGKILL and SIGSTOP have no user-installable handler, so they are handled specially: from inside the namespace they are also ignored for PID 1, but from a parent namespace, such as the host, they are always delivered.

That is precisely why docker stop can fall back to SIGKILL after the grace period and it always works, while a SIGTERM to a handler-less PID 1 does nothing.

It also means kill -9 1 from inside a container does nothing, but kill -9 <host-pid> from the host ends the container.

When PID 1 exits for any reason the kernel sends SIGKILL to every other process in the namespace, which is why an exec'd debugging shell dies the instant the application exits.

"How would you check, without reading the source, whether the application installed a SIGTERM handler?"

Read /proc/<pid>/status for the process, either from the host with the host PID or inside the container with PID 1.

The lines SigCgt, SigIgn, and SigBlk are hexadecimal bitmasks of caught, ignored, and blocked signals; bit 15 corresponds to SIGTERM, so a SigCgt mask with the value 4000 in the low bits means a handler is installed.

A JVM shows SIGTERM, SIGINT, and SIGHUP caught because it installs shutdown hooks; a /bin/sh running a child typically shows none, which is the shell-form bug. The one-liner I use is grep -E 'SigCgt|SigIgn' /proc/1/status.

To test behaviour rather than flags, I send docker kill --signal=TERM and watch docker events for the exit and its code: 143 means the process exited on the signal; a 137 ten seconds later means it did not.

"What changes if I run the container with --pid=host?"

Then there is no separate PID namespace: the process sees and is seen with the host's numbering, it is not PID 1, and the special PID 1 signal rules no longer apply to it.

kill -TERM <pid> from the host reaches it directly and default actions work. That sounds convenient but it removes isolation: the container can see every host process in ps, can signal any of them it has permission for, and with CAP_SYS_PTRACE can attach to them.

The legitimate uses are monitoring agents and debugging sidecars that must observe host processes.

--pid=container:web is the safer variant: the new container joins another container's PID namespace, which is how kubectl debug --target and docker debug let a tools container see the application's processes without host exposure.

Inside a shared PID namespace, whichever process was first is PID 1 and still carries the reaping duty.

"Kubernetes sends SIGTERM to the container. Does it go through Docker's stop path at all?"

Not through dockerd, since Kubernetes has talked directly to containerd through the CRI since 1.24. The kubelet calls the CRI StopContainer with a timeout equal to terminationGracePeriodSeconds, default 30 rather than Docker's 10.

containerd asks the shim to send the container's configured stop signal to PID 1 — SIGTERM unless the image sets STOPSIGNAL — waits, then sends SIGKILL. So the same PID 1 rules apply: a shell-form entrypoint still swallows the signal and the pod takes the full grace period.

Two Kubernetes-specific additions: a preStop hook runs before the signal is sent, and its duration counts against the same grace period; and the pod is removed from Service endpoints at roughly the same moment, which is why a short preStop sleep of a few seconds is used to let load balancers catch up before the listener closes. STOPSIGNAL SIGINT in the Dockerfile is honoured by both runtimes.

Q7. "Why does a container start in tens of milliseconds when a VM takes tens of seconds? Be specific about what work is skipped and what work remains."

Reveal answer

Strong answer A VM boot does three expensive things a container never does. It initializes virtual hardware and firmware, it boots a kernel that probes devices and mounts filesystems, and it starts an init system that launches dozens of services.

That is seconds of work and hundreds of megabytes of memory before your process exists. A container start, once the image is local, is roughly five cheap kernel operations.

The clone system call with namespace flags creates a process in new namespaces in well under a millisecond. Writing a few files under /sys/fs/cgroup creates the cgroup. Mounting the overlay filesystem is metadata only, because the layers are already on disk and nothing is copied.

Creating a veth pair and attaching it to a bridge is a few netlink messages, and is actually the slowest part at around 10 to 50 milliseconds. Finally, execve starts your binary.

The work that remains is entirely yours: a Go binary is serving in 30 milliseconds total, a Spring Boot application still takes its usual several seconds to initialize because the JVM and the framework do not care that they are in a container.

The one Docker-specific cost people forget is image pull: a cold node pulling a 900 MB image spends more time on the network than the kernel spends on everything else combined.

Land it Container start is fast because nothing boots — so if your container takes eight seconds to become ready, the eight seconds are in your application, not in Docker, and that is where to optimize.

Likely follow-ups
"How would you actually measure where the time goes between docker run and the first log line?"

I would split it into three clocks. For the engine's share, docker events --format '{{.Time}} {{.Status}}' in another terminal timestamps create, start, and the network attach, and the gap between them is the daemon plus runc work, usually 50 to 200 milliseconds.

For the kernel's share, strace -f -T -e trace=clone,execve,mount,unshare on runc run against an exported bundle shows the syscall costs directly.

For the application's share, the process's own start time from /proc/<pid>/stat against the timestamp of its first log line, or for a JVM, -Xlog:startuptime and Spring's ApplicationStartup buffering.

On a typical host, the container itself is ready in under 300 milliseconds, network attach is the largest engine cost, and everything above that is the process.

If the engine share is large, the usual culprits are a slow overlay mount on a huge image with tens of thousands of files, or userland-proxy setup for many published ports.

"Why can Firecracker start a microVM in about 125 milliseconds if VMs are inherently slow to boot?"

Because it removes the three expensive things I listed rather than speeding them up.

Firecracker exposes only five virtual devices — virtio net, virtio block, a serial console, a keyboard for reset, and a clock — so there is no PCI bus to enumerate, no BIOS or UEFI firmware, and no ACPI tables to parse.

The guest kernel is booted directly from an uncompressed image with a minimal config, so device probing takes a few milliseconds. The guest init is not systemd but a tiny purpose-built init that starts one process.

Memory is mapped lazily and the VMM itself is a small Rust process of a few megabytes. The remaining cost is genuine kernel initialisation, about 100 milliseconds, which is why the floor sits there rather than at the container's 10.

Snapshot-and-restore of a booted microVM, which Lambda uses, gets below that by skipping the boot entirely.

"You said pull dominates on a cold node. What are the options for starting before the whole image has arrived?"

Lazy pulling. The idea is that a container typically touches under 10 percent of its image's files at startup, so a snapshotter that can fetch file ranges on demand can start the process after downloading only the metadata.

The eStargz format keeps a table of contents at the end of each gzip layer so the stargz snapshotter can seek into it over HTTP range requests; Nydus and SOCI do the same with a separate index.

All of them plug into containerd, which is why they need the containerd image store on Docker or a Kubernetes node. Images must be converted or built with the format, for example nerdctl image convert --estargz.

The trade-offs are that a missing file at runtime becomes a network fetch with its own latency and failure mode, and that the registry must support range requests.

For a JVM whose classpath is scanned at startup the win is smaller than for a Python image full of unused packages.

"Does the veth setup ever become a real bottleneck, and what would you do about it?"

It does when you start hundreds of containers a minute on one host, which happens with function platforms and CI runners.

Each veth pair means several netlink round trips, a bridge port addition, and iptables or nftables rule insertion; the rule insertion is the worst, because with the iptables backend every insert re-reads and re-writes the whole table, which grows with the number of published ports.

Ten thousand rules can push one attach to a second.

Mitigations, in order: switch the engine to the nftables backend, which updates incrementally; avoid publishing ports on ephemeral containers and use a shared network with service discovery instead; use --network none for jobs that need no network; or pre-create network namespaces and reuse them, which is what pooled sandbox platforms do.

At the Kubernetes level the same cost lives in the CNI plugin, and eBPF-based CNIs such as Cilium avoid iptables entirely.

Q8 · Design. "Design the isolation model for a platform that runs untrusted customer code — think serverless functions submitted by thousands of tenants. Which runtime, what limits, what you would refuse to do."

Reveal answer

The real test Whether you treat the shared kernel as the threat and layer defences, rather than trusting a seccomp profile to hold hostile code.

Strong answer Assumptions: tenants can upload arbitrary binaries, functions run for seconds to minutes, thousands of tenants share hardware, and a single cross-tenant read is a company-ending incident. The requirement is a defensible boundary, not just resource fairness. The design has four layers.

First, the runtime: every function runs in a microVM using Kata Containers or Firecracker, so each tenant gets its own guest kernel and the boundary is the hypervisor. Startup is roughly 125 milliseconds, which is acceptable for this workload.

Second, inside the microVM, still run the code as a non-root user in a container with all capabilities dropped, a read-only root filesystem, and the default seccomp profile, so a guest kernel exploit still faces a second wall.

Third, resource limits at both levels: the VM gets a fixed vCPU count and memory, and inside it the cgroup gets memory.max, cpu.max, and pids.max of about 128 to stop fork bombs.

Fourth, network egress goes through a per-tenant policy that denies the metadata service at 169.254.169.254 and any internal range by default.

Trade-offs: microVMs cost about 5 to 10 percent CPU overhead and around 30 MB of memory each, and they cannot share page cache between tenants, so density is lower than runc.

gVisor is the alternative if startup latency matters more than raw syscall performance; I would benchmark both on the real workload.

What I would not do: run tenants under plain runc with a hardened seccomp profile and call it isolation, because the history of kernel CVEs says that boundary fails a few times a year.

I would also not give tenants Docker-in-Docker or any access to the Docker socket, since either is root on the host.

Land it For hostile code, the question is never "is runc secure enough" — it is "how many independent boundaries does an attacker have to break", and one shared kernel is a count of one.

Likely follow-ups
"The requirement changes: functions must start in under 20 milliseconds warm and 100 milliseconds cold. Does the design survive?"

Not as stated; a fresh microVM boot sits at about 125 milliseconds, so I would change how VMs are obtained rather than what they are. Two techniques.

First, a warm pool: keep a few hundred pre-booted microVMs per host, each with the language runtime already initialised and paused, and assign one to a tenant on invocation, so the warm path is a resume plus a tenant-specific mount, well under 20 milliseconds.

Second, snapshot restore: boot a golden VM once, snapshot its memory and device state with Firecracker's snapshot API, and restore copies on demand with memory mapped lazily, which gets a cold start to roughly 10 to 30 milliseconds.

The cost is that the snapshot must be scrubbed of anything tenant-specific, random number generator state must be reseeded on restore, and pool capacity becomes a scheduling problem.

If even that misses the budget, I would move that tier to gVisor, accepting the weaker boundary for the latency-critical functions and documenting why.

"What would you cut first if you had to ship in six weeks instead of six months?"

I would cut the second layer inside the VM and the peer-to-peer distribution niceties, never the VM boundary.

Concretely: keep Firecracker or Kata as the isolation unit, because that is the security claim the business is built on; keep per-tenant egress policy, because the metadata service and internal network are the easiest targets; keep memory, CPU, and pid limits, because a fork bomb takes down the host otherwise.

Defer the in-VM non-root user and seccomp hardening to the second release, since a guest kernel exploit is a later threat than a hostile function calling the metadata endpoint. Defer snapshot-based fast start and accept 150-millisecond cold starts.

Defer custom base images and offer two fixed runtimes. What I would not cut is the audit log of which tenant ran on which host at what time, because the first incident will ask exactly that question.

"How do you stop a tenant from reading another tenant's data through the host's page cache or CPU side channels?"

The page cache is not shared across the VM boundary by design: each microVM has its own guest page cache and the host only sees opaque block devices, so a tenant cannot observe another's file access timing through the cache.

For CPU side channels the mitigations are scheduling and hardware.

I would pin each microVM's vCPUs so that two tenants never share a physical core's sibling hyperthreads, which is the core-scheduling feature in the Linux scheduler or simply disabling SMT on tenant hosts, at a 20 to 30 percent capacity cost.

The host kernel runs with the standard Spectre and MDS mitigations enabled, and the microVM's CPU template masks features the guest should not see. Memory is never overcommitted between tenants, and freed guest memory is zeroed before reuse.

Finally I would isolate by hardware tier: tenants who pay for it get dedicated hosts, which is the only complete answer to side channels.

"Why not just run each tenant's functions in a Kubernetes namespace with network policies and a strict PodSecurity profile?"

Because every one of those controls is enforced by the shared kernel the tenant is attacking.

A namespace is an API-server concept; a network policy is iptables or eBPF in that same kernel; the restricted PodSecurity profile removes capabilities and privilege escalation but leaves the container's system calls landing in the host kernel.

That is fine for an internal platform where tenants are colleagues, and I would use exactly that for first-party services.

For uploaded binaries from strangers, one kernel exploit reachable from an unprivileged syscall — and there are a few every year — gives the attacker every other tenant on the node.

Kubernetes can still be the control plane: I would use a RuntimeClass of kata or gvisor per pod and node pools dedicated to that runtime, so the scheduling and networking model stays familiar while the isolation unit becomes a VM.

Q9. "Explain rootless Docker and user namespaces. If root inside the container is UID 100000 on the host, how does the mapping work and what breaks?"

Reveal answer

Strong answer A user namespace is the namespace that maps user and group IDs. Inside it, a process can be UID 0 with full root capabilities, while the kernel translates that to an ordinary unprivileged UID outside.

The mapping is written to /proc/<pid>/uid_map as three numbers: inside-start, outside-start, and count. A typical line is 0 100000 65536, meaning UID 0 inside is 100000 outside, UID 1 inside is 100001, and so on for 65,536 IDs. The ranges are allocated from /etc/subuid and /etc/subgid.

Rootless mode takes this further: the whole Docker daemon runs as an unprivileged user in its own user namespace, installed with dockerd-rootless-setuptool.sh install, with the socket at $XDG_RUNTIME_DIR/docker.sock. A container escape then lands the attacker as a normal user, not root. Three things break or change.

Ports below 1024 cannot be bound without setting net.ipv4.ip_unprivileged_port_start. Networking cannot create real bridges, so it uses slirp4netns or pasta, user-space network stacks that cost measurable throughput.

And files a container writes to a bind mount appear on the host owned by UID 100000, which confuses anyone running ls. The daemon-level equivalent for a normal install is userns-remap in /etc/docker/daemon.json, which keeps the daemon as root but remaps every container.

Podman does all of this by default, which is one of its selling points.

Land it User namespaces turn "root in the container" from a real threat into a bookkeeping trick, at the cost of a few rough edges around ports and file ownership that you should know before you turn it on in production.

Likely follow-ups
"A bind-mounted directory is owned by UID 1000 on the host. Inside a remapped container, root cannot write to it. Explain and fix."

Inside the container, root is UID 0, which the kernel maps to host UID 100000. The directory is owned by host UID 1000, which from the container's perspective maps to nothing at all and shows up as nobody with the overflow ID 65534.

The container's root has no capability over files outside its mapping, so the write is refused. Three fixes, in order of preference. Use chown 100000:100000 on the host directory, or better 100000 + 1000 if the container process runs as UID 1000.

Use an idmapped mount, which Docker supports on kernels 5.12 and newer through the --mount type=bind,...,bind-recursive=writable family and Podman exposes as :idmap; it remaps ownership at the mount rather than on disk.

Or, for rootless Podman, podman unshare chown performs the chown from inside the user namespace so the numbers line up. What I would not do is make the directory world-writable.

"What performance do you lose in rootless mode, and where does it come from?"

Two places. Networking, because an unprivileged user cannot create a bridge or veth in the host namespace, so the container's traffic goes through a user-space stack.

slirp4netns copies every packet through a TAP device and a user-space TCP implementation, which caps throughput at a few gigabits and adds latency; pasta, the newer default in Podman and available for Docker, is much faster because it splices TCP connections rather than reimplementing them, but still costs more than kernel bridging.

Published ports add another hop through RootlessKit's port driver. The second place is storage: the overlay filesystem needs either kernel 5.11 or newer, which allows unprivileged overlay mounts, or the fuse-overlayfs fallback, which is markedly slower on metadata-heavy work.

As of Aug 2026 every supported distribution kernel has native rootless overlay, so storage is a non-issue; networking remains a 10 to 30 percent tax for throughput-bound services and is the reason production nodes usually keep the root daemon with userns-remap instead.

"With userns-remap on the daemon, can a container still be run without the remap when it needs real host access?"

Yes, per container, with --userns=host, which disables the mapping for that one container and gives it the daemon's real UID space. It exists for the few workloads that genuinely need it: a monitoring agent that reads host-owned files, a privileged tool container.

The important thing is that it is an opt-out, so the platform default stays safe and each exception is visible in the run command and can be audited.

In Kubernetes the equivalent is the hostUsers: false field on the pod, generally available since 1.33, which asks the runtime for a per-pod user namespace, and leaving it unset keeps the host mapping.

One caveat: images that were pulled under the remap live in a separate directory, /var/lib/docker/100000.100000/, because the layer files must be chowned into the mapped range, so switching the setting on an existing host makes existing images invisible until re-pulled.

"If root in a user namespace has full capabilities, what stops it from mounting the host's disk?"

Capabilities inside a user namespace are only valid over objects that namespace owns.

The container's root has CAP_SYS_ADMIN in its own namespace, which lets it mount a tmpfs or a bind mount of something it already sees, but the host's block devices are owned by the initial user namespace, so opening /dev/sda fails with permission denied even with every capability.

The same rule applies to loading kernel modules, changing the host's network configuration, or signalling host processes: the kernel checks whether the target object is owned by a namespace the caller's capability reaches, and the host's objects never are.

The residual risks are kernel bugs in code paths that unprivileged users can now reach, since user namespaces expose more of the kernel to non-root users; that is why some hardened distributions restrict namespace creation with the kernel.unprivileged_userns_clone or user.max_user_namespaces sysctls, which in turn breaks rootless Docker.

Drill · Overlay filesystems, layers & the writable layer

This group tests whether you can explain where a container's files physically live, why an image is bigger than it looks, and what happens on the disk when a process writes.

Q10. "Explain overlay2: what are lowerdir, upperdir, and workdir, and what exactly is copy-up?"

Reveal answer

The real test Whether you can describe the copy-up cost concretely enough that the "why is my write slow" question answers itself.

Strong answer OverlayFS is a kernel filesystem that stacks several directories and presents them as one merged view. Docker's overlay2 storage driver uses it for every container.

The lowerdir is the read-only stack of image layers, one directory per layer under /var/lib/docker/overlay2/<id>/diff, joined with colons in the mount options, lowest layer last. The upperdir is the container's private writable directory; every file the container creates or changes lands there.

The workdir is an empty scratch directory on the same filesystem that the kernel uses to make renames and copies atomic; you never touch it.

Reading a file walks the stack from the top down and returns the first match, which is a pure metadata operation and costs almost nothing.

Writing to a file that lives in a lower layer triggers copy-up: the kernel copies the entire file into the upperdir first, then applies the write there.

For a 2 GB database file inside the image, appending one byte copies 2 GB. Deleting a lower-layer file creates a whiteout, a special character device entry in the upperdir that hides the name below.

You can see all of this with docker inspect --format '{{json .GraphDriver.Data}}', which prints the four directory paths, and with mount | grep overlay on the host.

Land it Overlay makes reads free and first writes to image files expensive — so anything a container writes heavily belongs on a volume, not in the image.

Likely follow-ups
"How would you reproduce a copy-up cost and measure it, so a team believes the number?"

I would build a two-line demonstration. Start a container from an image that contains a large file, for example one built with RUN fallocate -l 2G /big.bin. Inside it, time a one-byte append: time sh -c 'echo x >> /big.bin'.

The first append takes seconds and du -sh /var/lib/docker/overlay2/<id>/diff on the host shows 2 GB appearing in the upperdir. The second append is instant, because the file now lives in the upper layer.

Then repeat with the file on a volume, -v data:/data, and the first append is also instant. The kernel does have an optimisation for metadata-only changes: since Linux 4.19 with the metacopy=on mount option, a chmod or chown copies only the inode metadata, not the data.

Docker does not enable it by default because it interacts badly with some layer-sharing checks, so the demonstration usually stands.

"What are the limits of overlay2, and when have you hit them?"

Three practical ones.

The kernel caps the number of lower directories in a single mount at 500 in recent kernels, and the mount option string has a page-size limit, so images with more than about 125 layers fail to mount; Docker also enforces a 127-layer limit on images.

Renaming a directory that exists in a lower layer fails with EXDEV unless the redirect_dir feature is enabled, which Docker leaves off, so a mv of a package directory inside a container can fail while a copy succeeds — I have seen an npm install break on exactly this.

And overlay does not support some file-system features of the backing store, such as reflinks, so tools that rely on them fall back to full copies. The backing filesystem must be ext4 or xfs with ftype=1, which the daemon checks at startup.

docker info shows the driver and the backing filesystem, and dmesg | grep overlayfs reports feature warnings.

"Where do a container's writes physically end up if I never mount a volume, and how do I find them from the host?"

They land in the upperdir, which is /var/lib/docker/overlay2/<container-layer-id>/diff/ on the host, and they exist there exactly as long as the container does. The quickest way to find the path is docker inspect --format '{{.GraphDriver.Data.UpperDir}}' web.

Deleted lower-layer files appear in that directory as character devices with major and minor number 0, which are the whiteouts, and an opaque directory marker is an extended attribute trusted.overlay.opaque you can see with getfattr.

To size it without walking the tree, docker ps -s prints the writable-layer size per container.

docker diff web lists every path that changed relative to the image with an A, C, or D marker, which is the fastest way to prove an application is writing where it should not.

docker commit turns that upperdir into a new image layer, which is useful for capturing a crashed container's state for later analysis.

"Docker is moving toward the containerd snapshotter. Does that change any of this?"

The kernel mechanism is identical: containerd's overlayfs snapshotter uses the same OverlayFS mount with lowerdir, upperdir, and workdir. What changes is bookkeeping and location.

Snapshots live under /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/<n>/fs, keyed by content digest rather than Docker's random cache IDs, and docker inspect no longer shows the GraphDriver paths; you use ctr snapshots mounts or nerdctl to find them.

The practical gains are alternative snapshotters — stargz and Nydus for lazy pulling, the native and zfs snapshotters where overlay is unsuitable — and the ability to hold multi-platform images locally. The behaviour a developer sees, including copy-up cost and whiteouts, is unchanged.

One difference worth knowing: with the containerd store, docker system df and pruning are computed from containerd's lease and content store, so tools that walked /var/lib/docker/overlay2 for disk accounting stop working.

Q11 · Scenario. "A teammate added RUN rm -rf /usr/share/doc /var/cache/apt as the last line of a Dockerfile to shrink the image. The image did not get smaller. Why, and what actually works?"

Reveal answer

Strong answer I would show the evidence, then explain the layer model:

  1. Run docker history <image>. The delete step shows a size of a few kilobytes, and the earlier layer that installed the packages still shows its full size. Total size is unchanged or slightly larger.
  2. The cause is that image layers are immutable and additive. Each RUN produces a new layer containing only the differences from the layer below. A deletion cannot reach into an earlier layer; it can only add whiteout entries in the new layer that hide the files. The bytes stay in the lower layer and are still pulled, stored, and shipped.
  3. Fix one: delete in the same RUN that created the files, chained with &&, so the files never exist in any committed layer. For example RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*.
  4. Fix two, for files a base image already contains: a multi-stage build, where a final FROM stage copies only the artifacts you need with COPY --from=build, leaving every layer of the build stage behind.
  5. Fix three: docker build --squash is deprecated, but docker buildx build --output type=image,rebase=false with a single-layer strategy or exporting through docker export and docker import produces one flat layer at the cost of losing shared-layer caching.
  6. Prevention: add dive or docker history --no-trunc to the CI pipeline with a size budget, and teach the rule that only the layer that created a file can make it disappear.

Going deeper One correction to the flattening options.

There is no rebase=false output option in BuildKit; the real ways to get a single-layer result are a multi-stage copy of the whole root, FROM scratch followed by COPY --from=build / /, which produces one layer that BuildKit can still cache as a unit, or docker export piped into docker import, which drops all metadata such as ENTRYPOINT and ENV and must be re-applied with --change.

The legacy --squash flag requires the experimental daemon setting and is ignored by BuildKit. Flattening also destroys the sharing that makes a fleet cheap: twenty services on one base each ship their own copy of the base bytes.

The order of preference is therefore same-RUN cleanup first, multi-stage second, and flattening almost never. The verification step is docker history --format '{{.Size}} {{.CreatedBy}}' before and after, plus dive's efficiency score, which counts bytes present in a lower layer and hidden by a whiteout above.

Land it A later layer can hide a file but never un-ship it — deletion only shrinks an image when it happens in the same layer as the creation.

Likely follow-ups
"They moved the rm into the same RUN as apt-get install and the image is still 900 MB. What next?"

Then the bytes were never in that layer, and I would stop guessing and rank layers by size with docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' image | sort -h.

The usual finding is that the largest layer is the base image itself or a COPY, not the apt step. A full JDK base is 450 MB; a COPY . . that captured .git, node_modules or target is a few hundred more; a downloaded installer left behind by a RUN that did not delete it is another hundred.

Each of those has its own fix: a JRE or jlink base, a .dockerignore, and deleting the installer in the RUN that downloaded it.

I would also run dive and read its "wasted bytes" figure, which counts exactly the files that exist in a lower layer and are shadowed above. If the base is the culprit, only a different FROM or a multi-stage copy changes anything.

"Why does an image with a delete layer sometimes get slightly bigger rather than staying the same?"

Because the delete produces a layer with content of its own.

Every removed path needs a whiteout entry, a zero-length file named .wh.<name> in the layer tar, or an opaque directory marker for a whole subtree; each is tiny, but a recursive delete of /usr/share/doc with thousands of files creates thousands of entries, which is the few kilobytes to a few megabytes docker history shows.

There is a second, larger effect: if the RUN also touched any file's metadata, for example a package manager rewriting its database or apt updating /var/lib/dpkg/status, the whole modified file is copied up into the new layer.

So a cleanup step that also runs apt-get clean can add a copy of the package database. None of this reclaims anything below; it is pure addition, which is the point of the question.

"Would a cache mount have avoided the problem entirely? Show me the line."

For package caches, yes, and it is the cleanest answer because the cache never enters any layer. The line is RUN --mount=type=cache,target=/var/cache/apt,sharing=locked --mount=type=cache,target=/var/lib/apt,sharing=locked apt-get update && apt-get install -y --no-install-recommends curl.

The mount is a directory BuildKit keeps between builds and attaches only for that RUN; the downloaded .deb files and the package lists stay there, are reused next build, and are absent from the image. sharing=locked serialises parallel builds that would otherwise corrupt the apt database.

You also need to remove Debian's docker-clean configuration, rm -f /etc/apt/apt.conf.d/docker-clean, which deletes the cache after every install and defeats the mount. The same pattern applies to /root/.m2, /root/.cache/pip, and /root/.npm.

It does nothing for documentation files installed by packages, which still need --no-install-recommends and a same-layer delete.

"Is there any reason to prefer a bigger image with intact package lists?"

One real reason: debuggability and reproducible patching in long-lived images. If /var/lib/apt/lists is gone, an on-call engineer who needs to apt-get install tcpdump during an incident first has to run apt-get update, which hits the network from a production host and may be blocked.

The counterargument is stronger: production images should not be patched by hand, tooling should come in a debug container, and the lists are 40 to 60 MB per image multiplied by every node.

So I delete them, and I make the debugging path explicit instead — a documented docker debug or kubectl debug workflow with a tools image that has everything installed.

The one image where I keep the lists is the CI builder image, which is not shipped and where people genuinely add packages ad hoc.

Q12. "Why is writing to the container's writable layer both slow and dangerous? Where should writes go instead?"

Reveal answer

Strong answer The writable layer is the overlay upperdir, and it has three problems.

First, performance: the first write to any file that exists in the image triggers a copy-up of the whole file, and every write goes through the overlay layer's extra bookkeeping, which benchmarks at roughly 10 to 30 percent slower than a plain ext4 or xfs directory for metadata-heavy workloads.

Second, it is ephemeral by design: the upperdir is deleted with docker rm, and any orchestrator that replaces a container — a Kubernetes rollout, a crashed pod being rescheduled — silently discards everything in it.

Third, it is unaccounted: nothing limits its size by default, so a log file that grows to 40 GB fills /var/lib/docker and takes down every container on the node.

docker ps -s shows each container's writable-layer size and is the first thing to run when a node's disk is full. The correct home for writes depends on the data.

Data that must outlive the container goes on a volume, a directory Docker manages outside the overlay under /var/lib/docker/volumes, mounted with -v name:/path, which bypasses overlay entirely. Scratch data that should vanish goes on --tmpfs /tmp, which lives in memory and counts against the cgroup.

Logs go to stdout so the logging driver handles them. The image's own root filesystem should be mounted --read-only so accidental writes fail loudly in testing rather than quietly in production.

Land it Treat the writable layer as a place that does not exist — a container that runs correctly with --read-only is a container whose state you actually understand.

Likely follow-ups
"The application must write temp files and it runs with --read-only. What exactly do you mount and how big?"

I would mount a tmpfs at every path the process legitimately writes, sized explicitly. --tmpfs /tmp:rw,noexec,nosuid,size=256m covers the JVM's java.io.tmpdir and most libraries; Tomcat also needs its work directory, so I point server.tomcat.basedir at /tmp/tomcat rather than mounting a second path.

The size= matters because tmpfs pages are charged to the container's memory cgroup, so a 2 GB tmpfs on a 1 GB container is a self-inflicted OOM kill waiting for a large upload. noexec stops a compromised process dropping a binary there and running it.

In Kubernetes the equivalent is an emptyDir with medium: Memory and a sizeLimit, plus readOnlyRootFilesystem: true in the security context.

To find the paths, I run the service once without --read-only and use docker diff to list what it wrote; anything outside /tmp is either a bug or a mount I need.

"How do you find out which container is eating the disk on a full node, and free it without restarting everything?"

In order: docker system df to see whether the space is in images, containers, volumes, or build cache, then docker ps -s --format '{{.Names}} {{.Size}}' to rank writable layers, then du -sh /var/lib/docker/containers/*/ for log files, which sit outside the overlay and are the most common culprit when the json-file driver has no rotation.

For a fat writable layer, docker diff name | head shows what is being written, and I can delete inside the container with docker exec name sh -c 'rm /app/logs/*.log'; because the file lives in the upperdir, deleting it frees space immediately.

For logs, truncate -s 0 /var/lib/docker/containers/<id>/<id>-json.log on the host frees space without touching the container. Then docker builder prune and docker image prune for the cache and dangling images.

Restarting is a last resort, and the fix afterwards is rotation in daemon.json and a volume for the app's writes.

"Named volume versus bind mount versus tmpfs — when is each the right answer?"

A named volume, -v pgdata:/var/lib/postgresql, is a directory Docker owns under /var/lib/docker/volumes; it is the default for data the container owns, because Docker manages its lifecycle and permissions, it works identically on Linux and Docker Desktop, and volume drivers can back it with network or cloud storage.

A bind mount, -v /srv/config:/etc/app:ro, maps a host path you control; it is right for configuration from the host, for source code during development, and for anything another host process must also read, at the cost of host-path coupling and the file-ownership problems from the user-namespace question.

A tmpfs is memory, disappears on stop, counts against the memory limit, and is right for secrets and scratch data that must not touch disk.

The rule I give teams: databases and uploads on volumes, config and source on bind mounts read-only, temp and secrets on tmpfs, and nothing on the writable layer.

"Does a volume actually perform like a native directory, and what about on Docker Desktop?"

On Linux, yes: a named volume is a plain directory on the host filesystem bind-mounted into the container, with no overlay in the path, so reads and writes run at the speed of the backing disk and fsync behaves normally.

That is why databases in containers perform fine when they use volumes. On Docker Desktop the picture splits. A named volume lives inside the Linux VM's own virtual disk, so it is fast — comparable to native Linux.

A bind mount from the macOS or Windows host crosses the VM boundary through VirtioFS or gRPC-FUSE, and metadata-heavy operations such as a git status over 50,000 files or a node_modules install can be five to twenty times slower.

The practical rule on laptops is to keep dependencies and databases in named volumes and bind-mount only the source files a developer is editing. You can measure the difference with fio or simply time find . | wc -l in both kinds of mount.

Q13 · Scenario. "Your Spring Boot image is 1.4 GB. The jar is 60 MB. Find where the bytes are and get the image under 300 MB."

Reveal answer

The real test Whether you measure before guessing — most candidates jump to "use Alpine" without looking at the layers.

Strong answer I would go layer by layer:

  1. Evidence first: docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' <image> lists every layer with its size and the instruction that created it. Sort it mentally by size. For a deeper look, dive <image> shows which files each layer adds and flags wasted space.
  2. Typical findings, ranked by how often I see them: the base is a full JDK image such as eclipse-temurin:21-jdk at about 450 MB when a JRE at 200 MB or a jlink-trimmed runtime at 80 MB would do; the build happened in the same stage, so Maven's ~/.m2 cache, the source tree, and target/ are all baked in at several hundred megabytes; an apt-get install layer kept its package lists and docs; and a COPY . . pulled in the .git directory because there is no .dockerignore.
  3. Fix: switch to a multi-stage build. Stage one uses the JDK image and Maven to produce the jar. Stage two starts from eclipse-temurin:21-jre-alpine or a distroless Java base and copies only the jar. Add a .dockerignore with .git, target, and IDE folders. Use Spring Boot's layered jar with java -Djarmode=tools -jar app.jar extract --layers so dependencies land in a separate, rarely changing layer from application classes.
  4. Verify: docker image ls should show around 200 to 260 MB, and docker history should show the jar layer as the only one that changes between builds.
  5. Prevention: a CI check that fails the build when the image exceeds 350 MB, and a shared base image the platform team maintains so every service starts from the same trimmed runtime.

Land it The bytes are almost never in the jar — they are in the build tools and the base runtime, and a multi-stage build removes both without touching the application.

Likely follow-ups
"You suggested a JRE Alpine image, but elsewhere you warn against Alpine for the JVM. Which is it?"

The warning wins; I would use a glibc runtime, and I would correct that suggestion. eclipse-temurin:21-jre-jammy is Ubuntu-based, about 190 MB with the JRE, and has no musl surprises.

If I need smaller, jlink on a Debian-slim base gives roughly 120 MB with a 60 MB custom runtime, and distroless gcr.io/distroless/java21-debian12 lands around 130 MB with no shell.

Temurin's Alpine variant does work — Adoptium tests it — but it inherits musl's memory allocator behaviour, the 128 KB default thread stack, and the DNS resolver differences, and every one of those has produced a production ticket I have had to explain.

Saving 60 MB on a 200 MB image is not worth a class of bugs that only appear under load.

The size target of 300 MB is comfortably met without Alpine, which is the real point: the bytes were in the JDK and the build tools, not in the operating system layer.

"After the multi-stage rewrite the image is 280 MB but every commit still pushes 200 MB. Why?"

Because size and layer churn are different problems.

The final stage probably copies the whole fat jar in one COPY, so every commit produces a new 80 MB jar layer, and if the JRE stage was rebuilt from a moving tag between builds the base layers changed too.

I would compare docker image inspect --format '{{.RootFS.Layers}}' for two consecutive builds and count how many diff IDs differ; the answer should be one.

The fixes are the Spring Boot layered extraction, so dependencies sit in their own layer that only changes when the pom changes, and pinning the runtime base by digest so its layers stay byte-identical across builds.

After that a code-only commit changes only the application layer, typically under a megabyte, and the registry push shows every other layer as "Layer already exists".

The metric I would put in CI is the unique bytes of each new image versus the previous one, not the total size.

"What does dive tell you that docker history does not?"

docker history shows one row per layer with its size and the instruction; it cannot tell you which files are inside or whether they are shadowed later.

dive unpacks every layer and shows a file tree per layer with added, modified, and removed markers, so I can see that a 300 MB RUN layer is 280 MB of /root/.m2, or that a COPY brought in .git.

It also computes an efficiency score and a wasted-bytes figure: bytes present in a lower layer and overwritten or deleted in a higher one, which is exactly the "rm in a later layer" mistake made visible.

It runs in CI with dive --ci --lowestEfficiency 0.95 image:tag and fails the build below the threshold.

The limitation is that it needs the image locally and is slow on very large images, so I run it on the pull request that changes a Dockerfile rather than on every commit.

"If the team insists on a single-stage Dockerfile for simplicity, how close to 300 MB can you get?"

Not close, and I would show them why with numbers. A single stage needs Maven and the JDK to compile, which is at least 450 MB before the application; Maven's local repository for a Spring Boot project is another 300 to 500 MB; deleting either in a later layer changes nothing. The only single-stage tricks are building the jar outside Docker in CI and copying the prebuilt jar in — which is legitimate and is what my template does, with the JDK stage used only for layer extraction — or using a cache mount for .m2 so the repository never enters a layer, which still leaves the JDK. So a true single-stage build from source bottoms out around 700 MB. The honest offer is: build in CI, copy the jar, two-stage extraction, and I write the template once so simplicity is preserved for the twenty services that copy it.

Q14. "docker image ls says my images total 12 GB but the disk shows only 4 GB used by Docker. Explain how image size is accounted and what docker system df shows differently."

Reveal answer

Strong answer An image's size, as printed by docker image ls, is the sum of the sizes of all its layers.

But layers are content-addressed: each one is identified by the SHA-256 hash of its contents and stored exactly once on disk, no matter how many images reference it.

If twenty microservice images all start from the same 200 MB base and add 30 MB each, docker image ls reports 230 MB twenty times, a total of 4.6 GB, while the disk holds one 200 MB base plus twenty 30 MB layers, which is 800 MB. docker system df reports the deduplicated truth: one row each for images, containers, local volumes, and build cache, with a SIZE column that is the real disk footprint and a RECLAIMABLE column for what docker system prune could free.

Adding -v shows per-image shared size versus unique size, which is the number you actually want when deciding what to delete: removing an image frees only its unique size.

To see which layers two images have in common, compare docker image inspect --format '{{.RootFS.Layers}}' for each; the entries are the diff IDs, and matching entries are physically the same directory under /var/lib/docker/overlay2.

Containers add their writable layers on top, visible with docker ps -s, and the build cache under docker buildx du is frequently the largest and least noticed consumer.

Land it docker image ls answers "how big is this image if it were alone", and docker system df -v answers "how much disk do I get back if I delete it" — only the second number matters for a full disk.

Likely follow-ups
"What does docker system prune actually delete, and what is the flag that bites people?"

Plain docker system prune removes stopped containers, networks not used by any container, dangling images — those with no tag and no container — and the build cache. It leaves tagged images and all volumes alone.

The flag that bites is -a, which also removes every image not currently used by a running container, so on a node that was mid-deploy or on a laptop with a week of pulled images it triggers a full re-pull of everything.

The second one is --volumes, which deletes every unused named volume, including the database volume of the container someone stopped an hour ago; there is no undo.

I run docker system df -v first to see what would go, use docker builder prune --keep-storage 20GB on build hosts so the cache stays warm, and set --filter until=72h on scheduled prunes so recently pulled images survive.

On Kubernetes nodes the kubelet does its own image garbage collection by disk thresholds, and manual pruning fights it.

"Two images report the same 200 MB base layer, yet docker system df says shared size is zero. What would cause that?"

The two "same" layers are not the same bytes.

The most common reason is that the base tag moved between the two pulls, so the diff IDs differ even though the tag name matches; I confirm with docker image inspect --format '{{.RootFS.Layers}}' on both and compare the first entries.

The second reason is that a layer with identical content sits on top of a different parent: overlay2 keys directories by chain ID, which includes the parent, so the same diff on a different base is stored twice.

The third is compression or platform differences: a zstd push and a gzip push of the same content share a diff ID after unpack, so that one does share, but an arm64 and an amd64 variant of the same image do not.

The fix for the fleet is digest pinning of the base and rebuilding every service from one digest in one pass, which is the answer to the next scenario.

"How does the build cache grow to 30 GB unnoticed, and how do you bound it?"

BuildKit keeps every intermediate layer and every cache-mount directory it has ever produced, keyed by content, and nothing evicts them automatically until a size policy fires.

On a developer machine or a long-lived CI host, every change to a Dockerfile line creates a new chain of layers below it, and the old chain stays. Cache mounts for .m2 or pip grow monotonically.

docker buildx du lists entries with sizes and last-used times and is the diagnostic.

To bound it, set garbage collection in the daemon: in daemon.json, "builder": {"gc": {"enabled": true, "defaultKeepStorage": "20GB"}}, or for a buildx builder, a buildkitd.toml with a [worker.oci] gc = true section and policies by age.

docker builder prune --filter until=168h on a cron is the manual equivalent. In ephemeral CI the local cache is thrown away with the runner, which is why remote registry caches with a retention policy replace it.

"Where does the space go on a node where images, containers, and volumes together are far less than the disk used under /var/lib/docker?"

Three usual hiding places. Container logs under /var/lib/docker/containers/<id>/<id>-json.log are not counted by docker system df at all, and without max-size a chatty service writes tens of gigabytes; du -sh /var/lib/docker/containers finds it.

The build cache is counted, but cache mounts and the containerd content store when the containerd image store is enabled live under /var/lib/containerd, a different tree.

And leaked overlay directories: after a hard daemon crash, upperdirs of containers that no longer exist can remain under overlay2; comparing ls /var/lib/docker/overlay2 | wc -l against the number of layers Docker knows about, or simply restarting the daemon and pruning, reclaims them.

A fourth, on hosts with deleted-but-open files, is a process still holding a removed log; lsof +L1 finds it, and only closing the file returns the space.

Q15 · Scenario. "Two services share a base image. After a base image update, the nodes' disks filled up and docker system df shows the old and new base both present with hardly any sharing. What happened?"

Reveal answer

Strong answer I would confirm the sharing story and then find why it broke:

  1. Evidence: docker image inspect --format '{{.RootFS.Layers}}' service-a:new service-b:new. If the base layers' diff IDs differ between the two services, the two builds did not actually use the same base. docker system df -v will show low shared size, confirming it.
  2. Cause one, most common: the two services were built at different times from a mutable tag like base:latest or eclipse-temurin:21, and the tag moved between the two builds. The services now reference two different base images that happen to share a name. Two base images at 450 MB each, times every node, is your missing disk.
  3. Cause two: the base was rebuilt without any content change, but the build was not reproducible — timestamps in apt package lists or a RUN date style step produced different layer contents and therefore different digests. Same bytes in spirit, different hashes in fact.
  4. Cause three: one service was built with BuildKit's --platform different from the other, or one of them used a compression change such as zstd, which produces different blob digests even for identical uncompressed content.
  5. Fix: pin the base by digest in every Dockerfile, FROM eclipse-temurin:21-jre@sha256:..., and have a single job that updates that digest across all services in one commit. Prune the old base once every service has rolled: docker image prune removes dangling layers nothing references.
  6. Prevention: set SOURCE_DATE_EPOCH in the build for reproducible timestamps, and add a nightly check that all services in the fleet reference exactly one base digest.

Land it Layer sharing is a property of digests, not of names — two images share a base only if they were built from the same bytes, and a moving tag quietly guarantees they were not.

Likely follow-ups
"You pinned the base by digest in every Dockerfile and the disks filled again a month later. What did you miss?"

Probably that pinning stops drift but does not create sharing on its own; the two services still had to be rebuilt from the same digest, and old images still had to be removed. I would check three things.

First, whether all 40 Dockerfiles actually reference one digest today: a script that greps FROM .*@sha256 across repositories and counts distinct values.

If a bot bumped half of them, the fleet has two bases again by design, and the fix is a single bump commit across all services.

Second, garbage collection on the nodes: pinning does nothing about images from previous deploys, so docker image prune or the kubelet's image GC thresholds must be running. Third, the build stage: mode=max registry caches export intermediate stages, and if nodes are also builders those layers count.

The rule is one digest across the fleet, rolled in one pass, with eviction of the old one confirmed by docker system df before closing the ticket.

"How do you roll a base image update across 40 services safely without a week of coordination?"

By making the base a build argument rather than a hard-coded line, and owning the bump centrally. Each Dockerfile says ARG BASE=registry/base/java21-jre@sha256:... then FROM ${BASE}, and the platform repository holds the canonical digest.

A weekly pipeline builds the new golden base, scans it, and opens one pull request per service that updates the ARG — Renovate's digest pinning does exactly this — or, for services that build from a shared CI template, a single change to the template.

Rollout is then ordinary CI: each merge rebuilds that service on the new base, and deployment follows the normal promotion path.

To keep disks sane during the transition, node image GC runs continuously, and I track a dashboard of base digests in use per environment so I can see the old one drain to zero.

The one thing I would avoid is rebuilding all 40 in one hour and deploying them together, because a bad base then breaks everything simultaneously.

"Could zstd compression alone have caused the low sharing? Explain what does and does not change."

Compression changes the blob digest but not the diff ID, so it changes what is transferred and stored in the registry, not what is stored on the node.

Two pushes of the same layer, one gzip and one zstd, appear as different blobs in the registry with different manifest digests, so the registry sees no sharing and a node that already has the gzip version still downloads the zstd one — it compares blob digests before deciding to skip.

After decompression the tar is byte-identical, the diff ID matches, and overlay2 stores it once. So zstd can explain duplicate bytes in the registry and a needless pull, but not duplicate directories on disk.

If the disks are full with two copies, the uncompressed content differed, which points back to a moved tag or a non-reproducible rebuild.

The one caveat is the containerd store with lazy-pull formats, where the compressed blob is what is stored locally and different compressions do not share.

"What does SOURCE_DATE_EPOCH actually fix here, and what does it not?"

It fixes timestamp drift. Every file in a layer tar carries a modification time, and the image config carries a creation time; two rebuilds a day apart of identical content produce different tar bytes and therefore different diff IDs purely because of those times.

Setting SOURCE_DATE_EPOCH to a fixed value, typically the commit time, makes BuildKit stamp the config and — with the rewrite-timestamp=true output option — every file in the layers with that time, so identical content yields identical layers.

It does not fix content that genuinely differs: an apt-get update that pulled a newer package list, a pip install without a lockfile, a random secret generated at build time, or a base tag that moved. Those need pinning and lockfiles.

So it is the last ten percent of reproducibility, valuable once the first ninety percent is done, and worthless before.

Q16. "How does BuildKit decide a layer is cached? What is the difference between a layer's diff ID, its chain ID, and the blob digest in the registry?"

Reveal answer

The real test Whether you know there are three different hashes and which one each tool shows you.

Strong answer BuildKit, the build engine behind docker build since Docker 23, keeps a cache keyed on the instruction and its inputs.

For a RUN step the key is the command string plus the cache key of the parent layer, so a change anywhere above invalidates everything below.

For COPY and ADD the key also includes a hash of the file contents and permissions being copied, which is why touching one source file rebuilds every later step. BuildKit does not re-run a step to find out whether its output changed; it trusts the key.

That is the whole reason Dockerfile ordering matters: put the rarely changing dependency install above the frequently changing source copy. Now the three hashes.

The diff ID is the SHA-256 of the uncompressed layer tar, listed in the image config under rootfs.diff_ids and shown by docker image inspect --format '{{.RootFS.Layers}}'.

The chain ID is derived by hashing the parent's chain ID together with this diff ID, so it identifies the layer plus everything below it; that is what the storage driver uses as the directory name, because the same diff on top of a different parent is a different filesystem.

The blob digest is the SHA-256 of the compressed tar as it sits in the registry, listed in the manifest.

Compress the same layer with gzip versus zstd and you get a different blob digest but the same diff ID. Pulling verifies the blob digest, decompresses, then verifies the diff ID, so both are checked.

Land it Diff ID is what the bytes are, chain ID is what the bytes are on top of, and blob digest is how they travel — the registry knows only the third and the storage driver cares only about the second.

Likely follow-ups
"Does changing an ENV line halfway down invalidate the layers below it, even though ENV adds no filesystem layer?"

Yes. The cache key of every instruction includes the full build state it runs on, and environment variables are part of that state because any later RUN could read them.

So changing ENV APP_VERSION=1.2 to 1.3 above a RUN produces a cache miss for that RUN and every instruction after it, even though the ENV itself is metadata only.

The same applies to ARG, but only from the first instruction that actually consumes the ARG, which is why I declare build arguments as late as possible.

The practical consequence is a Dockerfile ordering rule: environment that changes often, such as a version label or a build number, belongs at the bottom, after the expensive layers. LABEL behaves the same way.

A cheap way to see it is docker build --progress=plain, which prints CACHED against each step and shows exactly where the miss started.

"Two teammates build the same commit on their laptops and get different image IDs. Is the cache broken?"

Not necessarily. The image ID is the hash of the config blob, which includes the creation timestamp and the history entries, so two independent builds of identical content still get different IDs unless the build is made reproducible with SOURCE_DATE_EPOCH.

The right comparison is the list of diff IDs: docker image inspect --format '{{.RootFS.Layers}}' on both machines. If those match, the filesystem content is identical and only metadata differs.

If they diverge from some layer down, I look at that instruction: a RUN that fetched something from the network, a COPY of files whose content differs because one laptop has untracked files, or a base tag that resolved to different digests on the two machines because one pulled it last month.

That last case is extremely common and is fixed by digest pinning. The cache itself is per machine and never claims to produce identical IDs across hosts.

"How does the registry decide whether it already has a blob during a push, and what does that save?"

Before uploading each layer, the client sends HEAD /v2/<repo>/blobs/sha256:<blob-digest>; a 200 means the registry has it and the client skips the upload, which is the "Layer already exists" line.

Because the check is by blob digest, the compressed bytes must be identical, so recompressing with different settings defeats it. There is a second optimisation: cross-repository blob mounting.

If the blob exists in another repository the client can read, it sends POST /v2/<repo>/blobs/uploads/?mount=<digest>&from=<other-repo> and the registry links the existing blob without any transfer. That is how 40 services on one base push the base once per registry, not once per service.

The client tries the mount for layers it knows came from another image. In practice this makes a push cost only the unique layers, which for a code-only commit on a well-layered image is under a megabyte plus a manifest.

"Where does BuildKit store its cache keys, and can you inspect why a step missed?"

The keys live in BuildKit's own metadata store under /var/lib/buildkit for a standalone builder or inside /var/lib/docker/buildkit for the default one, alongside the content. You cannot query the key of a specific step directly, but you can get most of the way.

docker buildx du --verbose lists cache records with their description, which names the instruction, and their last-used time. --progress=plain shows CACHED per step, so the first non-cached step is the miss.

For COPY misses, BuildKit hashes file content and mode, ignoring mtime, so a miss means bytes changed or permissions changed; git diff --stat and a check for a generated file usually explain it.

For a registry cache, docker buildx imagetools inspect registry/app:buildcache --raw shows the cache manifest and the layer digests it can supply.

As of Aug 2026 there is also docker buildx history, which records each build and lets you inspect its steps and cache results after the fact.

Q17 · Design. "Design a layer-caching strategy for a monorepo with 40 Java services that share libraries. Builds currently take 12 minutes each in CI because nothing is cached between runs."

Reveal answer

Strong answer Assumptions: CI runners are ephemeral, so the local BuildKit cache is empty on every run; services share a parent POM and a handful of internal libraries; most commits touch one or two services.

Requirements: a no-change rebuild under one minute, a single-service change under three minutes, and no cross-service cache poisoning. The design has three parts.

First, Dockerfile structure: a common base stage that installs the JRE and any OS packages, then a dependency stage that copies only the pom.xml files and runs mvn dependency:go-offline, then the source copy and compile, then a slim runtime stage that copies Spring Boot's extracted layers in order — dependencies, snapshot dependencies, application.

Each stage changes at a different rate, so each caches independently. Second, remote cache: build with docker buildx build --cache-from type=registry,ref=registry/svc:buildcache --cache-to type=registry,ref=registry/svc:buildcache,mode=max. mode=max exports intermediate stages, not just the final image, so the dependency stage is reused even when the source changes.

For 40 services I would use one cache ref per service plus one shared ref for the common base stage.

Third, a builder with persistent state: a buildx Kubernetes driver or a dedicated build host with a warm /var/lib/buildkit, so the registry cache is the fallback rather than the only cache.

Trade-offs: mode=max caches can reach several gigabytes per service and need a retention policy; registry cache push adds 20 to 40 seconds per build; and cache keys are per-instruction, so a change to the shared parent POM still rebuilds all 40 dependency stages, which is correct but slow.

What I would not do: mount the CI runner's Docker socket and rely on local cache, because runners are recycled and the cache disappears; and I would not use a single shared cache ref for all services, because unrelated services would evict each other's layers.

Land it Caching in CI is a question of where the cache lives, not whether BuildKit is clever — export intermediate stages to a registry and order the Dockerfile from slow-changing to fast-changing.

Likely follow-ups
"The requirement changes: the monorepo builds with Gradle and a shared build cache, not Maven. What changes in the design?"

The Docker-layer part stays, but the dependency stage changes shape, because Gradle has no equivalent of dependency:go-offline that is reliable across plugins.

I would copy settings.gradle.kts, the root and module build.gradle.kts files, gradle.properties, the version catalog under gradle/, and the wrapper, then run ./gradlew dependencies --no-daemon or a custom task to resolve all configurations.

The Gradle home, /root/.gradle, goes on a BuildKit cache mount so the download survives even when a build file changes.

Then Gradle's own remote build cache — an HTTP cache such as the Develocity cache node — takes over for compilation: it caches task outputs by input hash, so an unchanged module's compile and test tasks are fetched rather than rerun, which is finer-grained than any Docker layer.

The result is two caches with different jobs: Docker layers for the runtime image and the dependency download, Gradle's cache for compile output. Both must be keyed per branch to avoid poisoning main from feature branches.

"You have four hours to cut the 12 minutes. What do you do first and what do you leave?"

First hour: add a .dockerignore and split the COPY so the pom files are copied and resolved before source; that alone stops the 40 dependency downloads on every commit and is typically half the time.

Second hour: add --mount=type=cache,target=/root/.m2 to the build RUN and switch CI to --cache-from and --cache-to against a registry ref per service with mode=max.

Third hour: move tests out of the image build into a parallel CI job, since a Docker build should compile and package, not test. Fourth hour: verify with --progress=plain that a no-change rebuild is all CACHED and measure.

I would leave for later the shared base stage across services, the persistent builder host, and the cache retention policy, because they are optimisations of an already working cache. I would also leave the parent-POM invalidation problem alone; it is correct behaviour and rare.

"How do you prevent one service's feature branch from polluting the cache that main relies on?"

By scoping cache references, and by only writing from trusted branches. The registry cache ref becomes registry/svc:buildcache-main for main and registry/svc:buildcache-<branch> for feature branches.

A feature build reads from both, --cache-from for its own branch first and then main, but writes only to its own ref; main builds read and write only main. That way a branch that changes the dependency stage never overwrites main's warm dependency layers.

Branch cache refs get a short retention, say seven days, enforced by a registry lifecycle rule on the tag pattern.

There is no correctness risk in the other direction because cache entries are content-addressed: a branch can only be served a layer whose inputs hash identically, so a poisoned cache in BuildKit terms means a stale or wasted cache, not a wrong image.

The same scoping applies to GitHub's type=gha backend through its scope= option.

"What breaks at 400 services instead of 40?"

Three things. Registry storage: at mode=max and a few gigabytes per service, 400 services is over a terabyte of cache, so retention rules and a nightly imagetools cleanup become mandatory rather than nice to have.

The shared-base rebuild: a parent POM bump now rebuilds 400 dependency stages, and if they all run at once they saturate the artifact repository, so I would pre-warm one shared dependency stage image and have every service FROM it rather than resolving independently.

And CI orchestration: the cache push adds 20 to 40 seconds per build, which at 400 services and several builds each per day is hours of runner time, so I would move to a persistent BuildKit cluster — the buildx Kubernetes driver with several replicas and a local persistent volume — where the registry cache is a fallback and most hits are local.

At that scale a build-graph tool that knows which services a commit actually affects, such as Bazel or Nx affected-detection, matters more than any Docker trick.

Drill · OCI images, identity & pulling

These questions test whether you understand an image as a signed-by-hash graph of blobs in a registry — and whether you can explain why a tag is a name and a digest is an identity.

Q18. "Describe the OCI image format: what is in the manifest, the config, and a layer, and how are they linked?"

Reveal answer

Strong answer The Open Container Initiative image specification defines an image as a small graph of JSON documents and tar files, all linked by content hashes.

The manifest is a JSON document listing one config blob and an ordered array of layer blobs, each entry giving a media type, a size, and a SHA-256 digest.

The config is another JSON blob holding what the runtime needs to start the container — the entrypoint and command, environment variables, working directory, exposed ports, the user, and the rootfs.diff_ids list of uncompressed layer hashes — plus the build history.

Each layer is a tar archive of the filesystem changes that step made, usually compressed with gzip and increasingly with zstd, with whiteout files marking deletions.

Every blob is stored and fetched by its digest, so the manifest's digest identifies the entire image: change one byte in any layer and every hash above it changes. That is why pulling by digest is tamper-proof without any signature.

Above the manifest sits the optional manifest list or OCI image index, a JSON document pointing at one manifest per platform. You can see all of it with docker manifest inspect nginx:latest for the index and manifest, and docker image inspect nginx for the config.

The image ID that Docker prints is the SHA-256 of the config blob, which is why it differs from the registry digest, which is the SHA-256 of the manifest.

Land it An image is a Merkle tree of blobs — manifest points at config and layers by hash — and every guarantee about identity and integrity follows from that single fact.

Likely follow-ups
"Show me how you would fetch the manifest and config of an image with nothing but curl."

For a public Docker Hub image the sequence is three calls. First a token: curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:library/nginx:pull" | jq -r .token.

Second the manifest: curl -s -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json" https://registry-1.docker.io/v2/library/nginx/manifests/latest, which returns the index; I pick the linux/amd64 entry's digest and repeat the call with that digest in place of latest to get the platform manifest.

Third the config: curl -s -L -H "Authorization: Bearer $TOKEN" https://registry-1.docker.io/v2/library/nginx/blobs/sha256:<config-digest>, which is the JSON with the entrypoint and the diff IDs. The Accept header is the part people forget; without it some registries return a legacy schema.

The crane manifest and crane config commands do the same with less typing.

"What is an OCI artifact, and how do signatures and SBOMs attach to an image without changing its digest?"

The OCI image spec was generalised so that a manifest can carry any content type, not just container layers — a Helm chart, a WASM module, an SBOM, a signature. Such a manifest is an artifact.

Attaching one to an image uses the subject field, added in image-spec 1.1: the artifact's manifest names the image manifest's digest as its subject, and the registry indexes that relationship. Clients query GET /v2/<repo>/referrers/<image-digest> to list everything attached.

The image's own digest is untouched because nothing in the image changed; the link points from the artifact to the image, not the other way. cosign sign and cosign attest publish signatures and attestations this way, and oras attach does it for arbitrary files.

Registries without referrers support fall back to a tag-schema convention, a tag named sha256-<digest>.sig, which is what older cosign versions used and which pollutes tag listings.

"Why do Docker's image ID and the registry digest differ, and which one should a deployment manifest use?"

The image ID is the SHA-256 of the config blob; the registry digest is the SHA-256 of the manifest, which itself contains the config digest plus the compressed layer digests.

They differ because the manifest includes compressed blob digests, and compression is not part of the local image.

The same image pushed to two registries with different compression has two different registry digests and one image ID. A deployment manifest must use the registry digest, in the form registry/app@sha256:..., because that is what the node will ask the registry for and verify on the wire; the image ID means nothing to a registry.

Locally, docker image inspect --format '{{.RepoDigests}}' lists the registry digests an image is known by, one per repository it was pushed to or pulled from, and it is empty for an image built locally and never pushed.

A multi-platform tag has a third value, the index digest, which is the one to pin for a mixed fleet.

"What is in the image config that a scanner or a runtime cares about beyond the entrypoint?"

The history array, one entry per instruction with the command text and an empty_layer flag, which is what docker history prints and where an ARG-passed secret leaks. The rootfs.diff_ids list, which the runtime verifies after decompressing each layer.

The os, architecture, and variant fields that the index entry is derived from.

Under config: User, which admission controllers read to enforce non-root; ExposedPorts; Env, which scanners grep for credentials; Labels, where the org.opencontainers.image.revision and source keys let a scanner tie a vulnerability back to a commit; StopSignal; Healthcheck; and Volumes.

Scanners such as Trivy read the config for labels and environment, then unpack the layers to enumerate packages. The config is small — a few kilobytes — which is why crane config is a fast way to audit a whole registry without pulling anything.

Q19. "Tags versus digests: what does each guarantee, why is latest a trap, and what does an immutable tag actually mean?"

Reveal answer

The real test Whether you can state that a tag is a mutable pointer in one sentence, and then say what you do about it in production.

Strong answer A tag is a human-readable name that a registry maps to a manifest digest, and that mapping can be changed by anyone with push access at any time. It guarantees nothing about content.

A digest, the sha256:... string, is the hash of the manifest, so it identifies exactly one set of bytes forever.

latest is not special in the registry; it is simply the default tag used when you omit one, which makes it the tag most likely to be overwritten and the one most likely to be pulled by accident.

The trap is that docker run nginx on two nodes an hour apart can run two different images, and neither log line tells you which. Beyond latest, the same problem applies to nginx:1.27, which the maintainers legitimately move on every patch release.

An immutable tag is a registry-side policy — available in Amazon ECR, Google Artifact Registry, Harbor, and GitHub Container Registry — that rejects a push to a tag that already exists.

It turns a tag into a write-once name, so myapp:1.4.2 can be trusted as much as its digest once it has been pushed.

My production rule is to build once, tag with the git SHA and a semantic version, enable immutability on those tags, and have the deployment manifest reference the digest, recorded at build time with docker buildx build --push --metadata-file meta.json or docker image inspect --format '{{index .RepoDigests 0}}'.

Then a rollback is a change of digest, and an audit is a grep.

Land it Tags are for humans to find things and digests are for machines to run things — deploy by digest and the words "it worked yesterday" become a diff of two hashes.

Likely follow-ups
"If you deploy by digest, how do you ever roll forward, and how do you keep the manifests readable for humans?"

Roll forward is a change to the digest line, made by a machine and reviewed by a human.

The build pipeline emits the digest as an output, and a promotion step opens a pull request against the environment's GitOps repository changing image: registry/app@sha256:old to @sha256:new; merging is the deploy.

For readability I keep the tag alongside the digest in the same reference, registry/app:1.4.2@sha256:..., which Docker, containerd, and Kubernetes all accept — the tag is ignored for resolution but stays visible in kubectl describe and in the diff.

Tools that make this routine are Renovate with digest pinning, Flux's image automation, and Argo CD Image Updater. Rollback is a revert of that commit.

The dashboard question "what is running" is answered by kubectl get pods -o jsonpath='{..imageID}', which reports the resolved digest regardless of how the manifest referenced the image.

"Immutable tags are on. A developer needs to re-push a fix to 1.4.2. What do you tell them?"

That there is no such thing as a fixed 1.4.2, and that is the feature. A tag that could be replaced would make yesterday's deployment record meaningless.

The fix becomes 1.4.3, or, if the versioning scheme is git-SHA-based, simply the new commit's SHA; the pipeline builds it, tests it, and promotes it through the normal path.

If the objection is that a release manifest already names 1.4.2, that manifest gets updated, which is a one-line change and exactly the audit trail we want.

The one exception I allow is the floating environment tags such as staging and prod, which are mutable by design because they are pointers, and which are never used in a deployment manifest.

Registries let you set immutability per repository or per tag pattern — ECR's imageTagMutability, Harbor's tag immutability rules — so version tags are locked while environment tags float.

"What does imagePullPolicy have to do with this, and what is the trap with latest there?"

Kubernetes decides at pod start whether to ask the registry again or reuse what the node already has. The default is IfNotPresent, except that a tag of latest or no tag at all defaults to Always.

So a manifest that says image: app:latest re-resolves the tag on every pod restart, meaning two replicas started an hour apart can run different code, and a node reboot silently upgrades the service.

A manifest that says app:1.4.2 with IfNotPresent has the opposite trap: if someone re-pushed 1.4.2, nodes that already have the old bytes keep running them while new nodes pull the new ones.

Pinning by digest makes the policy irrelevant, because the node can only ever have or fetch one set of bytes for that reference. That is the real reason to pin: it removes an entire class of "which node has which version" questions.

"Does pulling by digest protect you from a compromised registry?"

It protects you from a registry serving different bytes under the same name, because the client verifies the manifest and every blob against the digest and refuses anything that does not match.

It does not protect you from being handed the wrong digest in the first place: if the attacker can change the deployment manifest or the promotion pipeline, they can point it at their own image, which will verify perfectly. That is what signatures are for.

cosign sign creates a signature over the digest with a key or with a keyless identity from the CI job's OIDC token, stored in the registry as a referrer; an admission controller such as Kyverno or the Sigstore policy controller verifies that the digest the pod asks for carries a signature from the expected identity.

Digest pinning gives integrity of bytes; signing gives provenance of the pointer; you need both, and both are cheap as of Aug 2026.

Q20 · Scenario. "The same tag payments:2.3 was deployed yesterday and today. Yesterday's pods are fine; today's throw a NoSuchMethodError on startup. Nobody changed the deployment manifest. Find it."

Reveal answer

Strong answer I would prove the images differ before touching any code:

  1. Get the digests actually running. On a healthy node, docker inspect --format '{{index .RepoDigests 0}}' payments:2.3; on a broken node, the same. In Kubernetes, kubectl get pod -o jsonpath='{.status.containerStatuses[0].imageID}' for one old pod and one new pod. If the two sha256 values differ, the tag moved and the manifest is innocent.
  2. Check the registry's audit log or docker manifest inspect payments:2.3 for the push time. Typical finding: a CI job re-ran on the release branch after a dependency bump, or a developer pushed a local build to the same tag to "hotfix" something.
  3. Ranked causes: a mutable tag re-pushed with a different dependency set, which explains the missing method; the same tag built on a different builder that resolved a floating Maven version range; or, less often, a base image tag that moved and shipped a different JRE.
  4. Fix: redeploy by yesterday's digest, payments@sha256:<old>, which restores service in one rollout. Then compare the two images with docker history and a jar-level diff to find the changed dependency.
  5. Prevention: turn on tag immutability in the registry so the second push would have failed; reference images by digest in deployment manifests, with a tool like Renovate or a promotion pipeline updating the digest deliberately; and record the digest in the build log and in a startup log line so on-call can see it without SSH.

Land it "Nobody changed the manifest" is exactly the sentence a mutable tag lets you say while the bytes underneath it change — the fix is to make the manifest say the bytes, not the name.

Likely follow-ups
"The digests are identical on the healthy and broken nodes. Now what?"

Then the image is innocent and the difference is in the environment around it, so I switch to comparing everything except the image.

Base image of the node: a rolled node image may carry a different kernel or a different containerd; uname -r and docker version on both.

Mounted configuration: a ConfigMap or a bind-mounted directory that changed; kubectl get configmap -o yaml with the resource version, or a checksum of the mounted files inside each pod.

Environment variables and secrets injected at start: kubectl exec broken -- env | sort diffed against the healthy pod.

Sidecars or init containers pulled by their own moving tags: a Java agent injected by an init container is a classic NoSuchMethodError source, because it puts a different library version on the classpath.

And the JVM itself, if it comes from a mounted volume or an agent jar. In my experience, once the image digest matches, the culprit is a sidecar or an agent nine times in ten.

"How would you diff two images to find the changed dependency in minutes rather than hours?"

Layer first, then files, then jars. docker image inspect --format '{{.RootFS.Layers}}' on both digests tells me which layer index diverged; with a layered Spring Boot image that is usually the dependencies layer, which already narrows it to third-party jars.

Then container-diff diff --type=file old new, or manually docker create a container from each and docker export | tar -t | sort them, and diff the lists; jar files carry their version in the name, so the diff prints something like jackson-databind-2.17.1.jar against 2.18.0.

If the jar names are identical and only content changed, I compare SHA-256 sums of the jars and unzip the differing one to read META-INF/MANIFEST.MF. For non-Java images, syft produces an SBOM for each and diff of the two SBOMs names the changed package.

The whole exercise is under ten minutes and gives a concrete answer to put in the incident record.

"Turning on tag immutability would have broken the CI job that re-pushed. Is that acceptable?"

Yes, and it is the point: the failure moves from production at runtime to CI at build time, where it costs a red pipeline instead of an outage. The re-push was itself the bug.

The only legitimate reason a job pushes to an existing version tag is that the pipeline was re-run for the same commit, and the correct behaviour there is to skip the push when the tag exists with the same digest — a crane digest registry/app:2.3 check before pushing — and fail loudly when it exists with a different digest, because that means the build is not reproducible or the commit was rewritten.

Floating tags such as main or staging stay mutable and can be re-pointed freely. I would enable immutability on the pattern for version tags, fix the two or three jobs that break, and treat each break as a found bug.

"Nobody has the digest from yesterday. How do you recover it?"

Several places usually still have it.

A node that ran the old pods still has the image locally, and docker image inspect --format '{{.RepoDigests}}' lists it, as long as nothing pruned it; on Kubernetes, the pod's status.containerStatuses[].imageID from any pod that is still running or was logged by the audit trail.

The registry's history: Harbor and ECR keep untagged manifests until garbage collection runs, and crane ls --full-ref or the registry's API can list manifests by push time, so yesterday's push is retrievable by digest even though the tag has moved.

The CI logs of yesterday's build, if the pipeline printed the digest, which is why I always have it print one. The deployment tool's history, such as Argo CD's revision list. And the central log store, if the service logs its own image digest at startup.

The failure to find it anywhere is the finding to write up: the digest must be recorded in the deploy record from now on.

Q21. "What actually happens on the wire during docker pull? Describe the registry API calls and what the client verifies."

Reveal answer

Strong answer A pull is a small sequence of HTTPS calls against the OCI Distribution API, which most people still call the Docker Registry v2 API. First the client calls GET /v2/; the registry answers 401 with a WWW-Authenticate header naming a token service, and the client fetches a short-lived bearer token scoped to repository:library/nginx:pull.

Next it calls GET /v2/library/nginx/manifests/latest with an Accept header listing the manifest media types it understands. If the response is an image index, the client picks the entry matching its platform, say linux/amd64, and fetches that manifest by digest.

Then it reads the manifest's layer list and compares each blob digest against what it already has locally; layers already present are skipped entirely, which is why a second service on the same base pulls only its unique layers.

For each missing blob it calls GET /v2/library/nginx/blobs/sha256:..., and most registries answer with a 307 redirect to object storage such as S3, so the bytes never pass through the registry server. Docker fetches up to three layers in parallel, controlled by max-concurrent-downloads in daemon.json.

As each layer arrives it verifies the SHA-256 of the compressed bytes against the manifest, decompresses, verifies the diff ID against the config, and hands the tar to the snapshotter to unpack.

Only after every layer is unpacked does the image become visible in docker image ls. Everything is content-addressed, so a corrupted or tampered blob fails verification and the pull errors out.

Land it A pull is a manifest fetch followed by a diff against local layers — and the redirect to object storage is why a registry can serve a 500-node fleet without its own server melting.

Likely follow-ups
"A pull hangs at 'Waiting' on one layer for minutes and then fails. What is happening and how do you debug it?"

"Waiting" means the layer is queued behind the concurrent-download slots, default three, and the slots are held by downloads that are stalled.

The usual causes are the redirect target, not the registry: the manifest fetch succeeded against the registry host, but the blob GET was redirected to object storage such as S3 or a CDN that the node cannot reach through its egress rules, or that is slow from that region.

I would test each hop separately: curl -sI https://registry/v2/ for the registry, then take a blob digest from docker manifest inspect, request it with curl -sIL -H "Authorization: Bearer ..." and watch where the 307 sends me, then time a download of that URL from the node.

Daemon logs with journalctl -u docker show retries and the exact URL. A proxy set in HTTP_PROXY on the daemon's systemd unit but missing the storage domain from NO_PROXY is the most common corporate cause. Raising max-download-attempts only hides it.

"What does the client do differently when the registry requires authentication with a private image?"

The first GET /v2/ or the manifest request returns 401 with a header like WWW-Authenticate: Bearer realm="https://auth.example/token",service="registry",scope="repository:team/app:pull".

The client then calls that realm with the credentials it has for the registry host, taken from ~/.docker/config.json — either a stored base64 username and password or a credential helper such as docker-credential-ecr-login that fetches a short-lived token.

The realm returns a bearer token, usually a JWT valid for a few minutes and scoped to exactly that repository and action, and every subsequent manifest and blob request carries it.

Blob redirects to object storage use a pre-signed URL instead, so the token is never sent to S3. In Kubernetes the same flow uses an imagePullSecrets entry of type kubernetes.io/dockerconfigjson or, on cloud nodes, a credential provider plugin on the kubelet.

A 401 after a previously working pull is almost always an expired stored token, which is why long-lived CI runners need the helper rather than a saved login.

"Does the daemon verify anything about who published the image, or only that the bytes match?"

Only that the bytes match the digests. The pull path verifies the blob digests against the manifest and the diff IDs against the config, so a corrupted or substituted layer fails, but nothing checks who created the manifest.

Docker Content Trust, enabled by DOCKER_CONTENT_TRUST=1, adds Notary v1 signatures on tags, but it is rarely deployed and the ecosystem moved on.

As of Aug 2026 the practical answer is Sigstore: cosign sign in CI and verification either at admission in Kubernetes with a policy controller, or, for plain Docker hosts, a wrapper that runs cosign verify --certificate-identity ... --certificate-oidc-issuer ... before docker run.

containerd can also be configured with an image-verifier plugin that runs a binary on every pull and rejects on non-zero exit. So the daemon itself remains a bytes-match checker, and provenance is enforced one layer above it.

"Why is a pull of an image that is already present still not instant?"

Because the client cannot know it is present without asking. It must fetch the manifest — one token request and one or two HTTPS round trips — and compare the layer digests with the local store.

For a tag, that also confirms the tag has not moved.

On a fast link that is 200 to 500 milliseconds; through a slow corporate proxy or a distant registry it can be several seconds, which is what people notice when docker compose up with pull_policy: always stalls on a dozen unchanged images.

There is a second, smaller cost when the containerd image store is in use: it also re-reads the index to see if a new platform variant appeared.

Kubernetes avoids the cost with imagePullPolicy: IfNotPresent for tagged images and, for digests, skips the registry entirely if the digest is local. The daemon-side setting max-concurrent-downloads does not affect this metadata phase.

Q22 · Scenario. "Every deploy of a 1.1 GB image pulls the full image on every node, taking about four minutes, even though only the application code changed. Diagnose and shorten it."

Reveal answer

The real test Whether you check layer reuse before blaming the network.

Strong answer I would measure what is really being transferred:

  1. Evidence: run docker pull on a node that already has the previous version and watch the per-layer output. Lines that say "Already exists" are reused; lines that download are new. If almost every layer downloads, the layers are not being shared between versions. Confirm with docker image inspect --format '{{.RootFS.Layers}}' on the old and new image; differing diff IDs low in the list mean the change happened early in the Dockerfile.
  2. Ranked causes: the Dockerfile copies the whole source tree before installing dependencies, so the dependency layer changes on every commit; a COPY . . includes a file that changes every build, such as a generated version file or a build timestamp, invalidating everything after it; the jar is one fat 900 MB layer instead of Spring Boot's split layers; or the nodes are freshly provisioned autoscaled instances with nothing local, so "already exists" was never possible.
  3. Fix for ordering: copy pom.xml and resolve dependencies first, copy source last, and use the layered-jar extraction so third-party jars sit in their own stable layer. A code-only change then pulls about 20 MB.
  4. Fix for fresh nodes: a regional pull-through cache, or pre-pulling the image into the node image, or Kubernetes imagePullPolicy: IfNotPresent with a DaemonSet that warms the image.
  5. Fix for bandwidth: enable zstd compression with --output type=image,compression=zstd, which decompresses several times faster than gzip, and raise max-concurrent-downloads to 6 to 10.
  6. Prevention: a CI step that prints the unique bytes of each new image versus the previous one and fails if it exceeds, say, 100 MB for a normal commit.

Land it Pull time is the size of the layers that changed, not the size of the image — reorder the Dockerfile so a code change is a small top layer and the four minutes become twenty seconds.

Likely follow-ups
"You reordered the Dockerfile and a code-only change still downloads 600 MB on the nodes. What next?"

Then the layers really are new, and I want to know which. I would pull the previous and current tags on one node and diff docker image inspect --format '{{json .RootFS.Layers}}'; the position of the first differing diff ID tells me which instruction changed.

If it is the base layers, the runtime FROM resolved to a different digest between builds — a moving tag — and pinning by digest fixes it.

If it is the dependency layer, something upstream of it changed on every build: a file included in the COPY that carries a timestamp or build number, or a build argument used before that step.

If every layer differs, the image was built on a different builder with different compression, so the blob digests differ even though content matches; the node compares blob digests, so it downloads everything. One consistent builder, or at least one consistent compression setting, fixes that.

Finally, if the nodes are fresh autoscaled instances, "already exists" was never possible and the fix is pre-warming.

"What does zstd actually buy over gzip during a pull, and is there any downside?"

Decompression speed, mostly.

Pull time on a fast network is often bounded by the CPU decompressing and the disk unpacking rather than by bytes on the wire, and zstd decompresses roughly three to five times faster than gzip at similar ratios, so a 1 GB image unpacks in a third of the time.

Compressed sizes are similar or slightly smaller. The downsides are compatibility and sharing. Zstd layers need Docker 23 or later and containerd 1.6 or later; older daemons fail the pull with an unsupported media type, and some registries and scanners lagged for a while.

And because the blob digest changes, a zstd push shares nothing in the registry with the gzip version of the same layers, so switching a fleet mid-flight doubles registry storage until the old images are cleaned.

You enable it with --output type=image,compression=zstd,force-compression=true on buildx build, and you can verify the media type in docker manifest inspect.

"How would you pre-warm images onto autoscaled nodes without slowing the scale-up itself?"

Three options with different costs.

Bake the base layers into the node image: a nightly job builds the AMI with the ten most common base images already in the containerd store, so a fresh node only pulls the small application layers; this is cheap because base layers change weekly, not thirty times a day.

Run a warming DaemonSet that pulls the current application images on every node as they join, ahead of the scheduler placing pods; the node is briefly busy but the first real pod starts fast.

Or use peer-to-peer distribution so the new node fetches from neighbours on the local network rather than the regional registry. I would combine the first and third: bake bases, use Spegel or Dragonfly for application layers.

What I would not do is make the autoscaler wait for warming to finish, because that adds the pull time to every scale-up decision, which is the delay we were trying to remove.

"Give me the numbers: what should a pull cost after the fix, and how would you alert on regression?"

For a well-layered JVM service on a node that already has the previous version: one application layer of 0.5 to 5 MB and a manifest, so under two seconds including token and metadata round trips.

For a fresh node: the base and dependency layers, 150 to 250 MB, at about 10 to 20 seconds from a regional registry. Anything over 100 MB for a code-only deploy is a regression.

I would make the build pipeline compute unique bytes by comparing the new manifest's layer list with the previous tag's and summing the sizes of layers not present before; crane manifest plus jq does it in a few lines.

Fail the pipeline above 100 MB unless a label says it is an intended base bump. At runtime, the kubelet exposes image pull duration metrics, and containerd exposes per-pull bytes; a p95 pull time alert at 30 seconds catches the fleet-level effect.

Q23 · Design. "Design image distribution for a 500-node fleet across three regions that deploys 30 times a day. Docker Hub rate limits and cross-region egress bills are both hurting."

Reveal answer

Strong answer Assumptions: images are 200 MB to 1 GB, most layers are shared between versions, and a deploy must reach all nodes within a few minutes.

Requirements: no dependence on Docker Hub at deploy time, egress within region only, and a pull that hits the origin registry once per region rather than 500 times. The design has three tiers.

First, an origin registry per region — Harbor, or the cloud provider's registry with cross-region replication turned on — where CI pushes once and replication fans out.

Second, a pull-through cache in each region: a registry started with proxy.remoteurl pointing at Docker Hub and the origin, so public base images are fetched once per region and served locally thereafter.

Nodes are configured with "registry-mirrors": ["https://mirror.eu.internal"] in /etc/docker/daemon.json, which Docker consults before Docker Hub for any unqualified image name.

Third, for the 500-node fan-out, peer-to-peer distribution with Dragonfly or Spegel: each node's containerd serves the layers it already has to its neighbours, so the origin is read a handful of times and the rest of the fleet pulls over the local network.

Trade-offs: a pull-through cache only mirrors public pulls, not pushes, so private images must be pushed to the origin and replicated; caches must be sized for the working set, roughly 100 GB per region, with a garbage-collection schedule; and peer-to-peer adds a component per node that must be monitored.

The mirror is a single point of failure per region, so I would run two behind a load balancer.

What I would not do: bake images into the node AMI as the primary mechanism, because 30 deploys a day would mean 30 node image rebuilds; and I would not point production at Docker Hub directly under any circumstances, because a 100-pull-per-6-hour anonymous limit ends a deploy mid-rollout.

Land it The rule is one origin fetch per region and zero at deploy time — a mirror handles the first, peer-to-peer or pre-warming handles the second, and Docker Hub becomes something only the build pipeline ever talks to.

Likely follow-ups
"The requirement changes: one of the three regions is air-gapped with a nightly file transfer only. What changes?"

The pull-through cache is useless there, because it needs a live upstream. The region gets a full origin registry — Harbor or the distribution registry with local storage — and images arrive as files.

The build pipeline exports every promoted image as an OCI layout, crane pull --format=oci registry/app@sha256:... app.tar or skopeo copy docker://... oci-archive:app.tar, together with its signatures and SBOM attestations, into the nightly bundle.

On the far side a job runs skopeo copy oci-archive:app.tar docker://air-gapped-registry/app, which preserves the digest exactly because the layout is content-addressed, and re-verifies the signature before publishing.

Deploys in that region are then limited to the nightly cadence, which the business has to accept, or the transfer runs more often.

Base images and all their dependencies must be bundled too, and I would add a manifest of expected digests so the import can prove completeness rather than discovering a missing layer at deploy time.

"You have two days to fix the Docker Hub rate limit before the next release. What is the minimum?"

Two changes and nothing else.

First, stand up one pull-through cache per region with the official registry image, registry:2 configured with proxy.remoteurl: https://registry-1.docker.io and an authenticated Docker Hub account so the cache itself has the higher limit, backed by cloud object storage so it needs no disk management.

Second, point every node at it: "registry-mirrors": ["https://mirror.region.internal"] in /etc/docker/daemon.json or the equivalent hosts.toml for containerd, rolled out by the configuration tool, followed by a daemon reload.

That removes Docker Hub from the deploy path in a day; the first pull per region fetches from Hub, every other node hits the cache.

I would defer replication of private images, peer-to-peer, and high availability for the cache, and accept the single mirror as a risk for one release. The verification is docker info | grep -A2 Mirrors on a node and the cache's request log showing hits.

"How does peer-to-peer distribution like Spegel actually work, and what happens when it fails?"

Spegel runs as a DaemonSet that speaks the registry API and serves the layers that node's containerd already has.

It advertises which digests it holds over a peer-to-peer distributed hash table, and containerd on every node is configured through hosts.toml to try the local Spegel endpoint first as a mirror, then the real registry.

A pull for a digest another node already has is served over the cluster network at line rate, so the origin sees a handful of requests per region and the rest is intra-cluster traffic.

Because it is a mirror entry, failure is graceful: if the local Spegel is down or does not have the digest, containerd falls through to the origin after a short timeout, so the worst case is the original behaviour plus a few hundred milliseconds.

The genuine risks are that it only works for pulls by digest or resolved tags, and that a misconfigured mirror timeout can add seconds to every pull, so I would monitor the fallback rate.

"What would 5,000 nodes and 300 deploys a day break in this design?"

Two things become the bottleneck: the mirror and the registry's metadata path.

A single pull-through cache serving 5,000 nodes at 300 deploys a day handles hundreds of thousands of blob requests daily plus a burst of a few thousand simultaneous manifest requests per deploy; a single registry process on object storage saturates on the manifest and token endpoints, not on bytes.

So the mirror becomes a horizontally scaled pool behind a load balancer with shared object storage, and peer-to-peer distribution becomes mandatory rather than optional so blob traffic never reaches the mirror at all. Garbage collection of the cache grows into a real job.

The deploy tool also needs to stagger rollouts, because a simultaneous pull on 5,000 nodes is a thundering herd even against peers.

And observability: I would want per-region pull latency and origin request rate as first-class dashboards, because at that scale a registry incident is a deploy freeze.

Q24. "What is a manifest list, and what happens when an arm64 laptop and an amd64 server both run docker pull myapp:1.0?"

Reveal answer

Strong answer A manifest list, called an image index in the OCI specification, is a JSON document that a tag can point to instead of a single manifest.

It contains an array of entries, each with a manifest digest and a platform object giving os, architecture, and optionally variant, such as linux/amd64, linux/arm64, or linux/arm/v7.

When a client pulls the tag, it fetches the index, chooses the entry that matches its own operating system and CPU architecture, and then pulls that manifest and its layers.

The arm64 laptop and the amd64 server therefore fetch completely different sets of layers under the same name, and neither knows or cares that the other exists. The image ID they end up with also differs, because the config blobs differ.

You can see the index with docker manifest inspect myapp:1.0, and docker buildx imagetools inspect myapp:1.0 prints each platform with its digest. Two details matter in production.

First, the tag's digest is the digest of the index, so pinning by that digest still lets each node select its platform, which is what you want.

Second, if the index lacks an entry for the requesting platform, Docker fails with "no matching manifest", unless you pass --platform linux/amd64 explicitly, in which case an arm64 host will pull the amd64 image and run it under QEMU emulation, slowly.

Official images on Docker Hub have been multi-arch for years, which is why docker run nginx just works on a Mac with an M-series chip.

Land it One tag, one index digest, one manifest per CPU family — the index is what lets a single image name serve a mixed fleet without anyone choosing an architecture by hand.

Likely follow-ups
"A developer on a Mac pulled the image with --platform linux/amd64 and it 'works', but slowly. What is happening underneath?"

Docker Desktop's VM has binfmt_misc registered with QEMU user-mode emulators, so when the kernel is asked to execute an amd64 binary on an arm64 host, it hands the file to qemu-x86_64, which translates instructions at runtime.

A JVM under that translation runs at roughly a fifth to a tenth of native speed and, worse, the JIT compiler generates amd64 code that is then itself emulated.

Since 2023 Docker Desktop on Apple silicon offers Rosetta as the emulator, which is several times faster than QEMU but still not native.

So the image works, at a cost, and some things do not work at all: anything using io_uring, some seccomp behaviour, and multi-threaded native code occasionally crashes under QEMU. The right answer is a multi-arch image so the Mac gets a native arm64 variant; the emulation is a stopgap for one-off testing.

docker inspect --format '{{.Architecture}}' on the image tells you which variant you actually have.

"What does the digest in a deployment manifest point to for a multi-arch image, and is that safe?"

It points to the index, and that is exactly what you want. The index digest identifies the JSON list of per-platform manifests, and each of those is itself identified by digest inside the index, so pinning the index digest pins every platform variant transitively.

An amd64 node resolves the index, picks its entry, and pulls that manifest; an arm64 node picks a different entry from the same pinned index.

If someone pushed a new arm64 variant, the index would change and so would its digest, so the pin would break rather than silently drift.

The only subtlety is tooling that reports "the digest": kubectl shows the index digest in image and the platform manifest digest in imageID, and they are legitimately different. Signing works the same way; sign the index digest and verification covers all platforms.

"How would you add a platform to an existing tag without rebuilding the one that already exists?"

Build only the new variant to its own temporary tag, then write a new index that references both. docker buildx build --platform linux/arm64 -t registry/app:1.0-arm64 --push . builds the missing one.

Then docker buildx imagetools create -t registry/app:1.0 registry/app:1.0@sha256:<existing-amd64-manifest-digest> registry/app:1.0-arm64 creates and pushes an index containing both manifests; no layer bytes move, only a small JSON document. docker buildx imagetools inspect registry/app:1.0 confirms two platforms.

The caveats are that the tag's index digest changes, so anything pinned to the old digest keeps working but does not gain the new platform, and that with immutable tags the tag itself may not be re-pointable, in which case the combined index goes to a new tag. crane index append does the same job with a single command.

"The variant field: when does linux/arm/v7 versus v8 matter, and how does the client pick?"

The variant refines the architecture for CPU families that are not binary-compatible. For 32-bit ARM, v6 and v7 distinguish instruction set levels, and a Raspberry Pi Zero cannot run v7 code; for 64-bit ARM, arm64 is implicitly v8 and the field is usually omitted.

The client determines its own platform from uname and the CPU features, then matches on os, architecture, and variant in that order; if the index has an arm64 entry with variant v8 and the client reports no variant, current containerd and Docker treat them as compatible.

It gets strict for 32-bit ARM, where an image published only as arm/v7 fails on a v6 device with "no matching manifest". Windows images add os.version matching, since a Windows container must match the host's build number under process isolation. Most services only ever need linux/amd64 and linux/arm64.

Q25 · Scenario. "A developer builds an image on an M-series Mac, pushes it, and the x86 production nodes crash on start with exec /usr/bin/java: exec format error. Explain, fix today, and fix forever."

Reveal answer

Strong answer I would confirm the architecture mismatch and then fix the pipeline:

  1. Evidence: docker image inspect --format '{{.Os}}/{{.Architecture}}' myapp:dev on a production node prints linux/arm64. docker manifest inspect myapp:dev shows a single manifest with no amd64 entry. The error text itself is the kernel refusing to execute a binary compiled for a different CPU.
  2. Cause: docker build defaults to the builder's native platform. On Apple Silicon that is arm64, so every binary in the image, including the JVM from the base image, is arm64. The push succeeded because registries do not care what is inside.
  3. Fix today: rebuild from the same commit with docker buildx build --platform linux/amd64 -t myapp:dev --push .. On the Mac this runs under QEMU emulation, which is slow for a Maven build but works for a one-off. Alternatively trigger CI, which runs on amd64 runners.
  4. Fix forever: make CI the only place that pushes production tags, and have CI build a multi-arch index with --platform linux/amd64,linux/arm64 so Macs and servers both get native images. Set DOCKER_DEFAULT_PLATFORM=linux/amd64 in developers' shells if they must push to shared environments.
  5. Prevention: an admission check in the deployment pipeline that inspects the image index and rejects anything without a linux/amd64 entry, and a registry policy that only the CI service account can push to release repositories.

Land it "Exec format error" is always the wrong CPU architecture, and the durable fix is not a flag on a laptop — it is a pipeline where laptops never produce the images production runs.

Likely follow-ups
"You rebuilt with --platform linux/amd64 on the Mac and now the Maven step fails with a QEMU segfault. What next?"

Stop emulating the compile. The rebuild forced every stage, including the Maven build, to run as amd64 under QEMU, and the JVM under QEMU is exactly the kind of multi-threaded native code that crashes there.

The fix is to compile natively and only package for the target: mark the build stage FROM --platform=$BUILDPLATFORM maven:3.9-eclipse-temurin-21 AS build, so it runs as arm64 on the Mac, and leave the runtime stage's platform to the target so it pulls the amd64 JRE. Java bytecode is portable, so the jar produced on arm64 runs unchanged on amd64.

Rerun the same docker buildx build --platform linux/amd64 and the only emulated steps are the trivial COPY and user creation in the runtime stage.

If even that fails, the alternative for today is to trigger the CI pipeline, which has amd64 runners, and push from there — which is the "fix forever" anyway.

"What is the smallest control that would have caught this before production, and where does it live?"

A one-line check in the deploy pipeline that inspects the image's index before rollout. docker buildx imagetools inspect --format '{{json .Manifest}}' registry/app:tag | jq -e '.manifests[]? | select(.platform.architecture=="amd64") // empty', or the simpler crane manifest plus jq, and fail if no amd64 entry exists; for a single-platform manifest, check the config's architecture field.

It runs in seconds, needs no pull, and would have failed with a clear message instead of the fleet crashing. The second control is at the registry: restrict push on release repositories to the CI identity, so a laptop cannot push a production tag at all.

A Kubernetes admission policy could also check the architecture, but the pipeline is earlier and cheaper. I would also add a node selector or the scheduler's built-in kubernetes.io/arch label so a pod is only placed where its image can run.

"How does exec format error differ from 'no matching manifest', and which is worse?"

"No matching manifest for linux/amd64" happens at pull time: the tag points to an index that has no entry for the node's platform, so the pull fails and the container never starts.

It is the better failure because it is loud, immediate, and before any rollout progresses.

"exec format error" happens at run time: the image pulled fine because it is a single-platform manifest whose config says arm64, and Docker does not refuse to pull a mismatched single manifest, it just warns; the kernel then refuses to execute the binary.

That one is worse because the deployment proceeds, the old pods are terminated, and the new ones crash-loop.

The design lesson is to always publish an index even for one platform — buildx does this when --provenance is on — and to keep the pipeline check from the previous answer so mismatches are caught before pods are replaced.

"Should developers on Macs build amd64 images by default with DOCKER_DEFAULT_PLATFORM? What does that cost them?"

Only for images they push to shared environments, and I would rather solve it by not letting laptops push at all.

Setting DOCKER_DEFAULT_PLATFORM=linux/amd64 globally makes every local docker run and docker build emulate, which turns a two-minute Maven build into ten and makes local databases and message brokers run under QEMU as well, so developers quietly unset it and the problem returns.

The cost is a slower inner loop for everyone to prevent a mistake only the push path can make.

Better: local development runs native arm64 images, which official images support; the shared Makefile target that pushes to a shared registry passes --platform linux/amd64,linux/arm64 explicitly; and the registry rejects pushes to release repositories from human credentials.

Then the platform choice lives in the one place it matters and laptops stay fast.

Q26 · Design. "Design a multi-architecture build for amd64 and arm64 that runs in CI, is fast, and produces a single tag both fleets can pull."

Reveal answer

Strong answer Assumptions: a Java service with a Maven build, CI on GitHub Actions or similar with amd64 runners and optionally arm64 runners, and the output must be one tag whose index has both platforms.

Requirements: no QEMU emulation of the compile step, because emulating a Maven build is five to ten times slower and occasionally flaky, and the two platform manifests must come from the same source commit. The design: compile once, package twice.

Stage one of the Dockerfile is marked FROM --platform=$BUILDPLATFORM maven:3.9-eclipse-temurin-21 AS build, so the JVM bytecode is produced natively on the runner's architecture — Java bytecode is portable, so this is safe.

Stage two is FROM eclipse-temurin:21-jre AS runtime with no platform override, so BuildKit resolves the arm64 JRE for the arm64 target and the amd64 JRE for the amd64 target, and copies the same jar into both.

The command is a single docker buildx build --platform linux/amd64,linux/arm64 --push -t registry/app:1.4.2 --cache-to type=registry,mode=max --cache-from type=registry ., which builds both variants and pushes an index.

If the CI provider offers native arm64 runners, I would instead run the build on each and combine the results with docker buildx imagetools create -t registry/app:1.4.2 registry/app:1.4.2-amd64 registry/app:1.4.2-arm64, which writes only an index and moves no bytes.

For services with native code such as a JNI library, the compile stage cannot be shared and native runners become mandatory.

Trade-offs: the emulated route needs docker run --privileged tonistiigi/binfmt --install all on the runner and doubles the runtime-stage time; the native route needs two runners and an extra combine step.

What I would not do: build separate tags per architecture and let deployment manifests pick, because that pushes an infrastructure detail into every service's config and breaks the moment a node pool changes CPU.

Land it Compile on the build platform, package for the target platform, publish one index — that separation is the whole trick, and the $BUILDPLATFORM line is where it lives.

Likely follow-ups
"The requirement changes: the service has a JNI library compiled from C. Redesign."

The compile-once trick no longer applies to the native part, so the build splits. The Java stage stays on $BUILDPLATFORM because bytecode is portable.

The native library needs one compile per target architecture, which means either a real cross-compiler in the build stage — gcc-aarch64-linux-gnu on an amd64 runner, invoked with --target from the TARGETARCH build argument BuildKit provides — or native runners per architecture.

Cross-compiling C is well trodden and fast; cross-compiling something with a complex toolchain such as Rust or CMake with many dependencies is where I would switch to native arm64 runners and combine the per-arch images with imagetools create.

Either way the Dockerfile gains a stage that produces libnative-${TARGETARCH}.so and the runtime stage copies the right one.

Testing changes too: the JNI code must be tested on each architecture, so the CI matrix runs the integration tests natively on both, which is the real cost of native code.

"You have one afternoon and only amd64 runners. What ships?"

A single command and one Dockerfile change.

Add --platform=$BUILDPLATFORM to the build stage so the Maven compile runs natively, install binfmt on the runner once with docker run --privileged --rm tonistiigi/binfmt --install arm64, create a buildx builder with docker buildx create --use, and run docker buildx build --platform linux/amd64,linux/arm64 --push -t registry/app:1.4.2 ..

The arm64 runtime stage is emulated, but it only copies files and creates a user, so it adds seconds, not minutes. I would skip the registry cache export for today, skip native runners, and skip provenance attestations.

What I would verify before leaving is docker buildx imagetools inspect registry/app:1.4.2 listing both platforms, and one smoke start of the arm64 variant on a Mac. The native-runner design is a later improvement that removes the binfmt dependency and speeds up services with native code.

"What do $BUILDPLATFORM and $TARGETPLATFORM resolve to, and where do people misuse them?"

BuildKit predefines them per stage. BUILDPLATFORM is where the build is executing, for example linux/amd64 on a CI runner; TARGETPLATFORM is the platform of the image being produced, and it takes each value from the --platform list in turn, with TARGETOS, TARGETARCH, and TARGETVARIANT split out.

They are only available after you declare them with ARG TARGETARCH inside a stage, which is the first misuse: people reference them without the ARG and get an empty string.

The second misuse is putting --platform=$BUILDPLATFORM on the runtime stage, which produces a build-platform image labelled as the target and is precisely the Mac-to-production bug.

The third is using uname -m in a RUN to decide which binary to download, which reports the emulated or native CPU rather than the target; TARGETARCH is the correct source. A tidy pattern is a small case statement mapping amd64 to x86_64 for download URLs.

"How do you keep the two platform variants provably built from the same commit?"

Through provenance attestations. With --provenance=true, BuildKit attaches a SLSA provenance document to each platform manifest in the index, recording the Dockerfile digest, the Git commit from the build context if it was a Git URL or from BUILDKIT_CONTEXT_KEEP_GIT_DIR, the build arguments, and the base image digests.

Since the two variants are produced in one buildx invocation from one context, both attestations carry the same source revision, and a policy engine can verify that before deploying.

When the variants are built on separate native runners, each build's provenance records its own commit, and the imagetools create step runs in a job that checks the two commits match before writing the index. Label the images with org.opencontainers.image.revision as a human-readable backup.

Then a reviewer can run docker buildx imagetools inspect --format '{{json .Provenance}}' and see both variants pointing at one SHA.

Q27 · Design. "Design an image promotion scheme across dev, staging, and production so that what was tested is provably what runs, without rebuilding at any stage."

Reveal answer

The real test Whether "build once" is a slogan or a mechanism in your answer — the mechanism is a digest that never changes.

Strong answer Assumptions: one CI pipeline, one registry with several repositories, and three environments with progressively stricter gates. Requirement: a byte-identical image moves through all three, and every environment can prove which digest it runs. The design has four parts.

First, build exactly once, on a commit to main, and push to registry/app with two tags: the git SHA and the semantic version. The pipeline records the resulting index digest as an output artifact.

Second, promotion is a tag operation, not a copy: docker buildx imagetools create -t registry/app:staging registry/app@sha256:<digest> writes a new tag pointing at the same manifest inside the registry, moving zero bytes.

Production promotion is the same command with the prod tag, gated on the staging test run having recorded that same digest. Third, deployment manifests reference the digest, never the environment tag; the environment tags exist for humans.

A GitOps repository holds image: registry/app@sha256:... per environment, and promotion is a pull request that changes that line, which gives an audit trail for free.

Fourth, attach evidence to the digest: a signature with cosign sign registry/app@sha256:... at build time, a vulnerability scan attestation, and a test-passed attestation from staging, stored in the registry as referrers. The production admission controller verifies the signature and the staging attestation before allowing the pod.

Trade-offs: environment-specific configuration must come from the outside, through environment variables or mounted config, never baked in, and that discipline takes work in older services; registries without immutable tags let someone re-point prod by hand, so tag immutability on the version tags is required.

What I would not do: rebuild per environment "with the right config", because a rebuild produces a new digest and the staging test result no longer applies to anything; and I would not use separate registries per environment unless a compliance boundary forces it, because then promotion becomes a copy that must itself be verified.

Land it Promotion means moving a pointer, not bytes — if your process ever creates a new digest between staging and production, whatever you tested is not what you shipped.

Likely follow-ups
"Compliance now requires a separate production registry in another account. How does promotion change?"

Promotion becomes a copy, and the copy must preserve the digest and carry the evidence with it.

skopeo copy --all docker://dev-registry/app@sha256:X docker://prod-registry/app:1.4.2 copies the index and every platform manifest and blob unchanged, so the digest in the destination equals X; I would have the pipeline assert that with crane digest on both sides.

Because signatures and attestations are separate artifacts, they must be copied too: cosign copy moves them, or oras cp --recursive for referrers.

The production admission policy then verifies the signature against the build identity, which still validates because the signature is over the digest, not the registry name.

The staging evidence becomes a record that "digest X passed staging" rather than "this tag in this registry", which is why every gate should key on the digest.

The cost is a copy of every promoted image's bytes and a second registry to operate, which is why I avoid it unless a boundary requires it.

"You have a week. Which parts do you build first and which do you defer?"

Days one and two: build once on merge to main, tag with the git SHA, record the digest as a pipeline output, and change every environment's deployment manifest to reference the image by digest.

That alone gives "what was tested is what runs", because a rebuild cannot sneak in. Day three: the promotion job that re-tags with imagetools create and opens the GitOps pull request per environment.

Day four: immutable version tags in the registry and a push policy limiting release repositories to the CI identity. Deferred: signing and admission verification, which need key or OIDC identity setup and a policy controller; SBOM and vulnerability attestations; and the staging-passed attestation.

Those add proof against a malicious insider, which is a real threat but a later one than the accidental rebuild the team is suffering from now. I would write down the deferred list with owners so it does not become permanent.

"How does environment-specific configuration get in if the image is identical everywhere?"

From outside the image, at start time, through three channels in order of preference.

Environment variables and mounted files, injected by the deployment manifest per environment — Spring Boot reads SPRING_PROFILES_ACTIVE=prod and any property as an environment variable, and a ConfigMap or a bind-mounted application-prod.yaml in the config directory covers the rest.

Secrets via a mounted tmpfs or a secrets manager sidecar, never as environment variables in the image. And a configuration service or feature-flag system for values that change without a deploy.

The discipline that has to be enforced is that the Dockerfile contains no ENV with an environment name and no COPY of an environment-specific file; a linter rule for ENV .*PROFILE catches most regressions.

The test that proves it is starting the same digest with the staging and production configuration in CI and checking both boot, which also documents the configuration contract.

"What stops a person with registry write access from re-pointing the prod tag by hand?"

Nothing about the tag itself, which is why the manifests never use it.

The deployment reads a digest from a Git repository whose merge requires review and whose history is the audit log; re-pointing the prod tag changes what docker pull app:prod gives a human, and nothing running.

For defence in depth, registry permissions split into push for CI identities and read for humans, immutability is enabled on version tags so even CI cannot rewrite them, and the registry's audit log ships to the central store so a manual tag write raises an alert.

Finally the admission controller verifies a signature made by the CI identity, so even a digest that someone edited into the GitOps repository must correspond to an image CI actually built; a hand-built image would fail verification.

That combination means the only path to production is a reviewed commit pointing at a CI-signed digest.

Drill · Engine architecture, runc, exec & alternatives

This last group tests whether you can draw the CLI-to-runc chain, explain what docker exec does at the syscall level, argue why the socket is root, and place Podman, gVisor, and Docker Desktop correctly.

Q28. "Draw the Docker Engine architecture in words: CLI, dockerd, containerd, shim, runc. What does each one own, and why are there so many pieces?"

Reveal answer

Strong answer There are four processes in a line, each with one job. The docker CLI is a thin client; it turns your command into an HTTP request against the Docker Engine API and prints the response.

It owns nothing and can be on a different machine. dockerd, the daemon, is the high-level engine: it owns images, builds, networks, volumes, and the API. It does not run containers itself; it translates a run request into a gRPC call to containerd.

containerd is the core container runtime: it owns the container lifecycle, image pull and unpack through its snapshotters, and the low-level supervision. It is a graduated CNCF project and is what Kubernetes talks to directly, without dockerd at all.

For each container, containerd starts a containerd-shim, a small long-lived process that owns exactly one container's standard streams, its exit code, and its TTY. Finally the shim calls runc, which owns the actual creation: it reads the OCI config.json, creates the namespaces and cgroup, applies mounts and capability drops, and calls execve, then exits.

The reason for the layering is separation of concerns and, crucially, upgradability.

Because runc exits after starting the process and the shim is the container's real parent, you can stop and upgrade dockerd or even containerd without killing a single running container — the shims keep them alive and reconnect.

Kubernetes dropped the dockerd layer entirely in the "dockershim removal" of 1.24, talking straight to containerd, which is why "Docker" and "the thing Kubernetes runs" are no longer the same stack. As of Docker Engine 29 this is containerd 2.x, runc 1.3.x.

Land it The layers exist so the supervisor can be replaced without touching the supervised — the shim outliving runc is the design that makes a daemon restart survivable.

Likely follow-ups
"Show me how you would find the shim and the container process for a given container on the host."

Start with the host PID: docker inspect --format '{{.State.Pid}}' web, say 48213. Its parent is the shim: ps -o pid,ppid,cmd -p 48213 shows a PPID pointing at a process named containerd-shim-runc-v2 -namespace moby -id <container-id>.

That shim's own parent is PID 1, systemd, not containerd, because the shim is deliberately re-parented so containerd can restart without taking it down. pstree -p $(pgrep -f 'shim-runc-v2.*<id>') draws the whole subtree.

ls -l /proc/48213/ns shows the namespaces, and cat /proc/48213/cgroup shows the cgroup path the container lives in. From the containerd side, ctr -n moby containers ls and ctr -n moby tasks ls list what containerd knows, where moby is the namespace dockerd uses.

If a container is stuck, comparing what docker ps claims against ctr tasks ls and the actual process tree tells me which layer has lost track of reality.

"What happens when containerd restarts or crashes? Do containers survive that too?"

Yes, for the same reason: the shims are not children of containerd. When containerd comes back it scans its state directory, /run/containerd/io.containerd.runtime.v2.task/moby/, finds each shim's socket, reconnects, and rebuilds its view of running tasks. The container's process never noticed.

What is lost during the outage is the ability to start, stop, or exec anything, and events emitted while containerd was down are not replayed to dockerd. If a container exits during the gap the shim records the exit status and delivers it on reconnect.

The shim itself is the single point that must not die: killing a shim orphans the container's stdio and the container is killed on cleanup.

On the dockerd side, all of this only holds with live restore enabled; otherwise dockerd stops containers on its own shutdown, though a crash rather than a shutdown leaves them running and dockerd re-adopts them on start.

"Why did Kubernetes remove dockershim, and what did users actually have to change?"

Because dockerd was a redundant layer. The kubelet talks to a runtime through the CRI, a gRPC interface, and Docker never implemented it, so the kubelet carried an adapter called dockershim that translated CRI calls into Docker API calls, which then went to containerd anyway.

That meant two daemons, two sets of image stores, and features such as cgroup v2 and user namespaces that had to be plumbed through both. Removing it in 1.24 made containerd or CRI-O the direct runtime.

What users changed: node bootstrap to install containerd and point the kubelet at /run/containerd/containerd.sock; any tooling that ran docker ps on nodes, replaced with crictl; log paths, since containerd writes to /var/log/pods rather than /var/lib/docker/containers; and pods that mounted the Docker socket for builds, which now have no socket and moved to BuildKit or kaniko. Images did not change at all, because OCI images are runtime-agnostic.

"What is a shim v2 and why does the runtime name look like containerd-shim-runc-v2?"

The shim API is containerd's contract for a per-container supervisor, and version 2 made it pluggable.

Instead of containerd hard-coding runc, it looks for a binary named containerd-shim-<runtime>-<version> for whatever runtime the container requests, so io.containerd.runc.v2 resolves to containerd-shim-runc-v2, and Kata ships containerd-shim-kata-v2, gVisor ships containerd-shim-runsc-v1, and WebAssembly runtimes ship their own.

Each shim implements a small ttrpc interface — create, start, kill, delete, exec, stats — and is free to implement it however it likes; the Kata shim talks to a VM agent instead of forking runc.

That is the mechanism behind RuntimeClass in Kubernetes and the runtimes map in Docker's daemon.json. One shim can also manage several containers, which the runc v2 shim does for a Kubernetes pod, so that the pod's sandbox and its containers share one supervisor process.

Q29. "What is runc, what is the OCI runtime spec, and what exactly does runc read to start a container?"

Reveal answer

Strong answer The OCI runtime specification defines two things: the on-disk format of a container "bundle" and the operations a runtime must support to run it. A bundle is just a directory containing a config.json and a rootfs directory.

The config.json is the complete recipe: the process to run and its arguments and environment, the list of namespaces to create, the cgroup limits, the mounts, the Linux capabilities to keep, the seccomp profile, and the user mappings.

runc is the reference implementation of that spec — a small Go program, about the only job of which is to read a bundle and make the container real. It is what containerd invokes per container.

You can run it by hand to prove there is no magic: docker export a container's filesystem into rootfs, write a config.json with runc spec, then runc run mycontainer, and you have a container with no Docker daemon anywhere.

Because the interface is a file format and a binary name, runc is swappable. Point containerd at a different OCI-compatible runtime with --runtime or the runtimes map in daemon.json, and you can run runsc for gVisor or kata-runtime for Kata without changing anything above.

That is the whole value of the spec: dockerd and containerd never learn a new API to gain a stronger sandbox; they just call a different binary with the same config.json.

Land it runc turns a JSON file and a root directory into a running process and then gets out of the way — and because the input is a standard, swapping runc for gVisor is a config line, not a rewrite.

Likely follow-ups
"What does runc actually do between reading config.json and calling execve? Walk the steps."

runc forks a child, runc init, that does the dangerous work in two phases. The parent writes the cgroup files under the configured path and moves the child into the cgroup first, so resource limits apply from the start.

The child calls unshare or clone with the namespace flags from the config, which for a user namespace requires the parent to write uid_map and gid_map at that moment.

It then sets the hostname, performs every mount in the config in order — the rootfs, then /proc, /dev with device nodes, /sys, and the masked and read-only paths — and calls pivot_root into the new root.

Next it applies the seccomp filter, sets the capability bounding and ambient sets, sets no_new_privs, changes to the configured user and group, sets the working directory and environment, and finally execves the process arguments.

Before exec it waits on a pipe for the parent's go-ahead, which is where hooks such as CNI network setup run. strace -f runc run shows every step in order.

"Which sections of config.json would you edit to harden a container, and how do you get at them from Docker?"

The process.capabilities block, which has bounding, effective, permitted, inheritable, and ambient sets; linux.seccomp, the syscall filter; linux.maskedPaths and linux.readonlyPaths, which hide /proc/kcore and make /proc/sys read-only; root.readonly; process.noNewPrivileges; linux.resources for cgroup limits; and linux.namespaces, where adding a user namespace entry with uidMappings turns on remapping. Docker generates all of it from flags, so --cap-drop=ALL, --security-opt seccomp=profile.json, --read-only, --security-opt no-new-privileges, and --userns map directly. To see what Docker produced, run a container and read /run/containerd/io.containerd.runtime.v2.task/moby/<id>/config.json on the host; diffing that file between a default run and a hardened run is the fastest way to teach a team what each flag changes at the kernel level.

"What are crun and youki, and would you switch from runc?"

Both are alternative OCI runtimes with the same interface.

crun is written in C by the Podman team, starts containers a few tens of milliseconds faster than runc because it avoids the Go runtime's startup and its re-exec dance, uses less memory per container, and has been the default under Podman on Fedora and RHEL for years.

youki is a Rust implementation with similar goals and a smaller ecosystem. Since they read the same config.json, switching under Docker is a runtimes entry in daemon.json and --runtime=crun, or under containerd a runtime handler.

I would switch for workloads that create thousands of short-lived containers per minute, such as function platforms or CI, where the per-start cost adds up, and I would not bother for long-running services, where the start cost is noise.

As of Aug 2026 runc remains the reference and the most widely tested, which matters more for a production fleet than 30 milliseconds.

"Why is the runtime spec also the reason WebAssembly and gVisor plug in the same way?"

Because containerd only needs a shim that answers create, start, kill, and delete for a bundle; it does not care what the shim does with the bundle.

gVisor's runsc reads the same config.json and, instead of asking the kernel for namespaces, starts the Sentry user-space kernel and runs the process inside it. Kata's shim reads it and boots a microVM whose agent applies the mounts and limits.

A WebAssembly shim such as containerd-shim-wasmtime reads it, finds a .wasm file where the entrypoint would be, and runs it in a Wasm runtime with no Linux process at all.

The image format is unchanged, so registries, scanners, and deployment manifests do not know the difference; the only visible knob is the runtime class.

That is the design payoff of separating the image spec, the runtime spec, and the shim API: three stable contracts that let the execution engine be replaced beneath an unchanged platform.

Q30. "What does docker exec -it web bash actually do to get a shell inside an already-running container?"

Reveal answer

The real test Whether you name setns and understand exec creates a new process, it does not enter the existing one.

Strong answer docker exec starts a brand-new process and drops it into the same namespaces as the container's existing processes. The mechanism is the setns system call, which attaches the calling thread to an already-existing namespace given a file descriptor for it.

Every running process's namespaces are exposed as files under /proc/<pid>/ns/ — pid, net, mnt, and the rest. To exec into container web, the runtime opens those files for the container's PID 1 and calls setns on each, then sets the cgroup, then execves bash.

The new shell therefore sees the same processes, the same network interfaces, and the same filesystem as the app, because it now shares those namespaces, even though it is a different process that PID 1 did not start.

The command-line tool nsenter does exactly this from the host: nsenter -t <host-pid> -a /bin/sh enters all of that PID's namespaces and is how you debug a container whose image has no shell. Two consequences matter.

First, the exec'd process is not a child of the container's PID 1, so it is not covered by the app's signal handling or shutdown, and a long exec can outlive a docker stop briefly.

Second, exec adds a process to the container's cgroup, so a heavy command inside exec counts against the container's memory limit and can trigger its OOM killer.

Land it Exec does not enter the container so much as join its namespaces with a new process — setns is the call, and nsenter from the host is the same trick when the image has no shell to exec.

Likely follow-ups
"docker exec -u root works even though the image runs as UID 10001. Is that a hole?"

It is a design property rather than a hole, and it tells you where the boundary really is.

The exec'd process is created by runc with the user from the request, not inherited from PID 1, so anyone who can call the Docker API can run root inside any container regardless of the image's USER. The container's protections still apply: the root exec has the same dropped capabilities and seccomp profile as the container, so it is container-root, not host-root.

The hole, if any, is API access itself, which is already root-equivalent. In Kubernetes, kubectl exec cannot choose a user; it runs as the container's configured user, and a runAsNonRoot policy prevents the container starting as root at all.

If a team needs to forbid root exec on Docker hosts, the answer is an authorization plugin on the daemon or simply not granting API access, not a setting in the image.

"Exec into a container hangs or returns 'container not running' although docker ps shows it up. What do you check?"

First whether PID 1 is alive from the host's view: docker inspect --format '{{.State.Pid}}' then cat /proc/<pid>/status | grep State; a Z or D state explains everything.

A D state, uninterruptible sleep, usually means the process is stuck in a filesystem or NFS call and exec cannot join a namespace whose owner is blocked in the kernel.

Second, whether the container is out of PIDs: cat /sys/fs/cgroup/.../pids.current against pids.max, because exec needs to fork and a fork bomb or zombie pile blocks it with the resource-unavailable error.

Third, memory: exec adds a process to the cgroup, and if the container is at its limit the new shell is OOM-killed instantly, which looks like an immediate exit.

Fourth, the shim: if it is unresponsive, docker ps shows stale state; ctr -n moby tasks ls disagreeing with docker ps confirms it. As a fallback, nsenter from the host bypasses the daemon entirely.

"How do the -i and -t flags actually work, and why does a script using exec without -t sometimes hang?"

-i keeps the exec's stdin open and streams the client's stdin into it; without it the process's stdin is closed at start.

-t allocates a pseudo-terminal: the shim opens a pty pair, the process gets the slave side as its controlling terminal so line editing and signals like Ctrl-C work, and the client's terminal is put in raw mode and multiplexed over the API connection.

Scripts that pass -t without a real terminal fail with "the input device is not a TTY", and scripts that pass -i in a pipeline can hang because the exec waits for stdin to close; the fix is docker exec -i name cmd < /dev/null or omitting -i entirely for non-interactive commands.

Another subtlety: with -t, stderr and stdout are merged into the pty, so a script that separates them gets everything on stdout. For automation I use neither flag unless I need input, and I pass commands as an array rather than through a shell.

"Can you exec into a container and see the host, or into the host from a container?"

Not by exec, but with the same setns primitive you can go either direction if you have the privilege.

From a container that has CAP_SYS_ADMIN, CAP_SYS_PTRACE, and a view of the host's PID namespace — that is, --privileged --pid=host — nsenter -t 1 -m -u -n -i sh joins PID 1's namespaces and is a root shell on the host; this is the standard demonstration that a privileged container is the host.

It is also, deliberately, how node-debugging tools such as kubectl debug node/ and some agents work. Docker's default capability set prevents it because setns into another namespace requires CAP_SYS_ADMIN in the namespace that owns the target.

The other direction, host into container, is what docker exec is. The interview point is that the namespace boundary is only as strong as the capability checks on setns, which is why --privileged and --pid=host should never appear together on anything but a trusted tool.

Q31 · Scenario. "You need to debug a production container built from a distroless base. docker exec -it svc sh fails with 'exec: sh: not found'. How do you get in?"

Reveal answer

Strong answer The failure is expected and the fixes are ordered by how invasive they are:

  1. Understand the cause: a distroless image contains only the application and its runtime dependencies — no shell, no ls, no package manager. There is literally no /bin/sh to exec, which is the point, because there is nothing for an attacker to use either.
  2. First option, no changes: attach a debug container that shares the target's namespaces. docker debug svc in recent Docker, or in Kubernetes kubectl debug -it svc --image=busybox --target=app, starts a container with its own toolset in the target's pid, net, and optionally mount namespaces, so you can inspect the process and its network without the target having any tools.
  3. Second option, from the host: find the host PID with docker inspect --format '{{.State.Pid}}' svc and run sudo nsenter -t <pid> -n -p ps aux to enter just the network and pid namespaces, or add -m to see its filesystem. The tools come from the host, so the image staying minimal costs nothing.
  4. Third option, for filesystem inspection only: docker cp svc:/path ./local copies files out without any shell, and docker export svc | tar -t lists the whole filesystem.
  5. Prevention as policy: keep production distroless and rely on ephemeral debug containers, rather than shipping a shell into every image "just in case", which is exactly the tooling an attacker wants after a breakout.

Land it No shell in the image is a feature, not a gap — bring the tools in a debug container that shares the namespaces, and the production image stays as small and as un-exploitable as it was designed to be.

Likely follow-ups
"docker debug is not available on this host and you have no root. What is left?"

Without root on the host and without docker debug, I still have the Docker API, and the API can create a container that joins the target's namespaces.

docker run -it --rm --pid=container:svc --network=container:svc busybox sh gives me a shell that sees the application's processes and network; from there ps, netstat, and cat /proc/1/environ all work.

For the filesystem, the trick is that the target's root is visible through its PID 1: ls /proc/1/root/app inside the debug container reads the distroless image's files, because /proc/<pid>/root is a magic link into that process's mount namespace, and it works when the debug container shares the PID namespace and runs as a user with ptrace access over the target, which for the same UID or root inside the container it does.

That covers most incidents. If even --pid=container: is denied by policy, docker cp and docker export still extract files for offline inspection.

"How do you take a heap dump or a thread dump from a JVM in a distroless image?"

Two routes. The first needs no tools in the image: the JVM responds to signals and to the attach mechanism from the same PID namespace. docker kill --signal=QUIT svc makes the JVM print a thread dump to stdout, readable with docker logs.

For a heap dump, start a debug container with --pid=container:svc from an image that has a matching JDK, such as eclipse-temurin:21-jdk, and run jcmd 1 GC.heap_dump /tmp/heap.hprof; the attach works because jcmd and the target share the PID namespace and the JDK version matches, and the file is written into the target's filesystem, retrievable with docker cp.

The second route is to prepare the image for it: -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps with a volume mounted at /dumps, so the dump appears on the host without any interactive step. On Kubernetes, kubectl debug --target=app --image=eclipse-temurin:21-jdk is the same first route.

"Is a distroless image actually more secure, or does it just hide the shell from you?"

It is materially more secure, in two measurable ways, and it also has a cost.

First, attack surface after a compromise: an attacker who gains code execution in the process cannot run sh, curl, wget, or a package manager, so the common post-exploitation steps — download a tool, run a reverse shell script, pivot — require bringing everything in through the application's own runtime, which is harder and noisier.

Second, vulnerability count: with no shell, no coreutils, no libc-based tools beyond what the runtime needs, the scanner reports drop from dozens of findings to a handful, and the ones left are in the runtime you actually depend on, so patching effort is focused.

What it does not do is fix vulnerabilities in the application or the JVM. The cost is the debugging model, which has to be designed in advance with debug containers, and teams that skip that design end up shipping a :debug tag to production, which negates the first benefit.

"What would you put in the organisation's standard debug image?"

A single image, versioned like any other, that every on-call engineer knows by name.

Inside it: a shell with bash, the process and network basics — procps, iproute2, ss, tcpdump, curl, dig, netcat; strace and ltrace; lsof; jq; a JDK matching the fleet's Java version so jcmd, jstack, and jfr attach cleanly; a Python for scripting; and grpcurl and a Redis or database client for the platform's stores.

It runs as the same UID as the application so ptrace and attach work without CAP_SYS_PTRACE gymnastics. It is published under registry/tools/debug:2026.08, scanned weekly, and never used as a base for anything.

The runbook shows the two commands, docker debug or docker run --pid=container:, and kubectl debug --target. That way production images stay distroless because the alternative is one line away.

Q32. "Which Linux capabilities does Docker drop by default, and why does that make a container safer than running the same process as root on the host?"

Reveal answer

Strong answer Capabilities are the pieces that traditional all-powerful root was split into — about 40 distinct privileges such as CAP_NET_ADMIN for network configuration, CAP_SYS_ADMIN for a large grab-bag of mount and administrative operations, CAP_SYS_MODULE for loading kernel modules, and CAP_NET_RAW for raw sockets.

A normal Linux root process holds all of them.

Docker starts a container's root with only a bounded set of roughly 14 capabilities and drops the rest, so even a process running as UID 0 inside the container cannot load a kernel module, change the host's network settings, reboot the machine, or touch most of the dangerous surface.

That is why "root in a container" is meaningfully weaker than "root on the host": it is root with most of root's powers already removed.

On top of capability dropping, Docker applies a default seccomp profile that blocks around 40 system calls entirely, mounts /proc and /sys partly read-only, and hides host devices.

You tighten further with --cap-drop=ALL and then add back only what the app needs, for example --cap-add=NET_BIND_SERVICE to bind a low port, and you should also pass --security-opt=no-new-privileges so a setuid binary inside cannot regain dropped privileges.

The one command that undoes all of this is --privileged, which restores every capability, all devices, and disables seccomp, effectively giving the container the host — which is why it should appear in almost no production run command.

Land it Container root is a deliberately declawed root, and the security posture is a subtraction game — start from --cap-drop=ALL and add back the one or two the app truly needs.

Likely follow-ups
"Name the capabilities Docker keeps by default and say which ones you would still drop."

The default bounding set as of Aug 2026 is CHOWN, DAC_OVERRIDE, FSETID, FOWNER, MKNOD, NET_RAW, SETGID, SETUID, SETFCAP, SETPCAP, NET_BIND_SERVICE, SYS_CHROOT, KILL, and AUDIT_WRITE. Most exist so that an image's entrypoint can run as root, create users and files, then drop to a service account, which is what package-manager-driven images do at startup.

For a service that starts directly as a non-root user, none of them are needed, so I drop all.

The ones I would drop even for a root-starting image are NET_RAW, which allows raw sockets and therefore ARP and packet spoofing on the bridge network and has been a source of container-to-container attacks; MKNOD, which nobody needs; and SYS_CHROOT. NET_BIND_SERVICE is only needed for ports below 1024, and I avoid those inside containers anyway.

Kubernetes' restricted profile requires dropping ALL and allows adding back only NET_BIND_SERVICE, which is a good default.

"The container runs as a non-root user. Do capabilities still matter?"

Less, but yes. When runc switches to a non-root UID the effective and permitted sets are cleared unless the image uses file capabilities or ambient capabilities, so a non-root process normally has no capabilities regardless of what Docker allowed.

The bounding set still matters in two ways. A setuid binary inside the image — ping, su, sudo — can regain capabilities up to the bounding set when executed, which is what --security-opt no-new-privileges blocks by setting the no_new_privs bit so exec never raises privilege.

And a file with capability bits, set with setcap, grants those capabilities to any user who runs it.

So the safe stack for a non-root service is --cap-drop=ALL, no-new-privileges, and a read-only root filesystem, which together mean there is no path from the service's UID to any capability. getpcaps <pid> or grep Cap /proc/<pid>/status shows what a running process actually holds.

"What does --privileged do that --cap-add=ALL does not?"

--cap-add=ALL only restores the capability bounding set.

--privileged does that and also removes every other restriction: it disables the seccomp profile, disables the AppArmor or SELinux profile, mounts /proc and /sys read-write with no masked paths, and, crucially, exposes every host device node under /dev, so the container can open /dev/sda and mount the host's root filesystem.

That last one is why --privileged is host root in one step, while --cap-add=ALL with the default seccomp and no devices is still constrained. The legitimate uses are narrow: Docker-in-Docker for CI, some storage and network plugins, and hardware access on edge devices.

For each of those I would first try the specific thing needed — --device /dev/ttyUSB0, --cap-add=NET_ADMIN, a custom seccomp profile — because --privileged is the flag whose presence in a run command should end a code review.

"How would you discover the minimal capability set for a legacy image you did not write?"

Empirically, then confirm with tracing.

Run it with --cap-drop=ALL and exercise its functionality; most failures are immediate and name the operation, such as "Operation not permitted" on chown, which maps to CAP_CHOWN, or on binding port 80, which maps to NET_BIND_SERVICE. Add back exactly that one and repeat.

For anything non-obvious, run once with capabilities enabled under strace -f -e trace=capset,capget,setuid,setgid,chown,mknod,bind, or use the kernel's audit subsystem: with auditctl capability-use logging, every capability check the process passes is recorded, which gives the exact list.

The capable tool from BCC does the same with eBPF and lists PID, capability, and whether it was granted.

Then I write the result into the run configuration and into a test that starts the container with that set and exercises the same paths, so the next image update that quietly needs another capability fails in CI rather than in production.

Q33 · Scenario. "Security flagged a ticket: someone added a developer to the docker group so they could run Docker without sudo. Security says that is equivalent to giving them root. Are they right, and how do you explain and fix it?"

Reveal answer

Strong answer Security is right, and I would demonstrate rather than argue:

  1. The mechanism: membership of the docker group grants read and write on the Docker socket, /var/run/docker.sock. The daemon behind that socket runs as root and will do anything the API asks, including running a container with the host's root filesystem mounted in.
  2. The proof, which is a one-liner: docker run -v /:/host -it alpine chroot /host sh mounts the entire host filesystem into a container and chroots into it, giving a root shell on the host. The developer never typed sudo, and there is no capability drop that stops this because the request is legitimate from the daemon's point of view.
  3. So the group is not "run Docker conveniently"; it is "unrestricted root on this machine, laundered through the daemon". Any audit that treats the two differently is wrong.
  4. Fix, ranked: on shared and production hosts, do not add users to the docker group at all; grant specific commands through sudo with logging, or better, do not let humans run Docker on those hosts directly. On developer workstations where the risk is only their own machine, prefer rootless Docker or Podman, both of which run the daemon or the container as the user with no root-owned socket, so the same chroot trick lands them as themselves, not root.
  5. Prevention: a host policy check that alerts on any new docker group member, and for CI, per-job ephemeral runners rather than a shared host with a shared socket. Never mount the socket into a container that runs third-party code.

Land it The docker group is root with extra steps — the honest options are rootless Docker, Podman, or not running Docker on that host, not a policy that pretends the socket is less than what it is.

Likely follow-ups
"Rootless Docker broke the developer's workflow — ports below 1024 and a bind mount with root-owned files. What next?"

Both are the known rough edges and both have fixes without going back to the root daemon.

For low ports, set net.ipv4.ip_unprivileged_port_start=80 in /etc/sysctl.d/ so the rootless daemon can publish port 80 and 443; the alternative is to publish on 8080 locally and let a reverse proxy own the low ports, which is what production does anyway.

For bind mounts, files written by the container as UID 0 appear on the host as the developer's own UID under rootless — that is the point — but files written as the container's UID 1000 appear as a subordinate ID such as 165536 and confuse ls.

The fix is --userns=keep-id under Podman, or under rootless Docker running the container process as UID 0 inside, which maps to the developer, or using chown through rootlesskit's namespace.

If a tool genuinely needs the root daemon, a dedicated VM per developer is safer than the group.

"What is the difference between the docker group and sudo docker, from an audit point of view?"

With sudo docker, every invocation is logged by sudo with the user, the timestamp, and the exact command, and a sudoers rule can restrict which subcommands are allowed, though such rules are easy to bypass through argument tricks.

With the docker group, the socket is written directly with no record of who did what; the daemon's log shows API calls without a user identity, because a Unix socket only tells the daemon the peer's UID, which dockerd does not log by default.

So the group is unaudited root, while sudo is at least audited root. Neither is a real restriction.

The mechanism that gives real per-user authorization on Docker is an authorization plugin, configured with "authorization-plugins" in daemon.json, which sees every API request and can deny bind mounts of / or privileged runs per user; Open Policy Agent has a plugin for it.

For a shared host I would still prefer removing human access altogether.

"Is Podman's daemonless model actually safe, or does it just move the problem?"

It is safer in the specific way that matters here: there is no root-owned socket for a non-root user to write to.

Rootless Podman runs the container inside a user namespace owned by the invoking user, so the -v /:/host trick mounts the host filesystem with the user's own permissions, and chroot /host gets a shell with the user's privileges, not root.

Root inside the container is mapped to the user's UID and everything else to their subordinate range from /etc/subuid.

What moves rather than disappears: a kernel bug reachable from an unprivileged user namespace is still an escalation path, and sudo podman is exactly as root as sudo docker. Podman's remote mode with a socket has the same properties as Docker's socket.

So the honest statement is that daemonless-and-rootless removes the group-equals-root problem and keeps the kernel-bug problem, which is a good trade for workstations and CI.

"How would you detect and alert on this happening again across a fleet?"

Three signals. Configuration drift: a compliance check, in the configuration management tool or a scheduled script, that runs getent group docker on every host and reports any member other than the expected service accounts, with a ticket opened automatically.

Socket access: an audit rule, auditctl -w /var/run/docker.sock -p rw -k docker_sock, which logs every open of the socket with the calling UID, shipped to the central log store and alerted when the UID is a human account on a production host.

And behavioural: the daemon's own logs, or an authorization plugin, flag any container created with a bind mount of /, --privileged, or --pid=host, which are the specific requests an escalation needs.

For Kubernetes nodes the equivalent is an admission policy on host path mounts and privileged pods, plus Falco rules that detect a shell spawned inside a container that mounts the runtime socket.

Q34. "Why is the Docker socket root-equivalent even when the daemon drops capabilities from the containers it runs? Where does that leave sidecars that mount the socket?"

Reveal answer

Strong answer The capability drops apply to the process inside a container. The socket is the control channel to the daemon that creates containers, and the daemon itself runs with full root and no restrictions.

Anyone who can write to the socket can ask the daemon to create a new container with no capability drops, with --privileged, with the host root bind-mounted, or with the host's pid namespace shared, and the daemon will comply because those are all valid API calls.

So the sandbox around any one container is irrelevant to socket access; the socket is a request line to an unsandboxed root process.

This is why the common pattern of mounting /var/run/docker.sock into a CI container or a "Docker-in-Docker" build step is dangerous: that container, and any code it runs, now has host root.

It is also why tools that need to react to container events — log shippers, some service meshes, monitoring agents — are a real risk when they mount the socket, because a compromise of that sidecar is a compromise of the host.

The mitigations are to avoid mounting the socket at all where possible; to put a filtering proxy such as docker-socket-proxy in front of it that allows only the read endpoints an agent actually needs and blocks container creation; to use rootless Docker so the socket's daemon is not root; or to move builds to a daemonless builder like buildkit running as a dedicated service or kaniko that needs no socket.

In Kubernetes the equivalent anti-pattern is mounting the container runtime socket into a pod, and the same reasoning applies.

Land it Per-container capability drops protect you from the workload, not from the control plane — the socket is the control plane, so treat mounting it exactly as you would treat handing out root.

Likely follow-ups
"A log shipper needs container metadata. What is the smallest access you can give it instead of the socket?"

Usually none.

The metadata a shipper wants — container name, image, labels — is available without the API: Docker writes it next to each log file as config.v2.json in /var/lib/docker/containers/<id>/, so a read-only bind mount of that directory gives both the logs and the metadata; Fluent Bit's tail input with the Docker parser and Vector's docker source both work that way.

On Kubernetes the kubelet writes pod logs under /var/log/pods/<namespace>_<pod>_<uid>/ with the names encoded in the path, and the shipper enriches from the API server, not the runtime.

If an agent genuinely needs the events stream, I put docker-socket-proxy in front of the socket with only EVENTS=1, CONTAINERS=1, and INFO=1 enabled, and POST=0 so no create or exec call can pass, then mount the proxy's TCP endpoint into the agent rather than the socket itself. That reduces the agent's power from root to read-only listing.

"CI needs to build images. What replaces mounting the socket, and what does each option cost?"

Four options, in the order I would try them.

A remote BuildKit builder: a BuildKit daemon runs as a dedicated service, and CI jobs connect with docker buildx create --driver remote tcp://buildkit:1234 over mutual TLS; the job never has a socket, and the builder is a shared, cacheable resource.

Cost: one more service to run and TLS to manage. Rootless BuildKit inside the job: moby/buildkit:rootless runs as an unprivileged user using user namespaces and needs only a seccomp and AppArmor relaxation, no privilege. Cost: slightly slower and needs a kernel with unprivileged overlay.

kaniko: executes the Dockerfile in user space inside a plain container, no daemon at all. Cost: slower, no BuildKit features such as cache mounts, and maintenance has slowed as of Aug 2026.

Docker-in-Docker with --privileged: works with everything and is host root, so acceptable only on ephemeral, single-job runner VMs that are destroyed afterwards.

"Does exposing the daemon on TCP with TLS change the analysis?"

No; it changes who can reach root, not what the socket is.

A TCP endpoint with mutual TLS, configured with --tlsverify --tlscacert --tlscert --tlskey and -H tcp://0.0.0.0:2376, means only holders of a client certificate signed by your CA can talk to the daemon, which is a reasonable way to give a build server or a deployment tool access.

But every holder of such a certificate is host root, the certificate must be treated like a root password, and there is still no per-user authorization without a plugin.

Exposing the daemon on TCP without TLS, which the port 2375 default does, is an unauthenticated root shell on the network and has been mass-exploited by cryptominers for years; a scan for open 2375 ports should be part of any perimeter check.

Rootless mode is the only configuration in which the endpoint, TCP or socket, is not host root.

"How would you explain the risk to a product manager who says the sidecar is from a trusted vendor?"

I would separate trust in intent from trust in security. The vendor's agent is not malicious, but it is software with its own dependencies, its own vulnerabilities, and its own update cadence, and it sits on the network taking input.

If any bug in it, or in a library it uses, lets an attacker execute code inside that container, the socket turns that from "the monitoring agent is compromised" into "every container on this host and the host itself are compromised, including the payments database's credentials in memory".

The socket is the difference between a contained incident and a company-wide one.

Then I would offer the proportionate alternatives: the read-only proxy, the log-file mount, or the vendor's Kubernetes-native mode that uses the API server, and point out that most reputable vendors document a socket-free installation precisely because customers' security teams ask this question.

Q35 · Design. "Design the runtime-selection policy for a platform that runs a mix of first-party services and less-trusted workloads. Explain and choose between runc, gVisor, and Kata, and say what you would refuse to do."

Reveal answer

Strong answer Assumptions: most workloads are first-party and trusted, a minority run third-party or customer-adjacent code, and the platform exposes a per-workload runtime class so the choice is configuration, not a fork.

Requirement: each workload gets the weakest isolation that its trust level allows, because stronger isolation costs performance and density. The three runtimes sit on a spectrum of how much sits between the workload and the host kernel.

runc puts nothing between them: the container's system calls go straight to the host kernel, filtered only by seccomp and capabilities.

It is the fastest and the default, with essentially zero overhead, and it is correct for trusted first-party workloads, which is almost everything a normal company runs. Its boundary is the correctness of the host kernel, so a kernel exploit is an escape.

gVisor, invoked as runsc, puts a user-space kernel written in Go, called the Sentry, in the path: it intercepts the container's system calls and services most of them itself, only occasionally touching the host kernel through a tightly restricted interface.

That shrinks the host kernel's attack surface dramatically. You pay for it in system-call-heavy and I/O-heavy workloads, where overhead can be 10 to 50 percent, while CPU-bound work is barely affected.

Kata Containers runs each container, or pod, inside a real but tiny virtual machine with its own guest kernel, using a lightweight hypervisor. The boundary is now the hypervisor, the strongest of the three and the same isolation a cloud gives between tenants.

You pay around 100 to 150 milliseconds of extra startup and tens of megabytes of memory per container, and you cannot share page cache across the VM boundary.

The decision rule: trusted code runs on runc; code you are unsure about but that is not actively hostile can run on gVisor for a cheap extra wall; genuinely untrusted, multi-tenant, or compliance-bounded workloads run on Kata or the closely related Firecracker.

Because all three honor the OCI runtime spec, choosing one is a per-workload runtime class setting, not a platform rewrite.

What I would not do: default the whole platform to Kata "to be safe", because the overhead and the loss of shared page cache tax every trusted workload for a threat only a minority face; and I would not hand-tune a hardened seccomp profile on runc and market it as a substitute for a second kernel, because the CVE history says that boundary fails a few times a year.

Land it The axis is how many kernels an attacker must break — runc offers one shared kernel, gVisor a user-space kernel in front of it, Kata a whole second kernel — and you buy exactly as much of that as the trust level demands.

Likely follow-ups
"The requirement changes: everything must run on GPUs. How does that affect the runtime choice?"

It narrows it hard toward runc. GPU access from a container means passing the device nodes and the driver's user-space libraries into the container through the NVIDIA Container Toolkit, which works as a runc hook and is mature.

gVisor supports NVIDIA GPUs through its nvproxy feature since 2023, but it proxies a fixed set of driver ioctls, so it supports specific driver versions and CUDA features, and each driver upgrade must wait for gVisor to catch up; it is what some hosted inference platforms use, but with a maintenance tax.

Kata can pass a GPU through to the VM with VFIO, which gives strong isolation but dedicates a whole physical GPU to one VM and needs IOMMU support on the host, so there is no GPU sharing between containers.

So for trusted workloads I would run runc with the toolkit; for untrusted GPU workloads the choice is gVisor with nvproxy on pinned driver versions or Kata with whole-GPU passthrough, and I would state the density cost of each up front.

"You have a week to get the untrusted tier isolated. What ships and what waits?"

Ships: a dedicated node pool for untrusted workloads with gVisor installed, because runsc is a package install and a containerd runtime handler, and a RuntimeClass named gvisor that the platform assigns to the untrusted namespaces by admission policy; plus network policy that denies those pods egress to the internal ranges and the metadata endpoint.

That gives a second wall in front of the kernel within days and needs no image changes.

Waits: Kata, because it needs nested virtualisation or bare-metal nodes, hypervisor packaging, and storage integration; performance tuning of gVisor's platform choice; per-workload benchmarking; and the policy framework that lets a workload request a stronger class.

I would also defer the discussion of moving any first-party workload, since runc is correct for it.

The verification before the week ends is a pod in the untrusted namespace showing gVisor in dmesg — gVisor's fake kernel log is unmistakable — and a metadata curl failing.

"What are the concrete things that do not work under gVisor that would surprise a team?"

The list as of Aug 2026 is short but bites specific workloads. Some system calls are unimplemented or partial, and runsc returns ENOSYS for them; anything using io_uring, some perf and ptrace features, and a handful of obscure socket options fail.

Profilers and debuggers that rely on ptrace or perf_event_open do not work, so a JVM flight recording works but async-profiler's perf-based mode does not.

File I/O through the Gofer is slower, so databases and build tools with heavy metadata activity slow down noticeably, and the directfs mode trades some isolation for speed.

Networking goes through netstack, gVisor's own TCP stack, which is fine for services but shows different tuning behaviour and lacks some kernel congestion controls. /proc and /sys are emulated, so monitoring agents that read exotic files get empty results.

Each is discoverable in an afternoon with the team's own smoke tests, which is why I benchmark before committing a workload class.

"How do you make sure the untrusted workloads actually ended up on the isolated runtime?"

With an enforcing check and an observing check. Enforcing: a Kubernetes admission policy, ValidatingAdmissionPolicy or Kyverno, that rejects any pod in an untrusted namespace whose runtimeClassName is not gvisor or kata, and mutates it in if absent; without enforcement a copied manifest silently lands on runc.

Observing: from inside, dmesg under gVisor prints its own recognisable boot messages and uname -r reports gVisor's fake version; under Kata, uname shows the guest kernel, not the host's, and /proc/cpuinfo shows the VM's vCPUs. On the node, crictl inspect shows the runtime handler per container.

I would run a daily job that lists every pod, its namespace, and its resolved runtime handler and alerts on any mismatch, and I would add a synthetic canary in the untrusted namespace that fails if it can read a host-only path. Trust the policy, but measure it.

Q36. "Podman and nerdctl are called daemonless. What does that mean, what changes for the user, and where does Docker still have an edge?"

Reveal answer

Strong answer Daemonless means there is no long-running root background service that owns all containers. With Docker, every container is a child of the shim under dockerd, and the daemon is a single privileged process and a single point of failure.

Podman instead forks containers directly as children of the invoking user's process, using the same runc and the same OCI images, with the same command-line flags, so alias docker=podman works for most day-to-day use.

Because there is no root daemon, Podman runs rootless by default: containers run in a user namespace as the invoking user, which removes the root-owned socket that makes the Docker group root-equivalent.

It also introduces pods, groups of containers sharing namespaces, which map cleanly onto Kubernetes and let Podman generate Kubernetes YAML. nerdctl is a Docker-compatible command-line tool that drives containerd directly, giving you Docker-like ergonomics on a containerd-only host such as a Kubernetes node, plus access to containerd features like lazy-pulling snapshotters.

What Docker still does better in practice: Docker Desktop and Compose are more polished and more widely documented; Podman's rootless networking through pasta or slirp4netns is improving but historically slower and occasionally surprising for published ports; and the enormous base of tutorials and CI integrations assumes the Docker CLI and daemon.

Since a daemonless tool has no always-on process, features that depend on one — restart policies that survive a reboot, live events streams — are handled differently, through systemd units that Podman can generate with podman generate systemd or the newer Quadlet files.

Land it Daemonless trades a central privileged service for per-user processes, which is a security win and a fit for rootless and systemd — Docker's remaining edge is polish and ecosystem, not the core mechanism.

Likely follow-ups
"If Podman has no daemon, what keeps the container running after the user logs out?"

By default nothing, and that is the sharpest difference. A rootless Podman container is a child of the user's session, and when the session ends systemd's logind kills the user's processes unless lingering is enabled with loginctl enable-linger <user>.

Even with lingering, a container started from a shell has no restart-on-failure supervision because there is no daemon watching it.

The intended model is systemd: podman generate systemd --new or, preferred since Podman 4.4, a Quadlet file — a .container unit in ~/.config/containers/systemd/ that systemd turns into a service with Restart=always, dependency ordering, and journald logging.

Podman does run a small helper called conmon per container, which holds the stdio and exit code the way containerd's shim does, so a container survives the Podman command exiting; it does not survive the session without linger or systemd.

Docker's daemon does both jobs implicitly, which is convenient and is the trade.

"Can I point my existing docker compose files at Podman, and what breaks?"

Mostly, and the breakage is predictable. Podman exposes a Docker-compatible API on a socket, enabled with systemctl --user enable --now podman.socket, and setting DOCKER_HOST=unix://$XDG_RUNTIME_DIR/podman/podman.sock lets the real docker compose binary drive it; podman-compose is a separate reimplementation with more gaps.

What breaks: Compose files that mount /var/run/docker.sock, since the path is different and the semantics are rootless; services publishing ports below 1024 without the sysctl; anything relying on the default bridge's docker0 name or on host.docker.internal, which Podman calls host.containers.internal; and volume ownership when a container runs as a specific UID and expects host files to match.

BuildKit-specific Dockerfile features work because Podman's builder, Buildah, supports most of them, but --mount=type=cache and secrets have small syntax differences. The fastest check is running the Compose file once with --dry-run and reading the warnings.

"What does nerdctl give you on a Kubernetes node that crictl does not?"

crictl is a debugging tool for the CRI: it lists pods and containers as the kubelet sees them, inspects them, and reads logs, and it deliberately cannot build or run arbitrary images because the kubelet owns the node.

nerdctl is a full Docker-compatible client for containerd: it can pull, build with BuildKit, run, compose, and, importantly, do so in a containerd namespace of your choosing, so nerdctl -n k8s.io images shows the kubelet's images while nerdctl run in the default namespace runs something the kubelet does not manage.

It also exposes containerd-specific features Docker lacks: lazy pulling with --snapshotter=stargz, image encryption with nerdctl image encrypt, and IPFS-backed images.

On a production node I would use crictl for diagnosis and keep nerdctl for build hosts, because running unmanaged containers on a kubelet node confuses capacity accounting and audits.

"Where has Docker actually lost ground to these tools, and where has it kept it?"

Lost: the Kubernetes node, completely, since 1.24 — containerd or CRI-O runs every serious cluster and Docker Engine is not on the node at all. Lost on Red Hat family servers, where Podman is the default and Docker requires a third-party repository.

Lost in security-sensitive CI, where rootless Podman or BuildKit avoids the socket problem by default.

Kept: the developer laptop, where Docker Desktop's integration, Compose, and the sheer volume of documentation and tutorials still dominate, though Podman Desktop and Rancher Desktop are credible as of Aug 2026; the build engine, since BuildKit is Docker's project and Buildah lags it; and the single-server deployment, where the daemon's restart policies and Compose are still the simplest working answer.

The interview point is that the OCI standards made this a choice of tools rather than of formats — the same image runs everywhere — so a team can use Docker to build and containerd to run without friction.

Q37. "On a Linux server Docker runs natively, but Docker Desktop on a Mac or Windows laptop runs a Linux VM. Why, and what does that cost, especially for bind mounts?"

Reveal answer

Strong answer Containers are a Linux kernel feature — namespaces and cgroups are Linux constructs. A Mac runs the Darwin kernel and Windows runs the NT kernel, neither of which has them.

So Docker Desktop on those platforms runs a lightweight Linux virtual machine, and dockerd, containerd, runc, and every container live inside that VM. The docker CLI on the host talks to the daemon in the VM. On a Linux server there is no VM: the daemon and containers use the host's own kernel directly, which is why "Docker on Linux" and "Docker Desktop" behave differently and why production is always Linux-native.

The cost people feel most is bind mounts. When you mount a source directory from the Mac filesystem into a container, the files must cross the boundary between the host operating system and the Linux VM, historically over a network file protocol.

That crossing is slow for workloads that touch many small files — a Node.js node_modules tree, a large Maven build, a PHP project — and can turn a sub-second operation into tens of seconds.

Docker Desktop has mitigated it over the years with gRPC-FUSE, VirtioFS on macOS, which is now the default and much faster, and mount consistency flags like :cached and :delegated.

The other costs are memory and CPU: the VM reserves resources the host cannot use, so a laptop running Docker Desktop gives a few gigabytes to the VM whether or not containers need them.

The practical advice is to keep heavily-accessed data in named volumes, which live inside the VM's own fast filesystem and avoid the host boundary entirely, and to reserve bind mounts for source code you are editing.

Land it There is a whole Linux VM under Docker Desktop because containers are Linux, and the bind-mount slowness is the file-sharing boundary of that VM — keep hot data in named volumes and the boundary disappears.

Likely follow-ups
"A developer's Maven build takes 12 minutes in a container on a Mac and 90 seconds natively. How do you cut it?"

Almost all of that is the bind mount, and I would change what crosses the boundary. First, move the dependency cache off the bind mount: a named volume at /root/.m2, so the tens of thousands of small jar and pom reads happen inside the VM's disk.

Second, the build output: point target/ at a volume or build inside a copy of the source rather than in place, since writing thousands of class files across VirtioFS is the slowest operation.

Third, check the file-sharing implementation in Docker Desktop's settings: VirtioFS is the default and much faster than gRPC-FUSE; if the machine is still on the older option, switching is a settings change.

Fourth, exclude what the build does not need: a .dockerignore and a narrower mount, so .git and node_modules are not synchronised. The result on a typical project is two to three minutes.

The remaining gap is the VM's CPU allocation, which is a slider in the same settings panel.

"How does the docker CLI on the Mac reach the daemon in the VM, and what breaks because of it?"

Docker Desktop runs a Linux VM through Apple's Virtualization framework, and the daemon inside it listens on a Unix socket that Desktop forwards to ~/.docker/run/docker.sock on the Mac, with /var/run/docker.sock as a symlink; the CLI talks to that like any other socket.

Consequences: -v /host/path refers to the Mac path but is served through the file-sharing layer, and only directories under the configured shared paths are available.

Published ports are forwarded from the Mac's loopback into the VM by a helper process, so localhost:8080 works but the container's IP address such as 172.17.0.2 is unreachable from the Mac, which surprises people who read Linux tutorials.

--network host refers to the VM's network, not the Mac's, so it does not expose services on the Mac's interfaces. And tools that read /var/lib/docker on the host find nothing, because that path is inside the VM.

"What about the memory the VM takes? Is there a way to give it back when idle?"

The VM's allocation is a maximum, not a fixed reservation, on current versions.

Docker Desktop's VM uses virtio-balloon and, on macOS, the framework's dynamic memory so that pages the guest kernel frees can be returned to the host, and it shows the actual usage separately from the limit.

The practical problem is that a Linux guest tends to fill free memory with page cache from image layers and builds, and cache does not look free to the host, so the VM grows to its limit and stays there; a periodic drop of caches inside the VM or simply restarting Docker Desktop returns it.

The settings for CPUs, memory, swap, and disk size are in the resources panel and also in ~/Library/Group Containers/group.com.docker/settings.json.

The sensible default on a 16 GB laptop is 4 to 6 GB for the VM, and I keep resource-heavy databases as separate native services or in a remote environment rather than fighting for the laptop's memory.

"Are there alternatives to Docker Desktop on a Mac, and what do they trade?"

Several, all built on the same idea of a Linux VM. Colima uses Lima to run a VM with Docker or containerd and exposes a standard socket; it is free, scriptable, and lighter, but file sharing and port forwarding are a little less polished.

OrbStack is a commercial alternative with notably fast file sharing and low memory use and is popular with developers who hit VirtioFS limits. Podman Desktop and Rancher Desktop add Kubernetes and Podman support.

The trade in each case is support and integration: Docker Desktop's file sharing, credential helpers, Compose, and extensions are better tested, and corporate IT knows it.

The licensing point, which as of Aug 2026 still applies, is that Docker Desktop requires a paid subscription for larger companies, which is why Colima appears in many corporate environments.

The underlying engine and images are identical, so switching is a matter of installing and pointing DOCKER_HOST at the new socket.

Q38. "In one question: how are Windows containers different from Linux containers, and can a host run both?"

Reveal answer

Strong answer Windows containers are the same idea — process isolation with a restricted view and resource limits — but built on Windows kernel primitives instead of Linux namespaces and cgroups, and they share the Windows kernel rather than the Linux one.

Because a container shares the host kernel, a Windows container needs a Windows host and a Linux container needs a Linux host; a Linux image cannot run on Windows using the host's own kernel, and vice versa. Windows offers two isolation modes.

Process isolation is the direct equivalent of Linux containers: processes share the host kernel, so they are light and fast but the container's Windows build must match the host's closely.

Hyper-V isolation runs each container in a small dedicated virtual machine, which loosens the version-matching requirement and adds a hypervisor security boundary, at the cost of the usual VM overhead.

Windows base images are also large — the older servercore is over a gigabyte, though nanoserver is a few hundred megabytes — because Windows cannot be stripped as thin as a distroless Linux image.

On the "run both" question: a single kernel cannot host both, but Docker Desktop on Windows can switch between a Linux mode, which runs the same Linux VM as on a Mac, and a Windows-container mode that uses the host Windows kernel, so one machine can build and run either, just not simultaneously against the same daemon.

In practice the overwhelming majority of container workloads are Linux, and Windows containers appear mainly for legacy .NET Framework applications that cannot be ported to .NET on Linux.

Land it A container always shares its host's kernel, so Windows and Linux containers each need their own kernel — Windows containers are a real thing, mostly for legacy .NET, not a way to run Linux images on Windows.

Likely follow-ups
"What is the version-matching rule for Windows process isolation, and how do you handle a fleet with mixed host builds?"

Under process isolation, the container's base image build must match the host's Windows build family: a Windows Server 2022 host runs Server 2022 base images, and Server 2019 images fail with an incompatibility error.

Since Windows Server 2022 there is a relaxation for the servicing revision, so a container image from an older monthly update runs on a newer patched host of the same build, but crossing major builds still needs Hyper-V isolation.

For a mixed fleet the practical approaches are: label nodes by build and use a node selector so each image lands on a matching host, which Kubernetes does through the node.kubernetes.io/windows-build label; publish a multi-build manifest list where each entry's os.version field points at the right variant, which the runtime matches automatically; or run everything under Hyper-V isolation and pay the VM overhead.

I would push hard for a single host build across the fleet, because the alternatives multiply images and testing.

"Can a Kubernetes cluster run Windows and Linux pods, and what has to be different?"

Yes; the control plane is Linux-only, and Windows joins as worker nodes with their own kubelet, containerd, and CNI. Everything a pod does that touches the operating system differs: images must be Windows images, the node selector kubernetes.io/os: windows must be on every Windows workload or the scheduler will try Linux nodes, volume mounts use Windows paths and only some CSI drivers support Windows, security contexts such as runAsUser do not apply and are replaced by windowsOptions with a run-as-username, host networking is unsupported, and privileged containers are replaced by host process containers.

Network policy and service meshes have partial support. Resource limits work but memory is enforced differently, as a job object limit rather than a cgroup, and there is no OOM killer in the Linux sense.

Operationally, Windows nodes are larger, slower to pull, and patched monthly with a reboot, so I run them as a separate node pool with taints and keep the number of Windows workloads as small as the legacy estate allows.

"How does WSL 2 fit into this, and is Docker on WSL the same as Docker Desktop?"

WSL 2 is a lightweight Linux VM managed by Windows with a real Linux kernel that Microsoft ships and updates, so Linux containers under WSL 2 are Linux-native inside that VM. Docker Desktop for Windows uses the WSL 2 backend by default: it runs its daemon in a dedicated WSL distribution and integrates the CLI into the user's other distributions, so the developer experience is Docker Desktop's, with its file sharing and port forwarding. Installing Docker Engine directly inside a WSL 2 distribution with apt is also possible and gives plain Linux Docker without Desktop's licensing; it works well, with the caveats that systemd must be enabled in the distribution for the daemon to autostart, that files on the Windows filesystem under /mnt/c are slow to bind-mount for the same cross-boundary reason as on a Mac, and that ports are reachable from Windows through WSL's localhost forwarding. Neither runs Windows containers; those need the Windows daemon and Hyper-V or process isolation on the host.

"Why not just run the legacy .NET Framework app in a Linux container with Mono or Wine?"

Because the .NET Framework is not the same thing as .NET, and the gap is the whole reason Windows containers exist.

Mono implemented a large part of the Framework's API but never the Windows-specific pieces — WCF server side, System.Web and ASP.NET WebForms, Windows authentication, COM interop, registry access — that legacy enterprise apps use most, and Microsoft's own advice is to migrate to modern .NET, which runs natively on Linux, rather than to use Mono.

Wine is for desktop applications and is not a supported server platform.

So the realistic paths are: port the application to .NET 8 or later and ship a Linux container, which is the strategic answer and often a multi-month project; or containerise as-is on Windows Server Core, which works today, keeps IIS and Windows auth, and costs a gigabyte-plus image and a Windows node pool.

I would choose per application by remaining lifetime: anything living more than two years gets ported.

Q39. "State the current Docker and container-runtime version landscape as of August 2026, and why version currency matters for cgroups."

Reveal answer

Strong answer As of August 2026 the current release line is Docker Engine 29.x, with 28.x still supported and widely deployed. Underneath it, containerd is on the 2.x line, and runc is on 1.3.x.

The most consequential change over the last few years is the move to cgroups v2 as the default on essentially every modern distribution — recent Ubuntu, Debian, Fedora, and the RHEL family all boot with the unified cgroup hierarchy.

Docker and containerd both fully support v2, and it is what a new install expects.

Why currency matters here: cgroups v1 and v2 have different filesystem layouts and different controller semantics, so any tool that reads limits directly — a JVM sizing its heap, a Go program calling a cgroup library, a monitoring agent — must know which version it is on.

A JVM older than roughly JDK 15 only understood v1 paths and would ignore limits on a v2 host, sizing itself to the whole machine; the OOM-kill scenarios from the memory questions often trace back to exactly that mismatch.

Version currency also carries security fixes: runc has had container-escape CVEs patched in point releases, so running an old runc is a real risk, not just a missing feature.

The practical stance for a senior is to keep the engine within one major version of current, keep runc patched aggressively because it is the escape-relevant component, confirm the host's cgroup version with stat -fc %T /sys/fs/cgroup — which prints cgroup2fs on v2 — and make sure every runtime that reads limits is new enough to understand v2.

Land it Keep the engine current and runc patched hardest, because runc is where escapes live and cgroup v2 being the default means old limit-reading tools quietly get the numbers wrong.

Likely follow-ups
"A host was upgraded to cgroup v2 and a monitoring agent stopped reporting container memory. What is happening?"

The agent is reading v1 paths that no longer exist. Under v1 the memory controller lived at /sys/fs/cgroup/memory/docker/<id>/memory.usage_in_bytes and the limit at memory.limit_in_bytes; under v2 the same numbers are memory.current and memory.max in one unified directory such as /sys/fs/cgroup/system.slice/docker-<id>.scope/.

An agent hard-coded to the old layout either finds no file and reports nothing or, worse, falls back to host totals. I would confirm with stat -fc %T /sys/fs/cgroup printing cgroup2fs and mount | grep cgroup showing a single mount.

The fix is upgrading the agent to a version with v2 support, which every mainstream agent has had since around 2022, or as a temporary measure booting the host with systemd.unified_cgroup_hierarchy=0 on the kernel command line to go back to v1 — which I would do only to buy time, since the v1 code paths are deprecated in the kernel and containerd.

"How do you keep runc patched across a fleet without a maintenance window per host?"

runc is a single binary invoked per container start, so replacing it does not touch running containers: the next docker run or exec simply uses the new file.

The package manager update of containerd.io, which bundles runc, or of the separate runc package on some distributions, can therefore roll continuously.

The process I would run: subscribe to the runc and containerd security advisories; on a critical CVE, push the package update through the configuration tool to a canary pool, verify runc --version and a container start and exec, then roll fleet-wide with a concurrency limit.

For Kubernetes, the node image is rebuilt with the new runc and nodes are replaced by a rolling node pool upgrade, which drains pods gracefully.

The one wrinkle is that a containerd upgrade restarts the containerd service, which is safe with the shim design, but a Docker Engine major upgrade may not be live-restore compatible and is scheduled with a drain.

Verification is a fleet-wide report of runc --version gathered by the agent.

"What breaks when you upgrade Docker Engine by two major versions at once?"

Three categories.

API and CLI: the engine drops old API versions over time, and a client or SDK pinned to a removed version fails with a version error; docker version shows the minimum supported API and the fix is a client upgrade or the DOCKER_API_VERSION variable while you migrate.

Daemon configuration: deprecated daemon.json keys and storage drivers are removed — the devicemapper and aufs drivers are long gone, and a host still on them cannot start on the new engine without migrating images to overlay2.

Behaviour changes: the iptables-to-nftables move in recent engines changes how published ports interact with host firewalls, the containerd image store may become the default with a migration, and BuildKit-only features replace legacy builder behaviour.

Live restore does not carry running containers across a major upgrade, so plan a drain. My rule is one major at a time with the release notes read for the deprecated list, tested on a canary host with the actual Compose files.

"How does the JDK actually detect cgroup v2, and which JDK lines have it backported?"

The JVM's container support reads /proc/self/mountinfo and /proc/self/cgroup at startup to find how the cgroup filesystem is mounted and which path this process lives in.

If it finds a single cgroup2 mount, it uses the v2 code path reading memory.max, cpu.max, and cpu.weight from that directory; if it finds v1 controller mounts, it reads the v1 files.

That detection was added in JDK 15 through JEP-less work under bug 8230305 and backported to JDK 11.0.16 and 8u372, so as of Aug 2026 every supported JDK line handles v2; a JVM older than those updates on a v2 host reads nothing and behaves as if unlimited.

You can see the outcome with java -Xlog:os+container=info -version, which prints the detected cgroup version and every limit it read. The same detection also drives availableProcessors(), so an old JVM on a v2 host gets both the memory and the CPU count wrong.

Q40 · Scenario. "A batch job container is being OOM-killed and restarted every few minutes under Kubernetes, but the same image with the same --memory=1g runs fine for hours on a developer's laptop with docker run. Reconcile the two and connect it to what you know about limits."

Reveal answer

Strong answer The two environments are enforcing different things, and I would prove it:

  1. Get the real limit in each. On the laptop, docker inspect --format '{{.HostConfig.Memory}}' shows 1 GB and docker stats shows steady usage below it. In Kubernetes, kubectl get pod -o jsonpath='{.spec.containers[0].resources}' — the crucial check is whether limits.memory is set and what it equals, versus requests.memory.
  2. Confirm the kill: kubectl describe pod shows Reason: OOMKilled and a restart count climbing, and the node's dmesg shows the cgroup OOM message.
  3. Ranked causes. First and most common: the pod's memory limit is lower than the laptop's 1 GB — a namespace LimitRange or a copied manifest set limits.memory: 512Mi — so the job legitimately exceeds it. Second: limit equals request on the laptop but in the cluster the request is low and the limit high, and the node itself is under memory pressure, so the kubelet evicts or the kernel reclaims aggressively; the job's peak, which the laptop tolerated because it was the only process, now collides with neighbours. Third: the job's memory use depends on input size, and production input is larger than the developer's test input, so the peak genuinely differs.
  4. Fix: set the pod's limits.memory to match the peak you measured plus headroom, and set requests.memory equal to the limit for a batch job so the scheduler reserves the real amount and the pod gets the Guaranteed quality-of-service class, which protects it from eviction. If it is a JVM or other runtime, confirm it reads the cgroup limit and set its heap fraction accordingly, exactly as in the earlier memory question.
  5. Prevention: load-test with production-sized input, alert on the ratio of working-set to limit, and treat request-equals-limit as the default for batch. This ties directly to the Kubernetes appendix, where requests, limits, and QoS classes decide who gets killed first, and to the distributed-systems appendix on why noisy neighbours make single-host testing misleading.

Land it "Works on my laptop" and "OOM-killed in the cluster" are the same cgroup mechanism with two different numbers — find the limit each environment actually applied, and the contradiction turns into a one-line manifest fix.

Likely follow-ups
"The limit is identical, 1 Gi in both. It still dies only in the cluster. What next?"

Then the difference is in what else shares the cgroup or in the input.

Sidecars first: in a pod, each container has its own cgroup, but with a service mesh the sidecar and the app share the pod's overall accounting only if a pod-level limit is set, so I would check whether the OOM message in dmesg names the job process or the sidecar, and whether an init container or an injected agent is adding memory to the job's container itself, such as a Java agent jar.

Second, the working set definition: Kubernetes evicts on working set, which excludes inactive page cache, but the kernel's OOM killer counts the full memory.current, which includes cache from reading large input files, so a job that streams a 2 GB file through the page cache can hit 1 Gi on the kernel side while the laptop, with docker stats showing cache-excluded numbers, looked fine.

Third, the input: production runs bigger batches. memory.stat from the container's cgroup, captured every few seconds before the kill, settles which.

"Why request equals limit for a batch job, and what does that cost the cluster?"

Setting requests.memory equal to limits.memory puts the pod in the Guaranteed quality-of-service class, which means the scheduler reserves the full amount on the node and the kubelet evicts Guaranteed pods last under node pressure.

For a batch job that legitimately uses its peak, that removes the case where the node is oversubscribed on requests and the job is evicted mid-run because neighbours grew — an eviction wastes the whole run.

The cost is packing efficiency: memory reserved for the job is unavailable to others even when the job is idle, so a cluster full of Guaranteed pods runs at a lower average utilisation.

For long-running services with spiky memory, a request below the limit is the better trade.

For CPU I do not apply the same rule, because a CPU limit throttles rather than evicts and a batch job usually benefits from bursting; I set a CPU request and leave the limit off or high.

"What is the practical difference between the kubelet evicting a pod and the kernel OOM-killing a container?"

They are two different actors with different triggers and different evidence.

The kernel OOM killer acts when a single container's cgroup hits its memory.max; it sends SIGKILL to a process in that cgroup, the container exits 137, OOMKilled: true appears in the pod status, the restart policy restarts the container in place, and dmesg has the record.

The kubelet evicts when the node as a whole crosses its memory threshold, memory.available below the configured eviction hard limit, regardless of any single pod's limit; it picks pods by quality-of-service class and by how far usage exceeds requests, terminates the whole pod with the normal grace period, marks it Evicted with a reason in kubectl describe, and the pod is rescheduled elsewhere rather than restarted in place.

So 137 with OOMKilled means fix the pod's limit; an Evicted status means fix the node's capacity or the pod's request. A laptop with a single container can only ever show the first.

"How would you reproduce the cluster failure on the laptop so the developer can iterate?"

Copy every constraint the pod has into the docker run. Memory: --memory=1g --memory-swap=1g, because the cluster has swap disabled and the laptop may not, and swap is why the laptop tolerated the peak.

CPU: --cpus= matching the pod's CPU limit, since a tighter CPU limit changes garbage collection timing and can raise peak memory. Input: the same production-sized input file, not the test fixture.

Process: the same user, a read-only root filesystem, and any sidecar or agent the pod injects, added as a second container in the same cgroup with --cgroup-parent or simply as an extra process.

Then run docker stats --no-stream in a loop to log the memory curve and compare the peak with the cluster's.

If it still passes, the difference is cache accounting, and I can force it by reading the input through the page cache exactly as the job does. A Compose file capturing this becomes the standing repro.

08 · DrillDockerfiles, Builds & Runtime Behaviour — Q41–Q80

This section is the one most senior Docker rounds actually spend their time on, because every engineer has written a Dockerfile and very few can explain what each line does to the layer cache, to the image size, or to the process that eventually runs as PID 1.

The forty questions move from the instructions themselves, to how the build cache decides what to redo, to the JVM and Python images you will ship in practice, and finally to what happens at runtime: signals, exit codes, logs, memory limits and the way the JVM reads them.

Interviewers love this area because the answers are checkable — a wrong claim about CMD versus ENTRYPOINT or about exit code 137 is caught in one follow-up. Say each answer aloud, with the flag names, before you reveal.

Drill · Dockerfile instructions & layers

These questions test whether you know what each instruction does to the image — which ones add a layer, which ones only write metadata, and which ones quietly leak secrets or break signal handling.

Q41. "Explain ENTRYPOINT versus CMD, and shell form versus exec form. Why does the combination matter for how the container stops?"

Reveal answer

The real test Whether you connect the syntax choice to signal delivery, because that is where the production bug lives.

Strong answer ENTRYPOINT is the fixed program the container runs, and CMD is the default set of arguments appended to it.

When both are present, docker run image extra-args replaces only the CMD part, so you get a container that behaves like a command-line tool with sensible defaults. If only CMD is set, it is the whole command and is replaced entirely by any arguments you pass.

Each instruction can be written in two forms. Exec form is the JSON array, ENTRYPOINT ["java","-jar","/app.jar"], and Docker starts that binary directly as process ID 1 (PID 1), the first process in the container.

Shell form is a plain string, ENTRYPOINT java -jar /app.jar, and Docker actually runs /bin/sh -c "java -jar /app.jar", so the shell becomes PID 1 and your program is its child. That distinction matters because docker stop sends the SIGTERM signal to PID 1 only.

In shell form the shell receives it, does not forward it to the child, and after the 10-second grace period Docker sends SIGKILL and your JVM dies without running shutdown hooks.

Exec form also means no variable expansion, so ENTRYPOINT ["java","$JAVA_OPTS"] passes the literal string; you either use shell form deliberately with exec, or a small entrypoint script that ends with exec java "$@".

Land it My rule is exec form for ENTRYPOINT, CMD for overridable defaults, and a wrapper script only when I need variable expansion — and that script must end with exec so the real process becomes PID 1.

Likely follow-ups
"I have heard that sh -c sometimes does exec the child itself. So is shell form really always broken?"

Not always, which is why it is a trap rather than a hard failure.

Both bash and Debian's dash have an optimisation: when -c is given a single simple command with no redirections, pipes, or trailing commands, the shell replaces itself with that command using exec, so the program becomes PID 1 and signals work.

The moment the string has more than one command — java -jar app.jar && echo done, an environment assignment followed by a command, or a pipe into a logger — the shell stays resident as PID 1 and the child never sees SIGTERM. Busybox's ash in Alpine images did not do this optimisation for years, and older dash versions did not either.

So the behaviour depends on the shell binary in the base image and on the exact string, which is precisely the kind of thing that works on a laptop and fails after a base image change. Exec form removes the dependency entirely.

"How do I get variable expansion and still have the JVM as PID 1, without a script file?"

Use exec form with the shell called explicitly and an exec inside the string: ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar /app/app.jar \"$@\"", "--"]. The exec replaces the shell with the JVM once the expansion has happened, so the JVM is PID 1.

The trailing "--" becomes $0 and any docker run arguments become "$@", so CMD overrides still work.

For the specific case of JVM options there is a cleaner answer that needs no shell at all: JAVA_TOOL_OPTIONS is read by every JVM launch and can be set with ENV or with -e at run time, so ENTRYPOINT ["java", "-jar", "/app/app.jar"] plus JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75" gives configurable flags with exec form.

The JVM prints "Picked up JAVA_TOOL_OPTIONS" to stderr on start, which is the confirmation it worked.

"What happens if both ENTRYPOINT and CMD are in shell form, or if a child image sets CMD but the parent set ENTRYPOINT?"

If ENTRYPOINT is shell form, CMD is ignored entirely; Docker runs sh -c "entrypoint string" and the CMD value is never appended, which is a surprisingly common source of "my arguments do nothing".

If ENTRYPOINT is exec form and CMD is shell form, the CMD is wrapped as sh -c "cmd string" and appended as arguments, so the entrypoint receives sh, -c, and the string, which is almost never what anyone wanted.

The inheritance rule is that a child image inherits both from the parent, but if the child sets ENTRYPOINT, the inherited CMD is reset to empty, on the theory that the old default arguments no longer make sense for a new program.

A child that sets only CMD keeps the parent's ENTRYPOINT. docker inspect --format '{{.Config.Entrypoint}} {{.Config.Cmd}}' shows the resolved pair, and I check it whenever an image behaves differently from its Dockerfile.

"Why does Ctrl-C not stop docker run with a shell-form entrypoint, and why does docker stop behave differently from docker kill?"

With docker run in the foreground and a TTY, Ctrl-C sends SIGINT to the container's PID 1 through the attached terminal.

A shell-form PID 1 is sh, which in non-interactive mode ignores SIGINT and does not forward it, so the JVM keeps running; the same happens with SIGTERM from docker stop.

docker stop is a two-phase operation: send the image's STOPSIGNAL, default SIGTERM, wait the grace period, then SIGKILL, so it always terminates eventually but takes the full timeout when the signal is swallowed.

docker kill sends one signal, SIGKILL by default or whatever --signal names, and never waits, so it is the tool for sending a specific signal such as SIGHUP for a config reload or SIGQUIT for a JVM thread dump.

Compose's down uses the stop path, which is why a fleet of shell-form containers makes docker compose down take ten seconds per service.

Q42. "COPY versus ADD — when is ADD actually the right choice, and why do linters flag it by default?"

Reveal answer

Strong answer COPY takes files from the build context — the directory you hand to docker build — and places them into the image, and that is all it does. ADD does the same thing plus two extra behaviours.

First, if the source is a local tar archive in a recognised compression format, ADD unpacks it into the destination automatically. Second, if the source is a URL, ADD downloads it.

Those extras are exactly why linters such as hadolint flag ADD: the auto-extraction is a surprise when you simply wanted to copy a .tar.gz artefact into the image, and the URL download creates a layer whose cache validity depends on a remote file Docker cannot checksum ahead of time, so the layer is effectively never cached and the download is not verified.

ADD is the right choice in two narrow cases: unpacking a local tarball of a runtime, for example a vendored JDK, where you would otherwise need a RUN with tar and a second layer to delete the archive; and, since BuildKit added it, fetching Git repositories with ADD --keep-git-dir or checksum-verified downloads with ADD --checksum=sha256:… https://….

For everything else, COPY expresses intent precisely, and for downloads a RUN curl with a pinned checksum is clearer and can live in the same layer as its cleanup.

Land it Default to COPY, and treat every ADD in review as a question: did you want the extraction or the download, and is it checksum-pinned?

Likely follow-ups
"What is the cache behaviour of ADD with a URL, exactly, and how does --checksum change it?"

With a plain URL, the builder has to download the file to know whether it changed, because there is no local content to hash; the legacy builder downloaded it every time and compared the bytes, and BuildKit issues a HEAD request and uses the response headers, so the step is re-run when the server reports a different size or modification time and the layer is invalidated whenever the remote changes.

Neither verifies integrity.

With ADD --checksum=sha256:<hex> https://example/file.tgz /opt/, available since Dockerfile syntax 1.6, the checksum becomes part of the cache key, so the step is cached as long as the checksum in the Dockerfile is unchanged, and the download fails the build if the bytes do not match.

That turns ADD from a cache-unfriendly, unverified download into a pinned, reproducible one, which is the only situation in which I prefer it to RUN curl: it needs no curl in the image and leaves no temporary file to clean up.

"Does COPY preserve ownership and permissions, and how do --chown and --chmod work with it?"

COPY preserves the file mode bits from the build context but not ownership; files land owned by root, UID 0, regardless of who owns them on the host, which is why a non-root runtime user often cannot write to directories copied in.

COPY --chown=10001:10001 src/ /app/ sets ownership at copy time, without a separate RUN chown that would duplicate every file into a new layer.

COPY --chmod=0755 entrypoint.sh / sets the mode, which is the fix for "permission denied" on a script committed without the execute bit on a Windows checkout.

Two subtleties: the numeric form is safer than names, because the user may not exist yet in the stage; and directory semantics differ from cp — COPY src /app copies the contents of src into /app, not src itself, and a trailing slash on the destination is required when the destination should be treated as a directory.

COPY --link additionally makes the layer independent of previous layers for better cache reuse.

"When would COPY --from=image be better than a RUN that installs the same tool?"

When the tool is a static binary or a self-contained directory and I want its exact version without its package manager, its dependencies, or its base image.

COPY --from=ghcr.io/astral-sh/uv:0.8.0 /uv /usr/local/bin/ or COPY --from=busybox:1.36-musl /bin/busybox /bin/ adds one file in one layer with a pinned version, no apt-get, no network during the build beyond the registry, and a cache key that is the image digest.

It is the idiom for CLI tools like uv, tini, grpc_health_probe, and cloud SDK binaries. It is the wrong choice for dynamically linked binaries that need shared libraries from their original base, since the libraries are not copied; ldd on the binary tells you which.

It is also the mechanism behind borrowing certificates or timezone data from a full image into a scratch-based one. Pinning by digest rather than tag applies to the --from image exactly as it does to FROM.

"How do hadolint rules interact with a team that has a legitimate ADD? Do you disable the rule?"

I keep the rule on and suppress it inline where it is justified, so the exception is visible at the line that needs it.

hadolint's DL3020 flags ADD for non-archive sources; a line comment # hadolint ignore=DL3020 immediately above the instruction disables it for that line only, and the review sees both the ADD and the justification.

A project-wide .hadolint.yaml with the rule in ignored would hide every future misuse, which is the opposite of what a linter is for.

The other rules I expect teams to argue about are DL3008 and DL3013, which require pinned versions for apt and pip; those I enforce for runtime stages and relax for builder stages through a separate config, because the builder never ships.

The linter runs in CI on every Dockerfile change and as a pre-commit hook, and failures block the merge, since the cost of fixing a Dockerfile at review time is minutes and the cost later is a fleet rebuild.

Q43. "What is the difference between ARG and ENV, and how does each one end up in the final image?"

Reveal answer

The real test Whether you know that ARG values are not secret, even though they do not become environment variables.

Strong answer ARG declares a build-time variable that exists only while the Dockerfile is being processed. You set it with docker build --build-arg VERSION=1.4.2, and it is available to later instructions in the same stage until the stage ends.

An ARG declared before the first FROM is special: it is only usable in FROM lines, which is how you parameterise the base image tag.

ENV sets an environment variable that is baked into the image configuration, so every container started from the image sees it, and every later build instruction sees it too. ENV values persist; ARG values do not appear in the running container's environment.

The trap is that ARG is not a secrets mechanism. Every instruction that used the ARG records its expanded value in the image metadata, so docker history --no-trunc shows RUN curl -u user:$TOKEN with the real token substituted.

The layer contents may not contain the value, but the history does, and anyone who can pull the image can read it.

A second subtlety is caching: changing a build-arg value invalidates the cache from the first instruction that consumes it, not from where it was declared, so declare ARGs late and near their use.

For genuine secrets the answer is a BuildKit secret mount, RUN --mount=type=secret,id=npmrc, which exposes a file during that RUN only and leaves no trace in history or layers.

Land it ARG for values that shape the build, ENV for values the running process needs, and neither one for anything you would not paste into a public README.

Likely follow-ups
"How does an ARG declared before FROM behave, and how do you use it after FROM?"

An ARG before the first FROM lives in a global scope that only FROM instructions can see; it exists so that ARG JDK=21 then FROM eclipse-temurin:${JDK}-jre works.

Inside any stage it is undefined until you redeclare it: a bare ARG JDK after FROM, with no value, pulls the global value into that stage's scope. Forgetting the redeclaration is the classic cause of an empty variable in a RUN line.

The same redeclaration is needed per stage, since each FROM starts a fresh scope. Global ARGs also do not appear in the image history unless a stage uses them, which is slightly better for secrets but still not acceptable.

A related detail: BuildKit predefines some ARGs — TARGETPLATFORM, BUILDPLATFORM, and the proxy variables like HTTP_PROXY — and the proxy ones are deliberately excluded from the history so a build-time proxy password does not leak.

"An ENV set in the Dockerfile is being ignored at runtime in Kubernetes. Why?"

Because the pod specification's env entries override the image's environment, and the override happens per variable, so a ConfigMap or an env: block that sets the same name wins silently.

I would check the resolved environment inside the running container with kubectl exec pod -- env | sort and compare it with docker image inspect --format '{{.Config.Env}}'.

Two other common causes: the application reads a differently named variable, for example Spring Boot's relaxed binding expects SERVER_PORT rather than server.port; or an entrypoint script sets or unsets the variable before exec.

A subtle one is a value with $ in it — Docker expands ENV A=$B at build time, and Kubernetes expands $(NAME) references in value fields at pod creation, so a literal dollar sign has to be escaped in both places.

The general rule is that the image's ENV is a default, and every layer above it may override.

"Show me the leak concretely: what does docker history print for an ARG-based token?"

Suppose the Dockerfile has ARG NPM_TOKEN and RUN echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc && npm ci && rm .npmrc. Build it with --build-arg NPM_TOKEN=npm_abc123.

Then docker history --no-trunc image prints a line whose CREATED BY column is RUN |1 NPM_TOKEN=npm_abc123 /bin/sh -c echo ...: the builder records the ARG values in effect for the instruction as a |N key=value prefix, in clear text, in the image config's history array, which is pushed to the registry with the image.

Anyone with pull access sees it with one command, and crane config image | jq .history shows the same without pulling layers.

Note that the file deletion in the same RUN did keep the token out of the layer content, so a layer scan finds nothing; the history is the second channel. That is why the fix is a secret mount, not a cleverer RUN.

"When would you use ENV for something the process needs and when a mounted file instead?"

ENV for non-secret, stable defaults that describe how the image should behave everywhere: TZ=UTC, LANG=C.UTF-8, JAVA_TOOL_OPTIONS with the memory percentage, PYTHONUNBUFFERED=1, a PATH extension for a virtual environment. Those belong to the image because they would be wrong to forget in any environment.

Environment variables set at run time, through -e or the pod spec, for per-environment configuration such as database hosts and feature flags.

Mounted files for two kinds of value: secrets, because environment variables leak through docker inspect, through /proc/<pid>/environ to any process with the same UID, through crash dumps, and through child processes that inherit them; and large or structured configuration, since a YAML file is easier to review and to reload than forty variables.

Kubernetes secrets mounted as files on a tmpfs, or fetched from a secrets manager at start and never exported, is the pattern I enforce for credentials.

Q44 · Scenario. "A security scan flags that your production image contains a private package-registry token. The Dockerfile deletes the .npmrc file in a later RUN step, and the team insists the file is gone. Walk me through it."

Reveal answer

The real test Whether you understand that layers are additive and history is a second leak channel.

Strong answer I would take it in this order:

  1. Confirm the finding rather than argue. Run docker history --no-trunc image:tag and read each layer's command; if the token was passed as a build argument or written with an ENV or an echo, it appears there in clear text. Then export the image with docker save image:tag | tar -x and grep the layer tarballs, because a file deleted in a later layer still exists in full in the earlier layer where it was created. A deletion only adds a whiteout marker on top.
  2. Rank the causes. Most likely: COPY .npmrc . followed by RUN npm ci and RUN rm .npmrc, which leaves the token in the COPY layer forever. Next: ARG NPM_TOKEN used inside a RUN, which leaks through history even though no file was written. Least likely but possible: the token lives in the build context and a broad COPY . . pulled it in.
  3. Fix by rebuilding with a BuildKit secret mount: RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, passing --secret id=npmrc,src=$HOME/.npmrc at build time. The file exists only during that instruction and is never part of a layer or the history. Alternatively, do the dependency install in a builder stage and COPY --from only the results, so the leaked layer never reaches the final image.
  4. Rotate the token immediately, because every registry that ever stored the image has it.
  5. Prevent recurrence with a .dockerignore that excludes credential files, a scanner such as Trivy in CI that checks history and layers, and a review rule that any ARG carrying a credential is a blocker.

Land it Deleting a file in a later layer hides it from ls and from nobody else — secrets have to never enter a layer, which is what secret mounts and multi-stage copies are for.

Likely follow-ups
"The rebuild with a secret mount still trips the scanner. What else could be carrying the token?"

Three places I would check in order.

The build cache: if CI exports the cache with mode=max, intermediate layers from the old Dockerfile can persist in the registry cache tag, and a scanner that scans cache images finds the old layer; prune the cache ref or rotate its name.

The base image or a builder stage output: if the token was copied into node_modules as part of a lockfile URL or a .npmrc inside a package, COPY --from brings it along; grep -r 'npm_' node_modules in the builder stage finds it.

And the history rather than a layer: if --secret is used correctly there is no history entry, but a leftover ARG NPM_TOKEN that is still declared and still passed with --build-arg leaves the value in history even if no RUN uses it any more.

docker history --no-trunc and docker save | tar -x plus grep -r across the extracted layer tarballs is the definitive check.

"How does the secret mount work, and can a RUN step exfiltrate it into the image anyway?"

BuildKit mounts the secret as a file on a tmpfs inside the build container for the duration of that single RUN, at /run/secrets/<id> or the target path, from the source given on the command line or from an environment variable with env=.

The tmpfs is not part of the snapshot that becomes the layer, so nothing written to that path is captured, and the instruction's recorded command in the history contains only the mount flags, not the value.

A RUN can still leak it by copying: cat /run/secrets/token > /app/token.txt writes into the layer, and that is captured.

So secret mounts are a mechanism, not a guarantee, and the review rule is that a RUN with a secret mount must not write the secret anywhere except into a process's memory or a request.

For SSH keys the type=ssh mount is stricter, since it forwards an agent socket rather than the key file, and the key bytes never exist in the build container at all.

"Rotation is done and the image is rebuilt. What do you do about the old image that is still in the registry?"

Delete it, and assume it was already copied. Every registry that stored the image — the internal one, the CI cache, any mirror, and every node that pulled it — has the layer, so rotation is the real fix and deletion is hygiene.

Practically: list every tag and untagged manifest that references the leaked layer's digest, which registries with a layer search such as Harbor can do and otherwise a script over crane manifest for each tag can do; delete those manifests; run the registry's garbage collection so the blob is actually removed rather than just unreferenced; and prune the images from nodes and developer laptops with a broadcast.

Record in the incident that the token was live between the first push and the rotation, and check the package registry's access logs for that token over that window, because the question the security team will ask is whether it was used, not whether it was present.

"Which scanner finds this, and what does it actually look at?"

Trivy's secret scanning, which is on by default in trivy image, unpacks every layer and matches file contents against a rule set of credential patterns — AWS keys, GitHub and npm tokens, private key headers, generic high-entropy strings — and separately reads the image config to flag secrets in ENV and in the history.

Grype focuses on vulnerabilities and does not do secrets; gitleaks and TruffleHog scan repositories rather than images but can be pointed at an exported layer. Cloud registries run similar checks on push.

The important limitation is that a scanner sees a layer's content, so a file deleted in a later layer is still found, which is why the team's insistence that the file "is gone" was wrong, and a secret that appears only in the history is found only by scanners that read the config.

I run Trivy in CI with --scanners secret,vuln and fail the pipeline on any secret finding with no severity threshold, because there is no low-severity leaked credential.

Q45. "What does the VOLUME instruction really do, and why do experienced people avoid it? While you are there, what is ONBUILD for?"

Reveal answer

Strong answer VOLUME /data marks a path so that every container started from the image gets an anonymous volume mounted there automatically, unless the user mounts something else on that path.

The intention is good — data written under that path survives outside the container's writable layer — but it has three pitfalls.

First, any RUN instruction after the VOLUME line that writes into that path has its changes discarded, because the build creates a temporary container with the volume mounted and the writes go into the throwaway volume, not the image.

Second, anonymous volumes accumulate on hosts: every docker run without --rm -v leaves another unnamed volume behind, and I have seen hosts with thousands of them.

Third, it removes a choice from the operator, who may have wanted that path to be a plain directory in the container filesystem, for example in a test.

The modern practice is to document the data path in a LABEL or README and let the Compose file or the Kubernetes manifest declare the mount explicitly. ONBUILD is a trigger: ONBUILD COPY . /app in a base image does nothing when that image is built, but runs when another Dockerfile uses it as its FROM.

It was popular for language base images that wanted to "do the right thing" downstream, and it fell out of favour for the same reason VOLUME did: invisible behaviour that the downstream author did not write and cannot see without inspecting the parent image.

Land it Both instructions push decisions into a place the reader of the Dockerfile cannot see, and in infrastructure I prefer boring and explicit over clever and hidden.

Likely follow-ups
"Does BuildKit still discard writes after a VOLUME line, or is that a legacy-builder behaviour?"

The documentation still states that changes after the VOLUME declaration are discarded, and that was the legacy builder's literal behaviour, because it ran each RUN in a real container with the anonymous volume mounted.

BuildKit does not create a container with a volume; it snapshots the filesystem, so as of Aug 2026 writes after VOLUME are in practice kept in the image under BuildKit.

I would not rely on either: the runtime behaviour is the one that bites regardless of the builder, since at docker run an anonymous volume is mounted over the path and populated once from the image's content, after which the image's files at that path are irrelevant.

So a RUN that writes there after VOLUME may or may not be in the image, and it will be copied into the volume on first run and then diverge.

The safe position is to declare no VOLUME in the Dockerfile and to state the data path in documentation and the deployment manifest.

"An upstream image such as postgres declares VOLUME. What does that mean for me at run time?"

It means every docker run postgres without an explicit mount creates an anonymous volume at /var/lib/postgresql/data, named by a 64-hex-character ID, that outlives the container unless --rm was used, which removes anonymous volumes but not named ones.

Running a test database twenty times leaves twenty volumes, each with an initialised cluster, which docker volume ls -f dangling=true lists and docker volume prune removes. It also means that docker commit of a running postgres container captures nothing of the data.

For anything I care about, I mount a named volume or a bind mount at exactly that path so the anonymous one is never created, and in Compose I declare the volume at the top level so docker compose down -v can remove it deliberately.

The documented data path in the upstream README is the only reason the VOLUME line is ever useful to me.

"Is there any modern use for ONBUILD, or is it dead?"

Nearly dead, and the remaining uses are for internal base images within one organisation where the hidden behaviour is documented and owned.

The pattern is a language base image that says ONBUILD COPY pom.xml ., ONBUILD RUN mvn dependency:go-offline, ONBUILD COPY src ./src, so that each service's Dockerfile is a single FROM line.

It fails the moment a service deviates — a different layout, a multi-module build, a need for a secret mount — and the deviation cannot be expressed without abandoning the base. The official language images removed their onbuild variants years ago for that reason.

The modern replacement is a shared Dockerfile template distributed by the platform team, or a build tool that generates the image directly, such as Jib for Java, Buildpacks, or ko for Go, which reach the same "one line per service" goal with explicit, versioned behaviour.

Where I find ONBUILD in a base today, I treat it as technical debt.

"If not VOLUME, how does the image communicate which paths need persistence?"

Through metadata that tooling and humans read but that does not change runtime behaviour. A LABEL such as org.example.data-path=/var/lib/app is visible in docker inspect and can be read by a deployment generator.

The README and the example Compose file show the mount explicitly, so a newcomer copies a working definition.

In Kubernetes, the Helm chart or the manifest template owns the volume declaration, which is where it belongs, because only the deployment knows whether the path is a persistent volume, an emptyDir, or a hostPath.

I also make the application refuse to start, with a clear log line, if its data directory is not writable or is on the overlay root when a read-only root filesystem is expected, which turns a forgotten mount into a startup failure rather than silent data loss on the next redeploy.

Explicit at the deployment layer beats implicit in the image every time.

Q46. "Which Dockerfile instructions create filesystem layers, and which ones only change metadata? Include WORKDIR, USER, EXPOSE, LABEL, HEALTHCHECK, and ENV in your answer."

Reveal answer

The real test Whether you know that ordering the metadata-only instructions is free but ordering the layer instructions is where cache behaviour is decided.

Strong answer An image is a stack of read-only filesystem layers plus one JSON configuration document. Only three instructions add a filesystem layer: RUN, because it executes a command and captures whatever the filesystem changed; COPY; and ADD.

Everything else writes into the configuration document and produces an empty layer that costs nothing to pull.

WORKDIR sets the working directory for the following instructions and for the container, creating the directory if needed, and it is the correct replacement for RUN cd, which does nothing because each RUN starts a fresh shell.

USER sets the user ID for later instructions and for the running process; the user must already exist, so it usually follows a RUN that creates it.

EXPOSE is pure documentation: it records that the process listens on a port, and it publishes nothing unless you pass -P. LABEL attaches key-value metadata, and the org.opencontainers.image.* keys such as source, revision and created are what supply-chain tooling reads.

HEALTHCHECK records a command and interval that the Docker daemon runs inside the container to set the health status.

ENV adds an environment variable, and it is where you put things such as TZ=UTC and LANG=C.UTF-8, because containers otherwise run in UTC with a POSIX locale, which surprises Java date formatting and Python string handling.

The order rule that follows: put the cheap metadata anywhere, but order RUN and COPY from least-often-changed to most-often-changed, because a change invalidates every layer after it.

Land it Count the RUN, COPY and ADD lines and you have counted the layers; everything else is free, so spend your ordering effort only on those three.

Likely follow-ups
"WORKDIR creates a directory. Does that create a layer, and who owns it?"

Yes, a WORKDIR that names a directory that does not yet exist creates it, and that creation is a real filesystem change recorded in a layer — a tiny one, but a layer.

The directory is created as root with mode 755 regardless of any USER instruction before it, which means a subsequent non-root process cannot write into it; that is the reason for the pattern RUN mkdir -p /app && chown 10001:10001 /app before WORKDIR, or simply keeping WORKDIR to a path the process only reads and mounting a writable location separately.

Since BuildKit's Dockerfile 1.4 frontend, WORKDIR respects a preceding USER for ownership in some configurations, but I do not rely on that. Relative WORKDIR paths are resolved against the previous WORKDIR, so WORKDIR /app then WORKDIR src gives /app/src.

Because RUN cd is lost at the end of each RUN, WORKDIR is the only durable way to set the directory for COPY, RUN, ENTRYPOINT, and the running container.

"USER with a name failed with 'unable to find user'. Why, and what does Kubernetes need instead?"

USER resolves a name through /etc/passwd in the image at the time the instruction is processed, so USER app fails if the user was not created earlier by a RUN, or if the base is distroless or scratch and has no passwd file at all.

The fix is either a RUN that adds the user or, more robustly, a numeric UID: USER 10001 needs no passwd entry and works on any base.

Kubernetes' runAsNonRoot: true check inspects the image's configured user at pod start, and if the image says a name rather than a number, the kubelet cannot verify it is non-root without reading the image's passwd file, so it rejects the pod with "container has runAsNonRoot and image has non-numeric user".

So numeric always. A side effect of a numeric user with no passwd entry is that tools reading the home directory or the username, such as Git or some JVM libraries, may complain; setting HOME=/tmp or adding the passwd line covers that.

"What are the LABEL keys that tooling actually reads, and how do you populate them from CI?"

The OCI annotation keys under org.opencontainers.image.: source for the repository URL, revision for the commit SHA, version for the release, created as an RFC 3339 timestamp, title, description, licenses, vendor, and base.name and base.digest for the base image.

GitHub links a package to its repository by reading source; Renovate and some scanners use base.digest to know what to update; provenance verifiers compare revision against what the build claimed.

In CI I pass them as build arguments and set them in the last stage — ARG GIT_SHA then LABEL org.opencontainers.image.revision=$GIT_SHA — or more simply with docker buildx build --label org.opencontainers.image.revision=$GIT_SHA, which needs no Dockerfile change; the docker/metadata-action generates the full set automatically from the Git context.

Because LABEL is metadata, changing it does not invalidate any filesystem layer as long as it comes last.

"HEALTHCHECK in the Dockerfile versus probes in Kubernetes — should an image carry one at all?"

My rule is that the image carries a HEALTHCHECK only if the image is meant to be run under Docker or Compose, where it is the only health mechanism and drives depends_on: condition: service_healthy.

Kubernetes ignores the image's HEALTHCHECK entirely; the kubelet runs its own liveness, readiness, and startup probes defined in the pod spec.

Carrying a HEALTHCHECK in an image that only ever runs under Kubernetes has one small cost, a probe process forked every 30 seconds on Docker hosts such as developer laptops that do run it, and one real risk, which is that people assume it is doing something in production.

For a template used both ways I include it with generous settings and document that Kubernetes probes supersede it; HEALTHCHECK NONE in a child image disables an inherited one. The design principle is that the health definition should live wherever the restart decision is made.

Q47 · Scenario. "A container keeps flipping to unhealthy and an orchestrator restarts it, but the application answers requests perfectly the whole time. The HEALTHCHECK is curl -f http://localhost:8080/actuator/health. What is going on?"

Reveal answer

Strong answer I would diagnose it like this:

  1. Read the health-check output, which most people never do: docker inspect --format '{{json .State.Health}}' name shows the last five probe results with their exit code and captured output. That alone usually names the cause.
  2. Rank the likely causes. First, curl is not installed in the image, which is common in distroless or slim bases; the probe fails with exit code 127, "command not found", and Docker treats any non-zero exit as unhealthy. Second, the app binds to a different interface or port, for example only to an IPv6 loopback while curl tries IPv4, or to port 8081 for management endpoints in Spring Boot when management.server.port is set. Third, the probe's timeout is shorter than the endpoint's response time; the default is 30 seconds, but a health endpoint that checks a slow database can exceed a tightened --timeout=2s. Fourth, the health endpoint aggregates downstream checks, so a flaky dependency marks the whole container unhealthy although request serving is fine. Fifth, the start period is too short for a JVM, so the first probes fail during startup and count toward the retry threshold.
  3. Fix accordingly: use a probe binary the image actually has, such as Spring Boot's own liveness endpoint hit by a tiny static binary or a wget --spider in busybox-based images; point liveness at /actuator/health/liveness, which does not include dependencies; and set --start-period=60s --interval=15s --timeout=5s --retries=3.
  4. Prevention: distinguish liveness from readiness. Liveness should only fail if the process must be restarted; readiness reflects whether it should receive traffic. Docker's HEALTHCHECK is a single concept, which is why on Kubernetes you leave HEALTHCHECK out and define separate probes there, as E10 covers.

Land it A health check is a program with its own dependencies and its own timeouts — when it disagrees with reality, inspect its output before you touch the application.

Likely follow-ups
"You fixed the probe binary and the container still flips unhealthy under load. What next?"

Then the probe is telling the truth about something, and I want to know which resource it is reporting on.

Under load a Spring Boot health endpoint competes for the same Tomcat thread pool as the traffic; if all 200 threads are busy, the probe waits in the accept queue and times out at the configured limit, so the container is marked unhealthy while every real request is merely slow.

The fix is to move the management endpoints to a separate port with management.server.port=8081, which gets its own connector and thread pool, and to point the probe there.

Second, CPU throttling: a container at its cpu.max quota pauses all threads including the probe's, so cpu.stat's nr_throttled climbing alongside the failures is the signature, and raising the limit or lowering parallelism fixes it.

Third, the health endpoint itself doing real work — a database round trip — that is slow under load; the liveness endpoint should check nothing external. docker inspect's health log with timestamps against the load curve is the evidence.

"What exactly does Docker do when a container becomes unhealthy? Does it restart it?"

Nothing, by itself. Docker Engine records the state — starting, healthy, or unhealthy — in docker inspect and emits a health_status event, and that is all; the restart policy reacts to the process exiting, not to health.

What acts on it is whatever sits above: Docker Swarm replaces unhealthy tasks, Compose's depends_on with condition: service_healthy waits for it before starting dependents and, with restart: true on the dependency, restarts them when it changes, and third-party tools such as autoheal watch the event stream and restart containers.

So in the scenario the orchestrator is doing the restarting, and its policy may be more aggressive than the probe deserves.

Kubernetes is different in kind: a failing liveness probe does restart the container after failureThreshold misses, and a failing readiness probe only removes the pod from Service endpoints, which is why splitting the two matters there.

"Give me the exact numbers you would set for a JVM service and justify each."

For Docker: HEALTHCHECK --start-period=60s --interval=15s --timeout=5s --retries=3 CMD [...].

Start period of 60 seconds because a Spring Boot service on a throttled CPU can take 30 to 45 seconds and failures during the start period do not count toward retries; with --start-interval=2s, available since Engine 25, probes run more often during that window so the container is marked healthy quickly once it is up.

Interval 15 seconds as a balance between detection latency and probe cost. Timeout 5 seconds, which is long enough for a JVM under garbage collection pause and short enough that a hung process is noticed; the default 30 seconds is too generous.

Retries 3, so 45 seconds of consecutive failure is needed before the state flips, which absorbs a single slow GC or a brief dependency blip.

In Kubernetes the equivalents are a startup probe with failureThreshold: 30 and periodSeconds: 2, a liveness probe every 15 seconds with threshold 3, and a readiness probe every 5 seconds with threshold 1 so traffic is pulled fast.

"How do you probe a distroless image that has neither curl nor wget?"

Three options. Copy a tiny static probe binary into the image: COPY --from=ghcr.io/grpc-ecosystem/grpc-health-probe:v0.4.28 /ko-app/grpc-health-probe /bin/ for gRPC, or a small Go or C HTTP checker of a few hundred kilobytes for HTTP, and point HEALTHCHECK at it in exec form.

Use the runtime that is already there: for a JVM, CMD ["java", "-cp", "/app", "HealthCheck"] with a ten-line class that opens the URL — it costs a JVM start per probe, which is 100 milliseconds of CPU every interval, acceptable at 15-second intervals.

Or, in Kubernetes, use an httpGet probe, which the kubelet performs from outside the container over the pod network, so the image needs nothing at all; that is the best answer and one more reason to leave HEALTHCHECK out of Kubernetes-only images.

The one thing not to do is add a shell and curl to the distroless image, which throws away its main benefit.

Q48 · Design. "Design the Dockerfile for a Spring Boot 3.5 service that a team of twenty will copy as their template. Show me the file and defend every line."

Reveal answer

The real test Whether the file you write reflects cache behaviour, non-root execution and JVM container flags at the same time.

Strong answer Requirements I assume: builds run in CI with BuildKit, the artefact is a fat jar produced by Maven, images must run as non-root, and the same image must work locally and in Kubernetes. The design is a two-stage build. The first stage extracts the jar into Spring Boot's layers so that dependencies, which change rarely, sit below application classes, which change on every commit. The second stage copies those layers in order of volatility onto a JRE-only base image.

Dockerfile
# syntax=docker/dockerfile:1
FROM eclipse-temurin:21-jdk-jammy AS builder
WORKDIR /build
COPY target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination extracted

FROM eclipse-temurin:21-jre-jammy
ENV TZ=UTC LANG=C.UTF-8 \
    JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom"
RUN groupadd --system app && useradd --system --gid app --uid 10001 app
WORKDIR /app
COPY --from=builder --chown=app:app /build/extracted/dependencies/ ./
COPY --from=builder --chown=app:app /build/extracted/spring-boot-loader/ ./
COPY --from=builder --chown=app:app /build/extracted/snapshot-dependencies/ ./
COPY --from=builder --chown=app:app /build/extracted/application/ ./
USER 10001
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Defending the lines: the syntax directive unlocks current BuildKit features. The builder uses a full JDK because extraction needs it, and the runtime uses the JRE image, which is roughly 100 MB smaller. JAVA_TOOL_OPTIONS is read by every JVM launch, so operators can still override with their own -e. MaxRAMPercentage=75 sizes the heap from the container limit and leaves room for metaspace and threads. ExitOnOutOfMemoryError turns a Java out-of-memory into a clean exit so the orchestrator restarts a healthy process instead of a wedged one. The numeric UID satisfies Kubernetes runAsNonRoot, which cannot verify a name. The four COPY lines mean a code-only change rebuilds and pushes only the last, small layer. Trade-offs: I did not use a distroless base because on-call engineers need a shell during incidents, and I did not use Alpine because of musl issues with the JVM. I would not add a HEALTHCHECK here because Kubernetes probes replace it. See E4 for the build side of the layered jar.

Land it A template Dockerfile earns its keep when a one-line code change costs a one-layer push — everything else in the file exists to keep that true safely.

Likely follow-ups
"The requirement changes: the image must pass a scanner with zero critical findings and be under 150 MB. What changes in the file?"

The runtime base and the JRE. I would switch the second stage to a distroless or Wolfi Java base, gcr.io/distroless/java21-debian12:nonroot or cgr.dev/chainguard/jre:latest pinned by digest, which removes the shell, package manager, and most of the packages the scanner flags; the Chainguard image typically reports zero findings because it is rebuilt daily. That gets a Spring Boot image to roughly 130 to 160 MB. To be safely under 150, I add a jlink stage: run jdeps --print-module-deps --ignore-missing-deps --recursive --multi-release 21 --class-path 'extracted/dependencies/BOOT-INF/lib/*' extracted/application/BOOT-INF/classes to get the module list, build a runtime with jlink --add-modules $MODS --strip-debug --no-man-pages --no-header-files --compress zip-6 --output /jre, and copy it onto a debian:12-slim or distroless static base, giving about 110 MB. The user creation moves to the builder or uses the base's nonroot user, since there is no useradd. The trade is no shell in production, so the debug-container workflow must be in place first.

"Why extract the layers in a Docker stage instead of in the Maven build?"

Because it keeps the Dockerfile self-contained and the CI job simple.

The Maven build produces one artefact, the fat jar, which is what every other consumer — the artefact repository, local runs, integration tests — already expects; extracting inside the Dockerfile means no Maven plugin configuration, no extra directory in target/, and the same Dockerfile works when a developer builds locally from a jar they just packaged.

It also pins the extraction to the same JDK version that runs it, since both stages use the same base family.

The cost is a JDK stage that exists only for a two-second extraction, which BuildKit caches by the jar's checksum so it reruns only when the jar changes.

The alternative, running spring-boot:build-image with Buildpacks or Jib, removes the Dockerfile entirely and is a fine choice for teams that do not want to own one; for a template that twenty teams read and modify, an explicit Dockerfile is easier to reason about.

"Why ExitOnOutOfMemoryError rather than letting the JVM keep running or dumping the heap?"

Because in an orchestrated environment a process that has thrown OutOfMemoryError is unreliable but alive, which is the worst state: it passes a liveness probe, stays in the load balancer, and fails requests unpredictably, sometimes for hours.

-XX:+ExitOnOutOfMemoryError makes the JVM exit immediately with a non-zero code, the orchestrator sees the exit and restarts a fresh process, and the failure is visible in restart counts.

If I also want the evidence, I add -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps/ with a volume, understanding that a heap dump of a 3 GB heap takes tens of seconds and gigabytes of disk during which the process is frozen, so I enable it on a canary rather than the whole fleet.

-XX:+CrashOnOutOfMemoryError produces a native crash report instead, useful for native memory investigations. All three are set through JAVA_TOOL_OPTIONS so an operator can change the policy without rebuilding.

"You have an hour to make this template work for twenty teams today. What do you leave out?"

I would leave out the jlink stage, the distroless option, CDS training runs, and the build-argument parameterisation of the base, and ship exactly the two-stage file with the JRE base, the layered COPY lines, the numeric user, and the JAVA_TOOL_OPTIONS defaults.

Those four things are what every service needs and what breaks production when missing — cache behaviour, non-root, and container-aware heap.

I would spend the remaining minutes on a .dockerignore shipped alongside the Dockerfile, since without it half the teams will copy target/ and .git into the builder, and on a one-paragraph README stating the two commands to build and run locally.

Startup optimisation and hardening are follow-ups with measurable goals, and they should be added to the template once, centrally, rather than by each team.

The check before sending: build it, run it with --memory=512m, confirm the heap line in the log, stop it and confirm exit code 143 in under two seconds.

Q49. "Why is RUN apt-get update on its own line considered a bug, and why does deleting files in a later RUN not make the image smaller?"

Reveal answer

Strong answer Both questions come from the same fact: each RUN produces one immutable layer, and the final image is the stack of all of them. Put apt-get update on its own line and its layer, the package index, is cached the first time it runs.

Months later you add a package to the following apt-get install line; that line changes, so it re-runs, but the update line did not change, so the build reuses the stale index from months ago.

The install then fails on missing package versions, or worse, silently installs old packages with known vulnerabilities.

The fix is the single-RUN idiom: RUN apt-get update && apt-get install -y --no-install-recommends curl=8.5.0-2ubuntu10.6 && rm -rf /var/lib/apt/lists/*, so the index, the install and the cleanup all live and die together. The second question is the same mechanism seen from the size side.

If layer three writes 300 MB of package cache and layer five deletes it, the image still contains layer three in full; layer five only adds a whiteout entry telling the union filesystem to hide those paths. docker history will show the 300 MB layer plainly.

Cleanup therefore has to happen in the same RUN that created the mess, or the whole mess has to happen in a builder stage whose layers are never copied to the final image.

BuildKit's --mount=type=cache,target=/var/cache/apt is the modern refinement: the cache lives outside the layer entirely, is reused across builds, and never bloats the image.

Land it A layer is a photograph, not a diff you can retouch later — anything you do not want in the picture has to be cleaned up before the shutter closes.

Likely follow-ups
"With a cache mount for apt, do I still need rm -rf /var/lib/apt/lists in the same RUN?"

No, because with --mount=type=cache,target=/var/lib/apt the lists directory is the cache mount, which is not captured in the layer; and with --mount=type=cache,target=/var/cache/apt the downloaded packages are likewise outside.

What I do need is to stop Debian's default cleanup from deleting the cache so the mount is useful: rm -f /etc/apt/apt.conf.d/docker-clean once, plus echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache.

The stale-index problem is also handled differently: since the RUN still contains apt-get update && apt-get install as one instruction, any change to the install list reruns the update, and the cache mount makes that update cheap because unchanged index files are not re-downloaded.

What still applies is --no-install-recommends, because recommended packages land in the layer as real files, and deleting documentation under /usr/share/doc if size matters, since dpkg installs it regardless.

"The pinned version curl=8.5.0-2ubuntu10.6 disappeared from the repository and the build broke. Now what?"

This is the known cost of pinning on Debian and Ubuntu, whose repositories keep only the current version of each package; when a security update ships, the old one is removed and the pinned install fails with "version not found". Three responses.

Move the pin forward, which a bot such as Renovate can do for apt versions in Dockerfiles, so the failure becomes a pull request instead of a broken build.

Pin the repository snapshot rather than the package: snapshot.debian.org and Ubuntu's snapshot service let you point sources.list at a dated snapshot, so every version present on that date stays available forever and the whole set is pinned at once.

Or accept a floating install for the builder stage and pin only in runtime images, where reproducibility matters.

I favour the snapshot approach for golden base images and version-pinning through a bot for everything else, and I treat the breakage as the system working: it told me a security update happened.

"How does the same reasoning apply to pip and npm caches?"

Identically, with different directories.

pip caches wheels under /root/.cache/pip, so RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt reuses downloads across builds and never stores them in the image; without the mount, people wrote pip install --no-cache-dir to avoid bloating the layer, which fixes size but downloads everything every build.

npm's cache lives at /root/.npm, and npm ci with a cache mount there is the equivalent; uv uses /root/.cache/uv. Maven's /root/.m2/repository is the JVM case.

The layer-size reasoning is the same: the installed packages go into the layer, the download cache does not, and any cleanup must happen in the same RUN if there is no mount.

The ordering reasoning is also the same: copy the lockfile alone, install with the mount, then copy the source, so the install layer is keyed on the lockfile and survives code changes.

"Is there a way to have one RUN per logical step for readability without paying a layer per step?"

Heredocs. Since Dockerfile syntax 1.4, a single RUN can hold a multi-line script: RUN <<EOT followed by lines of shell and a closing EOT, run under sh -e so a failing line stops the build.

It reads like a script, with comments, and produces one layer, which removes the ugly backslash-and-ampersand chains that made people split steps in the first place. The interpreter can be chosen with RUN <<EOT bash or a shebang line, and multiple heredocs can feed one command.

It also works for COPY, writing a file from inline content: COPY <<EOT /etc/app/config.yaml and then the YAML. The one thing heredocs do not change is caching: the whole heredoc is the instruction's text, so any edit inside it reruns the step.

For that reason I keep the slow, stable work — package installs — in one heredoc RUN and the fast, frequently edited work in a separate later RUN.

Drill · Build cache, BuildKit & reproducibility

These questions test whether you can predict what the cache will reuse before you run the build, and whether you can make a build that is fast in CI and identical on every machine.

Q50. "State the exact rules the build cache uses to decide whether an instruction can be reused."

Reveal answer

The real test Whether you know that RUN is cached by its text while COPY is cached by content, because that asymmetry explains most surprising rebuilds.

Strong answer The builder walks the Dockerfile from the top and, for each instruction, asks whether it already has a layer produced by the same instruction on top of the same parent layer. The rules for "same" differ by instruction.

For RUN, the comparison is the command string, byte for byte; Docker does not execute the command to see whether the result would differ, so RUN apt-get update matches forever and RUN git clone matches even after the repository has changed.

For COPY and ADD, the builder hashes the contents and the metadata of the source files — content checksum and permissions, but not modification times — and any change misses the cache.

For metadata instructions such as ENV and LABEL, the value string is compared, and a changed ENV invalidates everything after it because later RUNs could read it.

The first miss is decisive: once one instruction misses, every following instruction is rebuilt regardless, because its parent layer is new. That is why ordering matters more than anything else. --no-cache ignores all cached layers for the build.

--cache-from tells the builder to consider layers from a named image, typically the previous CI build, as candidates; with BuildKit this is generalised into cache backends so the cache can live in a registry.

BuildKit also skips stages whose outputs are not needed by the target, and runs independent stages in parallel, so cache misses in one stage do not always slow the others.

Land it Predicting a rebuild is a two-question exercise: which is the first instruction whose key changed, and is everything expensive above it or below it?

Likely follow-ups
"RUN git clone is cached forever. How do you force a step to re-run when a remote changes, without --no-cache for everything?"

Put something that changes into the instruction's key. The clean way is a build argument whose value is the thing that changed: ARG GIT_REF then RUN git clone --branch $GIT_REF ..., with CI passing the commit SHA, so the key changes exactly when the source does.

A cruder version is a cache-busting ARG like ARG CACHEBUST=1 declared just above the step and passed a timestamp when a refresh is wanted, which invalidates that step and everything below it but nothing above.

Better than either is not cloning inside the build at all: use ADD https://github.com/org/repo.git#<sha> /src, which BuildKit supports for Git URLs with the ref in the fragment and keys the cache on it, or fetch the source into the build context before the build.

For downloads, ADD --checksum serves the same purpose. The principle is that the cache is correct as long as the key captures the inputs, so make the inputs explicit rather than fighting the cache.

"Does file modification time affect COPY caching, and what about file ownership on the host?"

Modification time does not; BuildKit hashes content and mode, so a git checkout that rewrites files with new timestamps but identical content still hits the cache, which is why CI runs on fresh clones cache correctly. The legacy builder had the same rule.

Ownership on the host is also ignored, since files land as root in the image regardless.

What does affect the key: the mode bits, so a file that becomes executable is a change; the file's path relative to the context; and the set of files, so an added or removed file under a copied directory is a miss.

Symlinks are hashed as links, not as their targets.

One trap is generated files: a build that writes a version file into the context before docker build, with a timestamp inside the file, changes content every run and busts the cache from that COPY downward; the fix is to derive such values from build arguments applied after the expensive steps.

"How do you predict from a Dockerfile alone what a one-line source change will rebuild?"

I read it top to bottom asking two questions per instruction: does its key depend on the changed file, and is it before or after the first instruction that does.

For a well-ordered file: FROM is unchanged; COPY pom.xml is unchanged; RUN mvn dependency:go-offline is unchanged; COPY src includes the changed file and misses; every subsequent instruction rebuilds regardless. So a source change costs a compile and a package, not a dependency download.

For a badly ordered file with COPY . . first, everything after it rebuilds, including the download. For metadata instructions, an ENV or LABEL change above expensive RUNs invalidates them even though it writes nothing.

I confirm the prediction with docker build --progress=plain and read the CACHED markers; the first uncached step should be the COPY I predicted. Making that prediction quickly is the real skill, and the ordering rule — slowest-changing at the top — follows from it.

"What happens to caching in multi-stage builds when a stage that the target does not use changes?"

Nothing, under BuildKit.

It first resolves which stages the target depends on by following COPY --from and FROM stage references and builds only those; an unreferenced stage — a test stage, a lint stage — is never even evaluated when building the default target, so its changes cannot invalidate anything.

Stages that are referenced are built in parallel where they do not depend on each other, so a change in one does not delay the others.

Within the dependency graph, a stage's cache key includes the keys of the stages it copies from, so a change in the builder stage's output invalidates the COPY --from in the runtime stage but not the runtime stage's earlier instructions such as its own package installs.

The legacy builder built every stage in file order regardless of use, which is one of the reasons multi-stage files felt slow before BuildKit. --target selects which stage is the root of this analysis.

Q51 · Scenario. "Every CI build of a Java service reinstalls all dependencies from scratch even though pom.xml has not changed in weeks. The Dockerfile starts with COPY . . then runs mvn package. Diagnose and fix."

Reveal answer

Strong answer In diagnosis order:

  1. Confirm the symptom in the build log with --progress=plain: the COPY . . step shows as executed rather than CACHED on every build, and every step after it follows.
  2. Identify why the COPY misses. COPY is cached by the checksum of everything it copies, and COPY . . copies the whole context, so any changed file, including the source file you just committed, changes the checksum. That is expected and unavoidable; the mistake is that the expensive dependency download sits after it.
  3. Check secondary causes that make even unchanged builds miss: a .dockerignore that fails to exclude target/, .git/, or IDE files, so build outputs from the previous run change the context; and CI runners that start with an empty local cache, so nothing is reusable without a remote cache.
  4. Fix by splitting the COPY into stages of volatility. First COPY pom.xml . and RUN mvn dependency:go-offline -B; that layer's key is the checksum of pom.xml alone and stays cached for weeks. Only then COPY src ./src and RUN mvn package -o -DskipTests. Add a BuildKit cache mount, RUN --mount=type=cache,target=/root/.m2 mvn package, so even when the pom changes, only the new artefacts are downloaded. Add a proper .dockerignore.
  5. For CI, export the cache to the registry with docker buildx build --cache-to type=registry,ref=registry/app:cache,mode=max --cache-from type=registry,ref=registry/app:cache, so fresh runners still hit.
  6. Prevention: a build-time budget in CI that fails the pipeline if the image build exceeds, say, three minutes, which catches regressions in ordering before they become normal.

Land it Copy the manifest, resolve dependencies, then copy the source — that three-line reordering is worth more build time than any hardware upgrade.

Likely follow-ups
"You split the COPY and added the cache mount, and the dependency step still runs every build in CI. What next?"

Then the runner has no cache to hit, and I would verify that before touching the Dockerfile again.

--progress=plain will show the COPY pom.xml step as not CACHED on a run where the pom did not change, which only happens when the builder's cache is empty — a fresh ephemeral runner — or when the parent layer changed, which means the base image tag resolved to a new digest.

For the first, the fix is the registry cache: confirm the --cache-from reference actually exists with docker buildx imagetools inspect registry/app:cache, that the build has pull permission on it, and that --cache-to was run at least once with mode=max, because mode=min exports only the final stage and the builder stage's dependency layer would never be in the cache.

For the second, pin the base by digest. A third, quieter cause is a multi-module project where the split COPY missed a child module's pom, so go-offline resolves a different set each time; copy every pom.

"mvn dependency:go-offline does not download everything. What does it miss and how do you handle it?"

It resolves the dependencies and plugins declared in the poms, but it misses plugin dependencies that are only resolved when the plugin runs, some test-scoped artefacts, and anything a plugin fetches dynamically, so the later mvn package -o in offline mode can fail on a missing artefact.

Two remedies.

Use mvn -B dependency:resolve dependency:resolve-plugins together, or better, run the actual build goal against an empty source tree in the dependency stage — mvn -B package -DskipTests with only the poms copied compiles nothing but exercises every plugin and pulls exactly what the real build needs.

Or drop the strict offline flag and rely on the cache mount for /root/.m2, so any artefact that go-offline missed is downloaded once and cached across builds; this is what I do in practice, because it degrades gracefully.

Gradle has the same problem in a different shape, and there the cache mount on /root/.gradle plus a resolve-all task is the equivalent.

"What is the fastest possible CI build for a code-only change, and what is left in it?"

With everything in place — split COPY, cache mount, registry cache with mode=max, layered jar, and tests moved out of the image build — a code-only change costs: a few seconds to pull the cache manifest and the base layers on a fresh runner, a Maven compile of the changed module, packaging the jar, extracting layers, and a push of one small application layer.

For a mid-sized Spring Boot service that is 60 to 90 seconds, of which the compile is most.

What remains and cannot be cached is the compile itself, which is why the next lever is the build tool's own incremental cache: Gradle's remote build cache or Maven's build cache extension, keyed on source hashes, can serve the compile output for unchanged modules and cut the remaining minute to a few seconds.

Beyond that is diminishing returns; runner start time and the registry round trips dominate.

"How do you keep this Dockerfile pattern from drifting back over the next year?"

With a measurement and a template.

The measurement is a CI metric: the build job records the number of CACHED steps and the total build time, and a threshold alert fires when a build that touched only src/ takes longer than, say, three minutes or shows the dependency step uncached.

That catches the day someone adds a file to the early COPY or inserts an ENV above the dependency stage.

The template is a shared Dockerfile in the platform repository that services include through a build argument or simply copy, with a linter rule — hadolint plus a small custom check — that flags COPY . . appearing before any RUN containing mvn or gradle.

And a short document with the reasoning, because engineers preserve rules they understand and delete rules they do not. Review of Dockerfile changes by the platform team for the first months helps until the pattern is habitual.

Q52. "Explain multi-stage builds: what --target and COPY --from give you, and one non-obvious way to use a stage."

Reveal answer

Strong answer A multi-stage build is a Dockerfile with several FROM lines, each starting a named stage, where only the last stage becomes the output image.

Every stage has its own layer stack, so anything installed or generated in an earlier stage stays out of the final image unless you copy it across explicitly with COPY --from=stagename /path /path.

This is how a Java build that needs a 400 MB JDK, Maven, and a test toolchain produces a 250 MB runtime image with only a JRE and the jar.

--from also accepts an external image, so COPY --from=busybox:1.36 /bin/busybox /bin/ borrows one file from another image without inheriting its base.

docker build --target builder stops at a named stage and makes it the output, which is how the same Dockerfile produces a development image with the toolchain and a production image without it, and how CI can run tests inside the builder stage by targeting it.

With BuildKit, stages that do not contribute to the target are skipped entirely, and independent stages run in parallel, so a test stage and a lint stage that both FROM the builder finish concurrently.

The non-obvious use is a scratch stage as a build output: FROM scratch AS report followed by COPY --from=test /build/reports /, and then docker build --target report --output type=local,dest=./reports writes those files to the host without running a container.

Another is a stage used purely as a cache anchor, where the base image is pinned once and every other stage says FROM base.

Land it Think of stages as functions with a return value that you copy out, and the final image is the one whose return value ships.

Likely follow-ups
"How do you run the tests inside the build without making the production image depend on them?"

Add a test stage that depends on the builder and produces an output, and make the production stage not depend on it. For example FROM build AS test with RUN mvn test, then FROM scratch AS test-results with COPY --from=test /build/target/surefire-reports /.

The runtime stage copies only from build. CI runs two builds: docker build --target test-results --output type=local,dest=./reports ., which executes the tests and writes the reports to the runner, and docker build --push -t registry/app:sha ., which never evaluates the test stage.

Because both share the builder stage's cache, the compile happens once. The reports appear as ordinary files for the CI system's test summary.

The alternative that many teams pick, running tests in the CI job outside Docker, is fine too; the in-Docker version guarantees the tests ran against the same compiled artefact and the same JDK as the image.

"What does the --output flag do, and what output types exist beyond an image?"

--output tells BuildKit what to do with the result of the target stage instead of loading it into the image store.

type=local,dest=./out writes the stage's filesystem to a directory, which is how a build produces a binary, a report, or a generated site without a container ever running. type=tar,dest=out.tar streams it as an archive. type=image,name=...,push=true is the normal image output with options such as compression=zstd and oci-mediatypes=true.

type=oci,dest=image.tar produces an OCI layout tarball for air-gapped transfer, and type=docker produces a docker load-compatible tarball. type=registry is shorthand for image with push. type=cacheonly builds and caches without exporting, useful for warming.

The pattern of a FROM scratch stage plus type=local turns Docker into a portable, cached build system for artefacts of any language, which is the most under-used feature in BuildKit.

"Can two stages share a base and be built in parallel, and does that speed up a Java build?"

Yes: stages that do not depend on each other run concurrently, up to BuildKit's parallelism, and a stage referenced by several others is built once.

For a Java service the useful parallelism is between the application build and independent work — a stage that downloads a static tool, a stage that builds a frontend with Node, a stage that generates documentation — which then all feed the runtime stage.

The Maven build itself is one stage and does not parallelise across stages, though Maven's own -T 1C parallel build helps within it.

What I have seen actually help is splitting a multi-module project into a dependency stage and per-module stages only when modules are independent, which is rare.

The bigger gains are usually from parallel test and lint stages during CI, which run alongside the main build rather than after it, and from a remote builder with more CPUs than the CI runner. --progress=plain shows the stages interleaving, which is the proof.

"What is a cache anchor stage and when is it worth the extra lines?"

It is a stage whose only job is to pin an image once so every other stage refers to it by name: FROM eclipse-temurin:21-jdk-jammy@sha256:... AS jdk, then FROM jdk AS build and FROM jdk AS test.

The benefits are that the digest appears once and a bump is one line, that a bot such as Renovate can update it in one place, that every stage is guaranteed to use the same base and therefore share layers, and that the runtime stage can say FROM jre where jre is another anchor.

It also lets a build argument select the base for the whole file — ARG BASE then FROM ${BASE} AS jdk — which is how an organisation-wide golden image is injected without editing each Dockerfile.

It costs two lines per base, and it is worth it in any Dockerfile with more than two stages or in any file that will be copied by other teams.

Q53. "What does BuildKit add over the legacy builder? Name secrets, SSH mounts, cache mounts, heredocs, and the syntax directive, and say when you would use each."

Reveal answer

The real test Whether you can write the mount flags from memory, because interviewers know that people who have used them can.

Strong answer BuildKit is the build engine that has been the default in Docker since Engine 23 and is at version 0.3x in 2026.

It builds a dependency graph of the Dockerfile instead of running lines top to bottom, which gives parallel stages, skipped unused stages, and finer cache keys.

The line # syntax=docker/dockerfile:1 at the top pins the Dockerfile frontend, the parser, to the current stable 1.x series so new instructions work regardless of the daemon's bundled version. The mount flags on RUN are the practical wins.

--mount=type=cache,target=/root/.m2 mounts a persistent directory that survives between builds but never enters a layer, ideal for package manager caches. --mount=type=secret,id=token exposes a file at /run/secrets/token for that one RUN, given at build time with --secret id=token,src=./token.txt or from an environment variable with env=TOKEN.

--mount=type=ssh forwards the host's SSH agent so a RUN can clone private Git repositories, with --ssh default at build time, and no key ever touches the image. --mount=type=bind,from=builder,source=/out,target=/in reads from another stage without a copy.

Heredocs let you write a multi-line script in place and are far more readable than backslash-continued shell.

Dockerfile (fragment with BuildKit mounts)
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    --mount=type=secret,id=pip_index_url,env=PIP_INDEX_URL \
    pip install --requirement requirements.txt
RUN <<EOT
set -eux
useradd --system --uid 10001 app
mkdir -p /app/data
chown -R app:app /app
EOT
USER 10001

Land it The three mounts remove the three classic Dockerfile crimes — bloated caches, leaked credentials, and copied SSH keys — so I treat any Dockerfile without them as legacy.

Likely follow-ups
"What does sharing=locked on a cache mount do, and when do you need shared or private instead?"

The sharing option controls what happens when two builds want the same cache mount at the same time, which occurs with parallel stages or concurrent CI jobs on one builder.

shared, the default, lets all of them use the directory concurrently, which is fine for caches that tolerate concurrent readers and writers, such as pip's wheel cache or Maven's repository, where files are written atomically by name.

locked serialises access, so a second build waits until the first RUN finishes; apt needs this because its lock file and database are corrupted by concurrent updates, and Go's module cache is happier with it.

private gives each concurrent user its own copy of the directory, so no waiting and no sharing, at the cost of duplicated downloads; it suits caches with stateful indexes that break when two writers interleave.

An id= lets two mounts with different targets share one cache, and from= can seed the cache from a stage.

"The build needs a private Git dependency. Show the SSH mount end to end and say what never touches the image."

In the Dockerfile: RUN --mount=type=ssh mkdir -p ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts && git clone git@github.com:org/private-lib.git.

On the build machine, the developer or the CI job has an SSH agent running with the deploy key loaded, ssh-add ~/.ssh/deploy_key, and runs docker buildx build --ssh default ..

BuildKit forwards the agent socket into the build container for that RUN only, at a path it sets in SSH_AUTH_SOCK; the private key bytes never enter the container, only signing requests go across the socket.

Nothing about the key is in the layer, the history, or the cache. The known_hosts entry is written into the layer, which is harmless. In GitHub Actions the agent is set up with the webfactory/ssh-agent action from a secret.

The one mistake I see is baking a deploy key with COPY and deleting it later, which is the .npmrc leak in another form.

"Why pin the syntax directive, and what happens on a daemon whose bundled frontend is older?"

The first line # syntax=docker/dockerfile:1 tells BuildKit to fetch the Dockerfile frontend — the parser and instruction implementation — as an image from the registry and use it instead of the version compiled into the daemon.

Pinning to 1 tracks the latest stable 1.x, so a feature such as heredocs, COPY --parents, or ADD --checksum works on any daemon that supports BuildKit at all, regardless of how old its bundled frontend is; pinning to 1.7 fixes an exact release for reproducibility.

Without the directive, an older daemon in CI rejects the new syntax with a parse error while a laptop on the latest Docker accepts it, which is one of the classic works-on-my-machine cases.

The cost is one registry pull of a small image, cached thereafter, and the requirement that the builder can reach Docker Hub or a mirror; air-gapped builders need the frontend image mirrored and referenced by its internal name.

"What else has BuildKit added recently that you would actually use?"

Several things as of Aug 2026. COPY --parents preserves directory structure for globbed sources, which finally makes copying every pom.xml from a multi-module tree one line: COPY --parents ./**/pom.xml ./. COPY --exclude filters within a COPY without a separate ignore file.

RUN --network=none proves a step needs no network, and --security=insecure exists for the rare privileged build step on a builder configured to allow it. Build checks, run with docker build --check, lint the Dockerfile for known problems such as casing and undefined variables.

The docker buildx bake command builds a graph of targets from an HCL or JSON file, which replaces a Makefile of docker build commands for multi-image repositories. Attestations, --sbom=true --provenance=true, attach an SBOM and SLSA provenance to the image.

And docker buildx history records past builds for inspection. Each of these is a small quality-of-life gain, and together they make the legacy builder look like a different tool.

Q54 · Scenario. "The service image is 1.4 GB and a CI build takes 12 minutes. The team says 'that is just how Java images are'. Where do you look first, and what do you expect to get it down to?"

Reveal answer

The real test Whether you separate the two problems — size and time — because they have different causes and different fixes.

Strong answer I would work through it in this order:

  1. Measure before touching anything. docker history image:tag shows the size of every layer, and a tool such as dive shows which files each layer added. For time, run the build with --progress=plain and note the wall time of each step and whether it says CACHED.
  2. Rank the size causes. A single-stage build shipping the JDK, Maven and its .m2 cache, which alone accounts for 600 to 800 MB. A full Ubuntu or Debian base with recommended packages installed. Build artefacts and test reports copied in by COPY . .. Package caches deleted in a later layer, which does not reclaim space.
  3. Rank the time causes. Dependencies re-downloaded every build because the COPY is too broad or CI has no persistent cache. Tests running inside the image build. A single sequential stage where BuildKit could parallelise.
  4. Fix in the order of return. Move to a two-stage build with a JRE runtime base such as eclipse-temurin:21-jre-jammy, or a jlink runtime for a further cut; expected image roughly 200 to 280 MB for a typical Spring Boot service. Split COPY so the pom is copied and resolved first, and add a --mount=type=cache for .m2. Push the build cache to the registry so fresh runners hit. Run tests in CI outside the image build, or in a parallel test stage that the production target does not depend on. Add a .dockerignore. Expected build time on a warm cache: under two minutes, with a code-only change closer to 45 seconds because only the application layer is rebuilt and pushed.
  5. Prevention: record image size and build time as CI metrics, fail the pipeline above a threshold, and review the Dockerfile when the base image is bumped.

Land it "That is how Java images are" is true for single-stage Dockerfiles and false for everyone who has copied only the runtime out of the builder — a 1.4 GB Java image is a Dockerfile problem, not a Java problem.

Likely follow-ups
"You did all that and the image is 400 MB, not 250. Where is the rest?"

I would go back to docker history on the new image and read the two or three largest layers, because after a two-stage rewrite the culprits change.

Common leftovers: the JRE base is not the slim variant — eclipse-temurin:21-jre-jammy is about 190 MB while 21-jre on full Ubuntu is 270; the runtime stage installs tools such as curl, vim, or a full fontconfig with fonts for PDF generation, which drags in 100 MB of packages; the layered extraction was skipped and the fat jar plus an extracted copy both exist in the image; or the application's dependencies are genuinely large, which dive shows as a 150 MB BOOT-INF/lib — then the work is in the pom, removing unused starters and the Kotlin or Groovy runtimes nobody uses.

400 MB with a legitimate reason is acceptable; 400 MB from an installed text editor is not. Every finding gets written down with its size so the next reviewer sees the reasoning.

"The team says the 12 minutes is mostly tests, and tests must run before an image is pushed. How do you reconcile that?"

By separating "before push" from "inside the image build". Tests should gate the push, not run in the Dockerfile.

The CI pipeline compiles once, runs unit tests in a job that uses the build tool's incremental and parallel test execution, and only then builds and pushes the image from the already tested artefact.

That takes the tests off the image build's critical path without weakening the gate, and it lets the test job use the runner's full CPU and a persistent test cache rather than a single-threaded RUN in a container.

If the team wants the guarantee that the tested bytes are the shipped bytes, the image build copies the jar the test job produced as an artefact, rather than recompiling.

Test time itself is then a separate optimisation — parallel forks, test containers reused across classes, splitting slow integration tests into a job that runs against the built image after push to a staging tag. Twelve minutes usually becomes four with only those changes.

"What are the numbers you would put in the CI budget and what happens when a build exceeds them?"

Image size: fail above 350 MB for a JVM service, warn above 300, both configurable per service by a file in the repository so a legitimate exception is a reviewed change rather than a disabled check.

Unique bytes per build: warn above 50 MB for a commit that did not touch dependency files, which catches layer-ordering regressions. Build time on a warm cache: warn above three minutes, fail above six.

Time of the dependency step when the lockfile is unchanged: fail if it is not CACHED. On failure the job prints the docker history table and the uncached step list, so the developer can see the cause without re-running locally.

The thresholds are checked by a small script after the build using docker image inspect and the build log, and they are reviewed quarterly, because a budget nobody adjusts is soon either ignored or worked around.

"Would a native image or a jlink runtime be part of your first pass?"

jlink maybe, native image no.

jlink is a build-only change: a jdeps call, a jlink call, and a different runtime base, which cuts roughly 100 MB more and adds a minute to the build; I would add it in the second pass once the two-stage build is stable, because it introduces its own failure mode when a library needs a module that jdeps did not detect, typically jdk.crypto.ec or java.desktop.

Native image with GraalVM is a project, not a pass: it changes how reflection, proxies, and resources are configured, it makes the build take five to ten minutes of CPU-heavy compilation, and it changes runtime performance characteristics.

It produces a 100 MB image that starts in 100 milliseconds, which is valuable for scale-to-zero and CLI tools, but a 1.4 GB image that takes 12 minutes to build is a Dockerfile problem, and I would not answer it with a compiler change.

Q55 · Design. "Design the build-cache strategy for a CI system that builds 60 services, each on ephemeral runners, using BuildKit."

Reveal answer

Strong answer Requirements I would state: runners start empty, so the local layer cache is worthless; builds must be fast for the common case of a code-only change; the cache must not leak secrets; and storage cost has to stay bounded. The design has three parts.

First, Dockerfile discipline that makes caching possible: dependency manifests copied and resolved before source, cache mounts for package managers, and multi-stage builds so the runtime stage is small. Second, a remote cache backend.

I would use the registry backend, --cache-to type=registry,ref=registry/svc:buildcache,mode=max and --cache-from type=registry,ref=registry/svc:buildcache, with one cache reference per service and per main branch.

mode=max exports the intermediate stages too, so the builder stage with resolved dependencies is reusable, not just the final layers; mode=min would only save the final image's layers and miss the expensive part.

On GitHub Actions the type=gha backend is an alternative that uses the Actions cache service, but its 10 GB per-repository limit is easily exhausted by 60 services, so a registry is the safer default.

Third, cache mount contents are not exported by registry caches, so for the package caches I would persist them per runner pool with a shared volume, or accept that a manifest change pays a full download.

Trade-offs: registry cache pushes add 10 to 30 seconds per build, which is worth it when a miss costs minutes, and cache images need a retention policy, for example delete cache tags older than 14 days, or the registry grows without limit.

What I would not do: share one cache reference across all services, because unrelated layers pollute it and hit rates drop; and I would not enable mode=max for stages that mount secrets without checking that secret mounts are excluded, which BuildKit does by design, but I would verify it once with an audit of the exported cache.

Land it Ephemeral runners turn caching from a local convenience into a registry design problem, and the two decisions that matter are per-service cache references and mode=max.

Likely follow-ups
"The requirement changes: CI must not have push access to the production registry. Where does the cache live now?"

In a separate registry or repository that CI can write to and that production never reads.

A cache reference is just an image-shaped object, so I would put it in a dedicated ci-cache registry, or a cache/ repository prefix in the same registry with a separate write credential, and keep the production repositories writable only by the promotion job.

The build then uses --cache-to type=registry,ref=ci-cache.internal/svc:main,mode=max and pushes the actual image to a staging repository from which promotion copies it.

Alternatives if a second registry is unwelcome: the type=s3 or type=azblob cache backends, which store cache blobs in object storage with their own credentials and no registry at all; or type=gha on GitHub Actions with its size caveat.

The key separation is that cache write permission is a low-value credential that can live on every runner, while production push is high-value and lives on one job.

"You have a day, not a week. What is the minimum viable cache?"

A single addition to the CI build command per service: --cache-from type=registry,ref=registry/svc:buildcache --cache-to type=registry,ref=registry/svc:buildcache,mode=max, using the existing registry and the credentials the job already has for pushing images.

Plus the Dockerfile ordering fix for any service whose dependency step sits below the source COPY, which is a two-line move. That gives every subsequent build a warm cache for the dependency stage, which is the expensive part, and typically turns a six-minute build into two.

I would defer per-branch cache scoping, retention policies, cache-mount persistence, and any builder infrastructure.

The single risk of the one-day version is unbounded cache growth in the registry, which I would accept for a few weeks and then fix with a lifecycle rule on the buildcache tag pattern.

I would also verify on one service that the second build shows CACHED for the dependency step before rolling to sixty.

"Why are cache mounts not exported to the registry cache, and how do you keep them warm on ephemeral runners?"

Because cache mounts are not layers; they are mutable directories on the builder's local disk, outside the content-addressed snapshot model, and the registry cache exports only snapshot layers keyed by instruction.

So on an ephemeral runner every cache mount starts empty, and the first mvn or pip install downloads everything, even though the layer that results may be served from the registry cache if the inputs match — in which case the RUN is skipped and the mount is never touched.

That is the important subtlety: with a registry cache hit the empty mount does not matter; it only matters on a genuine miss.

To keep the mounts warm across runners, the options are a persistent builder — the buildx Kubernetes driver with a persistent volume, or a remote builder — or a build-tool-level remote cache such as a Maven or Gradle remote repository proxy in the same network, which makes downloads fast enough that the mount hardly matters.

BuildKit has discussed exporting cache mounts but as of Aug 2026 it does not.

"How do you audit that the exported cache never contains a secret?"

By design it should not: secret and SSH mounts are tmpfs and agent sockets outside the snapshot, so their contents are absent from every exported layer. The audit is to prove that once, then guard it with a check.

The proof: build a service with mode=max, then pull the cache reference's blobs — crane export registry/svc:buildcache - | tar -t works for the layer blobs, or docker buildx imagetools inspect --raw to list them and crane blob to fetch each — and run Trivy's secret scanner and a grep for the known token pattern over the extracted content.

The guard: a CI step that runs the secret scanner against the image and the cache reference on every main-branch build, cheap because the scanner caches by layer digest.

The one real leak path to remember is a RUN that copies the secret into the filesystem, which the scanner catches; the mechanism is safe, the Dockerfile author is the variable.

Q56. "What does .dockerignore actually control, and what goes wrong when it is missing or wrong?"

Reveal answer

Strong answer When you run docker build ., the client first packages the build context — the whole directory tree you pointed at — and sends it to the builder, and only then does the Dockerfile run.

.dockerignore is a list of patterns, in a syntax similar to .gitignore, that removes files from that package before it is sent. It has three effects.

The first is speed: without it, a repository with a .git directory, a node_modules tree or a target folder can send hundreds of megabytes to the daemon on every build, and with a remote builder that is a network transfer.

The second is cache stability: COPY . . is keyed by the checksum of everything copied, so a log file or an editor swap file changing under the tree invalidates the layer even though the source did not change.

The third is safety: .env files, cloud credentials, private keys and the local .npmrc land in the image if they are in the context and a broad COPY picks them up.

A sensible file excludes .git, build outputs, dependency directories, test reports, IDE folders, secrets patterns, and, importantly, the Dockerfile and .dockerignore themselves so that editing them does not invalidate a COPY. Two subtleties: the file must be in the root of the context, and BuildKit also supports Dockerfile.dockerignore named after a specific Dockerfile when several share a context.

The pattern **/node_modules is needed to match nested directories, and a trailing !pattern re-includes an exception.

Land it The build context is a tarball of your repository sent to a daemon, and .dockerignore is the only thing standing between your credentials directory and that tarball.

Likely follow-ups
"Show me a .dockerignore for a Java repository and explain the two patterns people get wrong."

A sensible one is: .git, .gitignore, **/target, **/build, **/.idea, **/*.iml, **/.vscode, **/node_modules, **/*.log, .env, **/*.pem, **/.npmrc, Dockerfile*, .dockerignore, docs, and README.md.

The first mistake is writing target without the leading **/ and expecting it to match nested modules; the pattern language matches from the context root, so target excludes only the top-level directory and **/target is needed for multi-module projects.

The second is excluding something the build needs and discovering it as a "file not found" in COPY: excluding *.md when a Maven plugin reads README.md, or excluding .git when the build derives a version with git describe; the fix is a ! re-include line after the broad exclusion, or passing the version as a build argument.

I test a new file with docker build --no-cache --progress=plain and the context size printed in the first line.

"Does .dockerignore affect COPY --from or bind mounts during the build?"

No. It only filters the build context — the local directory sent to the builder.

COPY --from=stage reads from another stage's filesystem, which was populated by that stage's own instructions, so the ignore file has already had its effect earlier if that stage copied from the context. COPY --from=image reads from an image and is unaffected.

RUN --mount=type=bind,source=.,target=/src mounts the context, and since the context was already filtered when it was sent, the mount shows the filtered view too — but a bind mount from another stage or image shows that source in full.

The other thing it does not do is affect the running container in any way; it is purely a build-time filter.

One more subtlety: with multiple contexts, --build-context name=path, each additional context honours its own .dockerignore at its root, and a Dockerfile-specific Dockerfile.dockerignore takes precedence over the general one when present.

"How would you detect a repository that lacks a .dockerignore before it leaks something?"

Two checks in the pipeline. A presence and content check: the CI job fails if the context root has a Dockerfile and no .dockerignore, and it lints the ignore file for a minimum set of patterns — .git, .env, key files — using a small script.

And a context-size check: BuildKit prints "transferring context: N MB" in its plain progress output, and I parse that line and fail above a threshold, say 50 MB for a Java service, which catches a missing ignore file the day someone commits a large fixture or forgets target.

For leaks specifically, the Trivy secret scan on the resulting image is the last line.

Across many repositories, a periodic scan of the organisation's repositories for Dockerfiles without an accompanying ignore file, opening an automated pull request with the standard template, takes an afternoon to write and finds the stragglers.

"Why exclude the Dockerfile itself from the context?"

Because COPY . . includes it otherwise, and then any edit to the Dockerfile changes the context checksum and invalidates that COPY layer and everything below, even when the edit was a comment.

Excluding Dockerfile* and .dockerignore keeps a Dockerfile change from busting layers whose actual inputs did not change — though the instruction whose text changed still reruns, as it should.

The builder does not need the Dockerfile in the context to read it; it is sent separately, which is also why -f can point at a Dockerfile outside the context.

The same logic applies to README.md, docs/, and CI configuration under .github/: none of them belong in the image, and every one of them changes more often than the code.

Once the build context is only source and build manifests, the cache behaves the way the Dockerfile's ordering promises.

Q57 · Scenario. "The image builds fine on a developer's laptop and fails in CI. Same Dockerfile, same commit. Give me your checklist in order."

Reveal answer

The real test Whether you have an ordered list at all, rather than "it is probably the network".

Strong answer The checklist I run:

  1. Read the failing step, not the last line. The build log with --progress=plain names the instruction and the command's real error, which usually points at one of the causes below.
  2. Cache differences. The laptop has warm layers and may be reusing a stale apt-get update or a package version that no longer exists; CI starts cold and hits the real registry. Rebuild locally with --no-cache and the failure often reproduces.
  3. Architecture. A developer on an Apple silicon laptop builds arm64 images; CI is amd64. A base image tag or a downloaded binary that exists only for one architecture fails on the other. Check with docker buildx build --platform linux/amd64 locally, and pin base images by digest.
  4. Secrets and credentials. The laptop has an SSH agent, a logged-in registry, and a .npmrc in the home directory; CI has none of these unless passed via --secret or --ssh. A private dependency fetch failing with 401 is the signature.
  5. Build context. The developer's tree contains untracked files, a target directory with a prebuilt jar, or a local config that COPY . . picks up; CI does a clean checkout and those files are absent. Compare with git status --ignored and check .dockerignore.
  6. Builder version and features. An old CI daemon without BuildKit, or a missing # syntax directive, rejects heredocs or mounts; docker version on both sides settles it.
  7. Fix the root cause, then prevent it: build in CI only, by digest, with explicit secrets, and make developers build with the same --platform flag through a shared Makefile.

Land it "Works on my machine" for a Docker build almost always means the laptop has something the Dockerfile never declared — a cached layer, an architecture, a credential, or a file.

Likely follow-ups
"You went through the checklist and everything matches, and CI still fails on the mvn step with a timeout. What next?"

Then it is the network shape of CI, which the checklist touches only through credentials.

I would run the failing step with verbose output to see which host it is trying to reach — mvn -X shows the repository URL — and test that host from the runner with curl -v inside a container started from the same builder image.

The typical findings are a corporate proxy that the laptop has configured in ~/.m2/settings.xml and CI does not, fixed by passing the proxy through build arguments that BuildKit treats specially, --build-arg HTTP_PROXY, or through a mounted settings file; an internal artefact repository reachable only from the office network or VPN; or DNS inside the build container resolving differently because the runner's /etc/resolv.conf points at a resolver that does not know internal names, fixed with --network=host for the build or the daemon's dns setting.

IPv6-only runners hitting an IPv4-only mirror is the newest variant of the same theme.

"How would you reproduce the CI environment on the laptop rather than reasoning about the difference?"

By removing the laptop's advantages one at a time until the failure appears. git clone the repository into a fresh directory rather than building from the working tree, so untracked files and local build outputs are gone.

Build with --no-cache and --pull so no stale layer or old base tag helps. Build with --platform linux/amd64 to match the runners.

Run the build inside a container that has no credentials: docker run --rm -v $PWD:/src -w /src docker:cli against a clean daemon, or simply unset SSH_AUTH_SOCK, log out of the registry, and move ~/.m2/settings.xml aside.

Set the same environment variables the CI job sets, which the CI system prints at the start of a job. In most cases one of the first three steps reproduces it.

If the CI system offers it, the last resort is a debug session on the runner itself, which GitHub and GitLab both support through an SSH step.

"What single change to the pipeline would prevent most of this class of failure?"

Making the developer build the way CI builds, through one shared entry point.

A make image target or a small script that runs docker buildx build with the same platform flag, the same --secret and --ssh arguments, the same build arguments, and a pinned syntax directive, so the only difference between laptop and CI is the cache state and the network.

That removes architecture, credential, and builder-feature differences by construction. Second to that is pinning: base images by digest and the syntax frontend by version, which removes the moving-tag differences.

Third is a clean-checkout build on every pull request in CI, which surfaces the untracked-file dependency before merge. None of these costs more than an hour; they turn the checklist from a debugging tool into a set of things that cannot happen.

"Does BuildKit's --check or a linter catch any of these?"

Some. docker build --check runs BuildKit's built-in checks without building, and it flags undefined build arguments, inconsistent instruction casing, a missing syntax directive when newer features are used, empty continuation lines, and FROM with a platform flag that matches the target, which is the Mac-to-production trap.

hadolint catches unpinned base tags and package versions, the shell-form pitfalls, and ADD misuse. Neither can see credentials or the build context contents, so the network and secrets categories remain runtime discoveries.

I run both in CI on every Dockerfile change and treat warnings as failures for runtime stages, and I run --check in the pre-commit hook because it finishes in under a second.

The remaining category, cache staleness, is addressed by scheduled --no-cache builds on main once a day, which surface repository changes such as a removed package version before a developer hits them.

Q58. "What would it take to make an image build reproducible — the same input producing the same digest — and how close do teams actually get?"

Reveal answer

Strong answer A reproducible build means two people building from the same commit get byte-identical layers and therefore the same image digest, which is the strongest form of "this is what we reviewed". Getting there requires removing every source of variation.

First, the base image: FROM eclipse-temurin:21-jre-jammy is a moving tag, so pin it by digest, FROM eclipse-temurin:21-jre-jammy@sha256:…, and let a bot such as Renovate open pull requests when the digest moves.

Second, packages: apt-get install curl resolves to whatever is current, so pin versions, curl=8.5.0-2ubuntu10.6, or better use a snapshot repository such as Debian's snapshot.debian.org keyed by date.

Third, application dependencies: lockfiles for pip and npm, and for Maven the exact versions plus checksum verification of the repository.

Fourth, timestamps: every file in a layer carries a modification time and every image records a creation time, so BuildKit honours SOURCE_DATE_EPOCH, an environment variable holding a fixed Unix time, and with --build-arg SOURCE_DATE_EPOCH=… plus the rewrite-timestamp=true output option it normalises them.

Fifth, anything random or network-dependent in a RUN, such as a download without a checksum.

Most teams get to "pinned base digest, lockfiles, pinned system packages" and stop there, which gives you reproducible content and a stable software bill of materials even if the digest still drifts by a timestamp.

Full bit-for-bit reproducibility is achievable with BuildKit since 0.12 and worth it for regulated environments, but it costs discipline every time a version bumps.

Land it Pin the base digest and the packages first, because that is 90 percent of the security value; chase identical digests only when an auditor will ask for them.

Likely follow-ups
"Show the exact buildx command for a reproducible build and say how you would prove two runs match."

With a Dockerfile whose base is pinned by digest and whose packages are pinned or from a snapshot, the command is SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) docker buildx build --build-arg SOURCE_DATE_EPOCH --output type=image,name=registry/app:test,push=true,rewrite-timestamp=true --provenance=false --sbom=false ..

The environment variable feeds the config's created time and, through rewrite-timestamp, every file's modification time in the layers; provenance and SBOM are disabled because they embed build-time values that differ per run.

To prove it, run the command twice on two machines and compare crane digest registry/app:test after each, or without pushing, use type=oci,dest=a.tar and b.tar and compare sha256sum of the index.json manifests inside.

If they differ, diffoci or a layer-by-layer tar -tv comparison shows the first differing file, which is usually a package-generated file with a timestamp or an ldconfig cache.

"What is the practical value if the digest still differs by a timestamp? Why stop at 'pinned content'?"

Because almost every security and audit goal is met by pinned content, and the last step buys mostly elegance.

With a pinned base digest, pinned packages, and lockfiles, two builds from the same commit contain the same software with the same versions, so a vulnerability scan of one applies to the other, the SBOM is stable, a supply-chain reviewer can reason about what is in the image from the source alone, and a rebuild after a registry loss produces something functionally identical.

What identical digests add is the ability to verify independently that a published image came from the claimed source by rebuilding it and comparing hashes, which is what reproducible-builds projects and some regulated environments want.

That verification needs the whole toolchain pinned too — the BuildKit version, the frontend, the compressor — which is a maintenance commitment. So I recommend pinned content as the default and the full property only where someone will actually perform the rebuild-and-compare check.

"How does a lockfile-based install remain non-reproducible, and what fixes it?"

A lockfile pins versions but not always bytes or build behaviour. For Python, a lockfile with versions but without hashes lets a registry serve a rebuilt wheel with the same version; uv.lock and pip-compile --generate-hashes record hashes and refuse mismatches.

A source distribution compiled at install time embeds the compiler's output, which varies with the compiler version and flags in the builder stage — fixed by preferring binary wheels or pinning the builder image.

For npm, package-lock.json pins integrity hashes, but postinstall scripts can download platform binaries at install time; --ignore-scripts or vendoring them fixes it. For Maven, versions are pinned but the repository can be swapped; checksum verification and a fixed mirror address that.

And Java's own compiled output is reproducible only if the compiler's timestamp handling is configured, which Maven's project.build.outputTimestamp property handles for jar entries. Each ecosystem has a two-line fix once you know where its nondeterminism hides.

"How does reproducibility relate to provenance attestations and SLSA levels?"

They are complementary answers to "can I trust this image".

Provenance is a signed statement from the builder saying which source, which Dockerfile, which base, and which parameters produced the image; SLSA levels grade how trustworthy that statement is — level 1 is any provenance, level 2 is signed provenance from a hosted build service, level 3 adds a hardened, isolated builder whose provenance cannot be forged by the build steps themselves.

None of that requires the build to be reproducible; it requires it to be honest. Reproducibility is the independent check: if I can rebuild and get the same digest, I do not have to trust the builder's word.

In practice teams get to SLSA level 2 or 3 with BuildKit's --provenance=mode=max attestations and a hosted runner in weeks, while bit-for-bit reproducibility remains a longer project, so provenance is the first investment.

Both attach to the image as referrers and both are verified by the same admission tooling.

Drill · JVM, Python & base-image choices

These questions test whether you can choose a base image and a layout with reasons, and whether you know the specific ways the JVM and Python wheels break on the wrong base.

Q59. "How does the Spring Boot layered jar work, what are the four layers, and why does the order of the COPY lines matter?"

Reveal answer

The real test Whether you can name the extraction command and explain what each layer holds, not just say "it makes pushes smaller".

Strong answer A Spring Boot fat jar contains your compiled classes plus every dependency jar nested inside it, so as a single file it changes on every commit and the whole 80 MB is a new Docker layer every time.

The layered jar feature splits that content by how often it changes. Since Spring Boot 3.3 the command is java -Djarmode=tools -jar app.jar extract --layers --destination extracted, which writes four directories. dependencies holds released third-party jars, the largest and least volatile part.

spring-boot-loader holds the classes that boot a jar from exploded directories. snapshot-dependencies holds any dependency whose version ends in SNAPSHOT, separated because those change often. application holds your own classes and resources, the smallest and most volatile part.

The Dockerfile then copies these into the runtime image in exactly that order, each as its own COPY, so each becomes its own layer.

Because the cache invalidates from the first changed layer downward, putting the most volatile layer last means a code-only change rebuilds one layer of a few hundred kilobytes; the registry push and the node pull move only that layer, and a fleet of 200 nodes pulls 200 small layers instead of 200 times 80 MB. The layer definition is customisable in the Maven or Gradle plugin, so a company-internal library group can be given its own layer between dependencies and application.

Startup is unchanged: java -jar app.jar works against the extracted layout because the loader is present.

Land it The four layers are just "sort files by how often they change", and the Dockerfile's job is to copy them in that order and never merge them back.

Likely follow-ups
"Show me how to add a custom layer for our internal libraries, and why you would."

In the Spring Boot Maven plugin's configuration, a <layers> block points at a layers.xml that defines the layer order and the patterns for each.

A typical file lists dependencies with an <include>*:*</include> and an exclude for the company group, a new company-dependencies layer with <include>com.example:*</include>, then snapshot-dependencies, spring-boot-loader, and application; the <layerOrder> element places company-dependencies between third-party dependencies and the application.

The Dockerfile then adds one more COPY line in that position. The reason is change frequency: internal libraries are released weekly while third-party ones change monthly, so putting them together means a weekly internal release invalidates the big third-party layer.

Separated, a bump of an internal library pushes a 5 MB layer rather than 60 MB. java -Djarmode=tools -jar app.jar list-layers shows the resulting order for verification.

"Is the extracted layout the same as the fat jar at runtime? Any behavioural differences?"

Functionally the same, with two differences worth knowing.

Startup is slightly faster from the extracted layout, because the loader reads classes from the filesystem instead of from nested jars inside a jar, which avoids the nested-jar indirection Spring Boot's launcher otherwise performs; the extract command also writes a small app.jar with a classpath manifest, so java -jar app.jar in the extracted directory works and is the recommended launch.

The second is that anything that inspects the classpath — a library that scans for resources, a diagnostic that prints java.class.path — sees a directory of jars rather than one archive, which is closer to a normal Java application and generally more predictable.

Since Spring Boot 3.3 the extract command is the documented path, and the older -Djarmode=layertools is deprecated. The tools mode also has an extract --layers --launcher variant that keeps the launcher for images that want the original launch style.

"How does this interact with AppCDS or the JDK's ahead-of-time cache?"

Well, because the extracted layout has a stable classpath, which class-data-sharing archives require.

The CDS archive records the classpath it was trained with and refuses to load if the classpath differs, so it must be created after extraction and in the same directory layout, in the runtime stage of the Dockerfile: run the application once with -XX:ArchiveClassesAtExit=/app/app.jsa -Dspring.context.exit=onRefresh, which Spring Boot 3.3 and later understands as a training run that exits after context refresh, then start normally with -XX:SharedArchiveFile=/app/app.jsa.

The archive is 30 to 80 MB and becomes its own layer that changes whenever the application changes, so it goes last. The extract --layers layout also works with JDK 24 and later's ahead-of-time cache, which is trained the same way with -XX:AOTMode=record and -XX:AOTCache.

The gotcha in both cases is that the training run needs the same JVM binary as production, so it belongs in the runtime stage, not the builder.

"What would you tell a team that ships a Gradle build with Kotlin — is any of this different?"

The mechanism is identical; only the plugin configuration differs. The Spring Boot Gradle plugin enables layering by default for bootJar, and custom layers are declared in the bootJar { layered { ... } } block with application, dependencies, and layerOrder entries using Kotlin DSL. Kotlin adds a large runtime — kotlin-stdlib, kotlin-reflect, and the coroutines libraries — which are ordinary dependencies and land in the dependencies layer.

The one Gradle-specific point is the build/libs directory containing both the plain jar and the boot jar when the jar task is enabled, so the Dockerfile must copy *-boot.jar or the plain-jar task must be disabled to avoid an ambiguous COPY. And Gradle's own daemon and cache directories should never be in the build context.

Beyond that, the extract command, the four COPY lines, and the ordering argument are exactly the same, which is the point of it being a jar-format feature rather than a build-tool feature.

Q60. "Why do people warn against Alpine for JVM and Python images? Be specific about musl."

Reveal answer

Strong answer Alpine is attractive because its base image is about 8 MB, but it is built on musl, a small C standard library, where almost every other distribution uses glibc, the GNU C library.

The C library is the layer between programs and the kernel for memory allocation, threads, name resolution and locale, so swapping it changes behaviour in ways that show up late.

For the JVM, the well-known problems are musl's memory allocator, which returns memory to the operating system less eagerly and can inflate resident memory under thread-heavy workloads; a default thread stack size of 128 KB that has caused stack overflows in native code; and DNS resolution differences, because musl historically did not support some resolver features and queried servers in parallel, which surprised applications relying on /etc/hosts ordering or search domains.

Modern Temurin builds ship an Alpine variant that works, but you inherit those differences. For Python the pain is sharper. Prebuilt binary wheels on PyPI are compiled against glibc under the manylinux tag, and pip will not install them on musl unless a musllinux wheel exists.

Without one, pip falls back to compiling from source, so numpy, cryptography or psycopg installs need gcc, headers and many minutes, and often fail. The result is an Alpine image that ends up larger than a Debian slim one once the compiler is added.

The practical choice is python:3.12-slim or eclipse-temurin:21-jre-jammy, or for minimal attack surface a distroless or Wolfi image, which is glibc-based.

Land it Alpine saves 60 MB and costs you a C library, and for a JVM or a scientific Python stack that trade is almost never worth it.

Likely follow-ups
"Give me a concrete production incident that musl caused and how it was diagnosed."

The one I use as the example is the DNS case. A JVM service on Alpine intermittently failed to resolve an internal hostname that worked from Debian-based containers on the same nodes.

The cause was musl's resolver: it sends queries to all configured nameservers in parallel and takes the first answer, and it historically did not implement the ndots and search-domain behaviour the same way glibc does, so a Kubernetes short name that depended on search-domain expansion resolved through one nameserver and failed through another.

Diagnosis was nslookup inside both containers with strace -e trace=network showing the parallel queries, then reading /etc/resolv.conf. The fix was the Debian-based base; the workaround was fully qualified names.

The second common one is a Netty-based service whose native epoll transport crashed on a 128 KB thread stack, fixed with -Xss for the affected threads and eventually by leaving Alpine. Both cost days because nobody suspected the C library.

"Is the memory-allocator issue real, and how would you measure it?"

It is real for some workloads and negligible for others, so I measure rather than assert.

musl's malloc is simpler than glibc's and, in older versions, returned freed memory to the kernel less readily and fragmented more under many threads, so a JVM's native allocations — metaspace, thread stacks, direct buffers, JIT — could show higher resident memory than the same JVM on glibc.

Musl 1.2.1 introduced a new allocator, mallocng, that improved it, and Alpine 3.13 and later ship it.

To measure, run the same image on both bases under the same load and compare docker stats resident memory over an hour, and inside the JVM jcmd 1 VM.native_memory summary to separate JVM-accounted native memory from allocator overhead; the difference between the JVM's total committed and the cgroup's memory.current is the allocator's fragmentation plus page cache.

If the gap is under ten percent, Alpine is not the problem. Some teams on glibc also switch to jemalloc for the same reason, which is a separate optimisation.

"If the goal is a small image, what beats Alpine for a JVM or Python service?"

For the JVM, a jlink runtime on Debian slim or on distroless: 60 MB of custom JRE plus 30 MB of base gets to about 100 MB, glibc-based, no musl anywhere, and the size comes from dropping unused JDK modules rather than from the C library.

Distroless Java or the Chainguard JRE reach a similar size with the extra benefit of no shell.

For Python, python:3.12-slim is about 50 MB more than Alpine before packages and, once numpy and friends are installed, ends up smaller than Alpine with a compiler; distroless Python and the Chainguard Python image go further with a glibc base.

The honest observation is that for a typical service the application and its dependencies dominate — a Spring Boot service's libraries are 60 to 100 MB and a data-science Python environment is 500 MB — so the base image's 8 versus 50 MB is a rounding error, and the real size work is in the dependency list.

"Where is Alpine the right choice?"

Static binaries and tools with no C-library dependence beyond what musl handles well: Go services, which do not use the system libc at all unless cgo is enabled; Rust binaries built for the musl target; nginx, HAProxy, and Redis, whose official Alpine variants are widely used and well tested; and sidecar utilities where 8 MB versus 80 MB multiplied by thousands of pods matters.

It is also a fine base for the busybox-style debug and init containers whose only job is a shell and a few tools.

The rule I give teams is that Alpine is appropriate when the application is either statically linked or explicitly tested on musl by its upstream, and inappropriate when the runtime is one with a large native surface and glibc assumptions — the JVM, CPython with compiled extensions, Node with native modules, anything using getaddrinfo semantics heavily.

Written that way, the policy is about the runtime rather than a blanket ban.

Q61 · Scenario. "A data team's Python image started failing to build after they switched the base to python:3.12-alpine to shrink it. The log shows a 9-minute step ending in 'error: command gcc failed'. What happened and what do you tell them?"

Reveal answer

Strong answer In diagnosis order:

  1. Read the failing package name above the gcc error; it is almost always a compiled extension such as numpy, pandas, pydantic-core, cryptography or psycopg2. The 9 minutes are pip compiling from source because no musllinux wheel matched.
  2. Confirm by running the install with pip install -v and looking for "Building wheel" instead of "Downloading … manylinux" lines, and by checking the package on PyPI for a musllinux artefact.
  3. Causes, ranked: no musl wheel available for that package and version; musl wheel exists but pip is too old to recognise the tag; the compiler and headers are missing so even the fallback fails; and, less often, a Rust toolchain is needed for packages such as pydantic-core.
  4. The honest fix is to go back to python:3.12-slim, which is Debian-based, about 45 MB larger than Alpine, and installs the same packages from prebuilt wheels in seconds. If Alpine is non-negotiable, install build-base and headers in a builder stage, compile there, and copy the virtual environment into a clean Alpine runtime, accepting a much slower and more fragile build.
  5. Prevention: an organisation rule that Python and JVM services use glibc bases, a size budget so nobody reaches for Alpine to meet an arbitrary number, and a build-time budget in CI that flags any step over two minutes.

Land it The team traded a 45 MB base saving for a compiler in every build — the slim Debian image was the smaller image all along once you count what they had to add.

Likely follow-ups
"They went back to python:3.12-slim and the build still compiles something for three minutes. What next?"

Then a package still lacks a binary wheel for that exact combination, and I want its name.

pip install -v or uv sync -v prints "Building wheel for X" for anything compiled; I would look that package up on PyPI and check whether it publishes manylinux wheels for CPython 3.12 at that version.

Common findings: the package is too new or too old to have a 3.12 wheel, fixed by moving the version; the package is pure Python but declares a build backend that compiles optional speedups, which a --no-binary or --only-binary :all: flag reveals — the latter fails the install loudly if any package would need compiling, which is the behaviour I want in CI; or pip is old enough not to recognise newer manylinux_2_28 tags, fixed by pip install --upgrade pip first.

If a compile is genuinely required, it moves to a builder stage with build-essential and the resulting virtual environment is copied to a clean runtime stage.

"Why did the same requirements file install in seconds on the developer's Mac?"

Because the Mac pulled macOS wheels. PyPI packages publish separate wheels per platform — macosx_11_0_arm64 for Apple silicon, manylinux for glibc Linux, musllinux for Alpine — and a package may have the first two and not the third. The developer never touched musl, so nothing compiled.

This is a useful diagnostic in general: pip's log line "Downloading X-1.2-cp312-cp312-manylinux_2_17_x86_64.whl" versus "Downloading X-1.2.tar.gz" tells you whether a wheel matched, and the platform tag in the filename tells you why.

A developer can predict the container's behaviour by running pip download --platform musllinux_1_2_x86_64 --only-binary :all: -r requirements.txt on the Mac, which fails for every package without a musl wheel without building anything.

That command in a pre-merge check would have caught the base image change before the nine-minute build.

"The data team says they need Alpine because the security scanner reports fewer findings. How do you respond?"

I would agree with the goal and disagree with the means, and show numbers.

Alpine's low finding count comes from having few packages, not from being more secure per package, and the moment they add build-base, gcc, and headers to make the build work, the finding count rises past Debian slim's.

The alternatives that keep the count low without musl: python:3.12-slim with a multi-stage build so the runtime has no compiler, which typically scans at a handful of medium findings; the Chainguard Python image, which is glibc-based, rebuilt daily, and usually scans at zero; or distroless Python.

I would run Trivy against all three and their Alpine proposal with the real dependency set and put the table in the ticket.

Then I would point out that the vulnerabilities that matter in a data image are almost always in the Python packages — an old pillow, numpy, or requests — which no base image choice affects and which a lockfile update fixes.

"How would you make this build both small and fast for a team with heavy scientific dependencies?"

A builder stage on python:3.12-slim that creates a virtual environment from a lockfile with a cache mount, then a runtime stage that copies only the environment.

Concretely: COPY --from=ghcr.io/astral-sh/uv:0.8 /uv /bin/, RUN --mount=type=cache,target=/root/.cache/uv uv sync --frozen --no-dev, then in the runtime COPY --from=builder /app/.venv /app/.venv with PATH set. Pin the lockfile with hashes so the wheels are the ones tested.

Trim the scientific stack: numpy, pandas, and scipy together are 200 MB and cannot shrink, but installing opencv-python-headless instead of opencv-python saves 100 MB of GUI libraries, and removing a stray matplotlib or jupyter from production requirements saves more.

Strip .pyc for test directories, and set UV_COMPILE_BYTECODE=1 for the rest so startup is fast. The result is typically 400 to 600 MB, built in under a minute on a warm cache, which is what "small" realistically means for that kind of workload.

Q62 · Design. "Design the image for a Python 3.12 FastAPI service using uv. Show the Dockerfile and explain the environment variables you set."

Reveal answer

The real test Whether you know why the virtual environment is built in one stage and copied to another, and what the two PYTHON variables do.

Strong answer Assumptions: the project has a pyproject.toml and a uv.lock lockfile, the service listens on 8000, and it must run as non-root. The design uses uv, the fast Rust-based package manager, in a builder stage to create a virtual environment from the lockfile, then copies only that environment into a slim runtime image that never has uv, a compiler or the source tree's build tooling.

Dockerfile
# syntax=docker/dockerfile:1
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-install-project --no-dev
COPY src ./src
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev

FROM python:3.12-slim-bookworm
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
    PATH="/app/.venv/bin:$PATH" TZ=UTC
RUN useradd --system --uid 10001 app
WORKDIR /app
COPY --from=builder --chown=app:app /app /app
USER 10001
EXPOSE 8000
CMD ["uvicorn", "myservice.main:app", "--host", "0.0.0.0", "--port", "8000"]

The two uv sync calls split dependency installation from project installation, so the dependency layer is cached by the lockfile checksum alone and a source change only reruns the cheap second call. --frozen refuses to resolve anything not in the lockfile, which makes the build deterministic. UV_COMPILE_BYTECODE=1 precompiles .pyc files in the builder so startup is faster. In the runtime image, PYTHONUNBUFFERED=1 makes stdout unbuffered, so log lines reach docker logs immediately instead of appearing in bursts or vanishing on a crash; PYTHONDONTWRITEBYTECODE=1 stops Python writing .pyc files into a read-only or non-root filesystem at runtime. Putting the venv's bin directory first on PATH means the CMD runs the venv's uvicorn without activation. Trade-offs: the runtime image has no uv and no pip, which is the point but means no in-container installs. I would not use Alpine, for the wheel reasons in Q60, and I would not run pip install without a lockfile, because the image would then differ from build to build.

Land it Lockfile-first, dependencies before source, venv copied not rebuilt, and unbuffered output — those four decisions are what separate a Python image that behaves in production from one that merely runs.

Likely follow-ups
"Why copy the whole /app rather than just .venv, and what if the source has to live somewhere else?"

Copying /app brings both the virtual environment and the project source in one COPY, because the second uv sync installed the project itself into the venv in editable or regular mode, and the code has to be present at the same path for the imports to resolve.

If the team prefers to separate them, two COPY lines work: COPY --from=builder /app/.venv /app/.venv and COPY --from=builder /app/src /app/src, which also gives the venv its own layer that only changes when the lockfile does — a real gain, since the venv is 100 MB and the source is 1 MB.

The path constraint is that a venv records its own location in pyvenv.cfg and in the shebang lines of its scripts, so it must be copied to the same absolute path.

UV_LINK_MODE=copy in the builder ensures the packages are real files rather than hardlinks into the cache mount, which would be broken after the copy.

"The requirement changes: the service must run as a single process handling many requests with a worker model. Does the CMD change?"

Yes, but carefully. A single uvicorn process is the right container default because the orchestrator scales by replicas and a process-per-container keeps signals, logs, and resource limits simple.

If the team wants several worker processes per container for CPU-bound work on a multi-core limit, the modern option is uvicorn --workers 4, or gunicorn with the uvicorn worker class: gunicorn -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000 myservice.main:app.

Gunicorn's master then becomes PID 1 and it does handle SIGTERM and reaps children correctly, so no tini is needed. The worker count should match the CPU limit, and it needs a --graceful-timeout below the container's stop grace period.

The trade-off is memory: each worker loads the application separately, so four workers on a 512 MB limit can OOM; the rule is one container, one worker, more replicas, unless a measured reason says otherwise.

"How does the build behave when only the source changes versus only the lockfile changes?"

Source only: the first COPY of pyproject.toml and uv.lock is unchanged, so the first uv sync --no-install-project is CACHED, the COPY src misses, and the second uv sync reruns; with the cache mount that second call installs only the project package, which takes a second or two.

The runtime stage's COPY reruns because the builder's output changed, and the pushed layer is the venv plus source, unless they were split into two COPYs, in which case only the source layer moves.

Lockfile only: the first COPY misses, the first sync downloads what changed from the cache mount, and everything below reruns; a warm mount makes even that fast. Both cases avoid redownloading the wheel set, which is the expensive part.

I would verify with --progress=plain after a one-line source edit that exactly the steps I listed are uncached.

"What would you add for production readiness that is not in this Dockerfile?"

Three things, deliberately kept out of a template to keep it readable. A read-only root filesystem with a tmpfs at /tmp, set in the deployment rather than the image, and verified by running the service once with --read-only.

Health probes defined in the orchestrator against a /health route that checks nothing external, with a startup probe generous enough for the import of heavy libraries.

And observability: PYTHONFAULTHANDLER=1 so a segfault in a native extension prints a Python traceback, structured JSON logging configured in the application, and OpenTelemetry instrumentation through opentelemetry-instrument as the entrypoint wrapper if the platform uses it.

I would also pin the base by digest and add the OCI labels through the build command. What I would not add is a HEALTHCHECK, a shell-based entrypoint script, or pip in the runtime image.

Q63. "Compare distroless, Chainguard/Wolfi, ubi-minimal and a Debian slim base for a JVM service. What do you give up with each?"

Reveal answer

Strong answer Debian slim bases such as eclipse-temurin:21-jre-jammy, which is Ubuntu, or the Debian-based Temurin tags, give you a shell, a package manager, and familiar debugging tools, at roughly 100 to 130 MB before the JRE and with a few dozen packages that scanners will keep flagging.

Distroless, Google's gcr.io/distroless/java21-debian12, strips the shell and package manager and ships only the JRE, its libraries and certificates; the attack surface and the vulnerability count drop sharply, but docker exec into it gets you nothing, so you debug with ephemeral debug containers or a :debug tag that adds busybox.

Chainguard images built on Wolfi, a glibc-based distribution designed for containers, take the same minimal approach but rebuild packages daily so the scanner count is typically zero, and they publish signed images with a software bill of materials; the free tags track only the latest version, so pinning to a specific JDK line requires a paid plan or a mirror.

ubi-minimal, Red Hat's Universal Base Image, is the choice when the organisation runs OpenShift or wants a vendor-supported base with a support contract; it keeps microdnf, is glibc-based, and is larger than distroless but well understood by enterprise security teams.

What you give up: with slim, low vulnerability counts; with distroless and Wolfi, in-container debugging and the habit of apt-get install during incidents; with ubi, freedom to choose newer package versions.

All four are glibc, which is why they are all fine for the JVM in a way Alpine is not.

Land it The real choice is between "a shell in production" and "a low scanner count", and I make it once per organisation rather than once per Dockerfile.

Likely follow-ups
"How do you actually patch a distroless-based image when a CVE lands in glibc?"

By rebuilding on the updated base, never by patching in place.

Distroless images are rebuilt by Google from Debian packages, so a glibc fix appears as a new digest of gcr.io/distroless/java21-debian12 within a day or so of the Debian security update; the pipeline that pins the base digest gets a bump from the update bot, the service rebuilds, and the new image ships through the normal promotion.

There is no apt-get in the image to run, which is the point: the image is immutable and the fix is a new artefact with a new digest, not a mutated container.

The operational requirement this creates is that every service must be rebuildable at any time from source with no manual steps, and that the base digest is in one place per service.

A fleet-level report of base digests in use, compared with the current upstream digest, shows which services are behind. Chainguard's images are the same model with a faster upstream cadence.

"What does the :debug tag on distroless contain and when is it acceptable to ship it?"

The :debug variant adds a busybox shell and its utilities, so docker exec -it svc sh works and you get ls, cat, ps, wget, and the rest of busybox.

It is meant for local debugging and for a temporary swap during an incident when the ephemeral-debug-container path is not available.

Shipping it to production permanently gives up the main security benefit — an attacker who gains execution now has a shell and a downloader — while keeping the operational downside that most engineers still do not know busybox's limitations.

Where I have accepted it: a short-lived staging environment during a migration, and a single canary replica in production while chasing a specific bug, with a ticket to remove it.

The policy I write is that :debug is allowed only behind a named exception with an expiry, and that the platform must provide the debug-container workflow so the exception is rarely needed.

"Chainguard's free images only track latest. How do you get a pinned JDK line without paying?"

Three options. Mirror the free image into your own registry on a schedule and pin the mirrored digest; you get reproducibility for your builds but you are on your own when upstream moves to a newer major, since older lines are not rebuilt for free users.

Build your own equivalent with Wolfi packages: the apko tool takes a small YAML listing packages such as openjdk-21-jre from the public Wolfi repository and produces a minimal, glibc-based, SBOM-included image, which is exactly how Chainguard builds theirs, so you can pin the JDK line yourself and rebuild daily in your CI. Or use distroless or ubi-minimal, which do offer version-specific tags for free.

For a 300-service organisation I would evaluate paying, because the value is the patch cadence and the support, but the apko route is a real and well-documented free alternative as of Aug 2026.

"How would you compare these bases objectively for your organisation rather than by reputation?"

With a small benchmark repository that builds the same reference Spring Boot service on each base and records a fixed set of measurements. Size from docker image inspect. Scanner findings by severity from Trivy and Grype, since they differ.

Startup time to the readiness endpoint, averaged over ten runs with the same CPU limit. A debugging drill: how many steps to get a thread dump and a heap dump on each.

Time to patch: how many hours between a chosen recent glibc or OpenSSL CVE's Debian advisory and each base publishing a fixed digest, which is checkable from their registries' push times. Licensing and support terms. Then a one-page table.

In most runs I have seen, distroless and Wolfi win on findings and size, Debian slim wins on the debugging drill, and ubi wins only when there is a Red Hat relationship; the decision is then about which of those the organisation values, made once and written down.

Q64 · Design. "Write the base-image policy for a 300-service organisation. What does it allow, what does it forbid, and how is it enforced?"

Reveal answer

Strong answer Requirements: teams ship JVM, Python and Node services; security wants a bounded set of bases they can patch; platform wants fast builds; and on-call engineers want to debug.

The design is a small catalogue of golden images, one per runtime, built from an upstream base and published to the internal registry under a stable name such as registry.internal/base/java21-jre:2026.08.

Each golden image is glibc-based, pins the upstream digest, adds only certificates, time zone data, a non-root user with UID 10001, and the organisation's labels.

A weekly pipeline rebuilds them from the newest upstream digest, scans them, and publishes a new date tag; consuming services rebuild automatically on their next CI run because their Dockerfiles reference the tag through a build argument that a bot bumps.

The policy allows: golden images only for runtime stages; any public image for builder stages, since they never ship. It forbids: Alpine for JVM and Python, for the musl reasons; latest tags anywhere; and root as the runtime user.

It offers a documented escape hatch, a named exception with an expiry date reviewed by security, because a policy without one is bypassed silently.

Enforcement happens in three places: a Dockerfile linter in CI that checks the FROM of the final stage; an admission policy at the cluster that rejects images whose base label is not in the catalogue, which E10 discusses; and a registry scan that reports per-service which golden image version they run, so lagging services are visible.

Trade-offs: a catalogue slows adoption of new runtime versions by the length of the weekly pipeline, and it makes the platform team a dependency.

I would not choose distroless for the default, because debugging in production matters more to most teams than the last vulnerability count; I would offer it as the hardened option for internet-facing services.

Land it A base-image policy is really a supply-chain promise — "we can patch every service by rebuilding five images" — and everything in the design exists to keep that promise cheap.

Likely follow-ups
"A team needs a base you do not offer — say Node 22 with Chromium for PDF rendering. How does the policy handle it?"

Through the exception path, which is designed to be easy to enter and impossible to forget.

The team files a named exception with the image they propose, the reason, and an expiry of at most six months; security reviews it in a fixed weekly slot so the answer arrives in days.

Meanwhile the platform team decides whether the need is general — Chromium for PDFs usually is — and if so builds a golden image for it, at which point the exception closes because the catalogue grew.

The enforcement points know about exceptions: the admission policy reads an annotation on the workload referencing the exception ID, and the registry report lists exceptions with their expiry so the review sees them age.

The one thing I insist on is that the exception image still meets the non-negotiables: glibc, non-root, pinned digest, scanned weekly. A policy that has no exception path gets bypassed with a FROM nobody reports; one with a fast path gets used.

"The catalogue rebuild pushed a broken JRE and forty services picked it up overnight. How does the design prevent a repeat?"

By treating a base image release like any other release, with a canary and a rollback.

The weekly pipeline publishes the new date tag, and a smoke suite builds and starts three reference services on it — a JVM, a Python, and a Node service — and runs their integration tests before the tag is marked current; consuming services reference :current through a build argument only after that promotion, and the previous date tag is one line to revert.

Second, the rollout to services is staggered: the bot opens the bump pull requests in waves, low-risk internal services first, and stops if the first wave's CI fails.

Third, a base image includes its own build attestation and a changelog of package deltas from the previous version, so when something breaks the diff is readable.

Fourth, a fleet dashboard shows which base digest each service runs, so the blast radius is known within minutes rather than by looking at forty pipelines.

"How does the admission policy know an image's base? The image does not say."

It does if the build stamps it.

The golden image's Dockerfile sets LABEL org.opencontainers.image.base.name and, in the consuming service's build, BuildKit can be asked to record the base with the org.opencontainers.image.base.digest annotation, which the metadata action sets from the resolved FROM. The admission policy then reads the label from the image config, which Kyverno and similar controllers can fetch through the registry API, and checks it against the catalogue.

That is spoofable by a determined team, so the second check is structural: a scan job compares the first N layer diff IDs of every deployed image with the layer sets of the catalogue images and flags any image whose lowest layers match no golden base.

Layer matching is not spoofable without rebuilding the base bytes exactly. The label is for the fast path and the layer match is for the audit, and together they are enough for an internal policy.

"What would you cut if you had to enforce something within a month?"

I would cut the admission controller and the layer-matching audit, and ship the catalogue plus the CI linter.

The catalogue: three golden images — JRE 21, Python 3.12, Node 22 — built weekly from pinned digests with a non-root user and certificates, published under a date tag and a current tag.

The linter: a CI step in the shared pipeline template that reads the final stage's FROM and fails if it is not in the catalogue and no exception annotation is present, with the exception process being a file in the repository reviewed by security.

That reaches every service that uses the shared pipeline, which should be most of them, in a month. What is lost is enforcement on services that bypass the shared pipeline, which the registry report can find afterwards.

Admission enforcement and the layer audit come in the following quarter once the catalogue has proven stable, because enforcing a policy before the golden images are trustworthy creates pressure to disable it.

Q65. "Explain the tools for faster JVM startup in a container: jlink, class data sharing, AppCDS, and CRaC. What does each one actually save?"

Reveal answer

The real test Whether you know which of these shrink the image, which shrink startup, and which change the operational model.

Strong answer These four are often listed together but they do different things. jlink assembles a custom Java runtime that contains only the modules your application needs.

jlink --add-modules java.base,java.sql,java.naming --strip-debug --no-man-pages --no-header-files --compress zip-6 --output /jre produces a runtime of around 50 to 70 MB instead of a 200 MB full JRE. It reduces image size and a little of the class-loading work, but it does not change startup much on its own, and Spring Boot's module list has to be discovered with jdeps on the fat jar.

Class data sharing (CDS) is the JVM writing a pre-parsed, pre-verified archive of loaded classes to a file so the next start maps it into memory instead of parsing class files again. The default archive covers only JDK classes.

AppCDS extends that to your application's classes: run the app once with -XX:ArchiveClassesAtExit=app.jsa during the image build, then start with -XX:SharedArchiveFile=app.jsa.

Spring Boot 3.3 and later has first-class support through its training run, and typical results are a 30 to 40 percent startup cut, for example 6 seconds to 4.

CRaC, Coordinated Restore at Checkpoint, is different in kind: it snapshots the fully warmed-up running JVM, heap and all, to disk, and restores it in well under a second.

It needs a CRaC-enabled JDK such as Azul's or the Temurin CRaC builds, requires the application to close sockets and files before the checkpoint and reopen them after, which Spring Boot handles through lifecycle hooks, and the checkpoint contains whatever secrets were in memory, so the snapshot must be treated as sensitive.

JDK 21 and 25 both carry CDS improvements, and JDK 25's ahead-of-time cache goes further than AppCDS by also caching linked and initialised state.

Land it jlink shrinks the image, AppCDS shrinks the startup, and CRaC changes the deployment model — pick the first two by default and adopt CRaC only when sub-second start is a requirement worth the operational cost.

Likely follow-ups
"Walk me through the AppCDS Dockerfile lines for a Spring Boot service and what can go wrong."

In the runtime stage, after the layered COPY lines: RUN java -XX:ArchiveClassesAtExit=/app/app.jsa -Dspring.context.exit=onRefresh -jar /app/app.jar, which starts the application, lets Spring refresh the context, exits, and writes the archive.

Then ENTRYPOINT ["java", "-XX:SharedArchiveFile=/app/app.jsa", "-jar", "/app/app.jar"], and I add -Xshare:on in a test so a mismatch fails loudly rather than silently falling back.

What goes wrong: the training run needs the same environment as production — the same JVM binary, the same classpath, the same JAVA_TOOL_OPTIONS — or the archive is rejected with a warning and startup is unchanged; the training run may need database connections or secrets, which are not available at build time, so the application must tolerate starting without them or use a profile that stubs them; and the archive adds 30 to 80 MB to the image in a layer that changes every build. Verification is -Xlog:class+load showing "source: shared objects file" for most classes.

"How does JDK 25's ahead-of-time cache differ from AppCDS in practice?"

AppCDS caches parsed and verified class metadata, so the JVM skips reading and verifying class files but still links, initialises, and profiles them at runtime.

The ahead-of-time cache introduced by JEP 483 in JDK 24 and extended in JDK 25 goes further: it records classes in their loaded and linked state, and in 25 also caches method profiles and, for some methods, compiled code, so the JIT warms up faster.

The workflow is the same shape: a training run with -XX:AOTMode=record -XX:AOTConfiguration=app.aotconf, an assembly step with -XX:AOTMode=create -XX:AOTCache=app.aot, and production with -XX:AOTCache=app.aot. Reported gains are 40 to 60 percent of startup on Spring-style applications, versus 30 to 40 for AppCDS, and the cache is larger.

As of Aug 2026 it requires JDK 25, which is the current long-term support line, and Spring Boot's training-run support works with it. The constraint about matching JVM and classpath is identical.

"What are the operational implications of CRaC that stop most teams adopting it?"

Four. The checkpoint is a memory image of the process, so it contains every secret, session, and cached credential that was in memory at checkpoint time; it must be stored encrypted and access-controlled, and secrets should be fetched after restore rather than before checkpoint.

Open files and sockets must be closed before the checkpoint and reopened after, which Spring Boot handles for its own resources but every third-party library with a connection pool or a native handle needs to cooperate, and some do not.

The checkpoint is tied to the exact JVM build and CPU features, so an image built with a checkpoint on one CPU generation may fail to restore on another; that makes multi-architecture and heterogeneous fleets awkward.

And the restore itself requires CAP_CHECKPOINT_RESTORE or a privileged step through CRIU, which conflicts with the drop-all-capabilities default and needs a platform allowance. Teams with a strict sub-second requirement, such as scale-to-zero functions, accept those costs; most services get what they need from AppCDS.

"jlink complains about an automatic module or a missing module at runtime. How do you resolve it?"

The two are different problems. A missing module at runtime — a ClassNotFoundException for something like java.sql.Driver or a failure loading elliptic-curve crypto — means jdeps did not detect a module that is only used reflectively, which is common for JDBC, JNDI, crypto providers, and logging.

The fix is to add modules explicitly: --add-modules java.sql,java.naming,jdk.crypto.ec,jdk.unsupported,jdk.management,jdk.zipfs is my usual baseline for a Spring service, and I keep a list per organisation.

The automatic-module complaint arises when jlink is asked to include application jars on the module path; the answer is not to do that — use jlink to build only the JDK runtime image and put the application on the classpath as usual with java -jar, which is how the layered Dockerfile works.

I verify a jlink runtime by running the full integration test suite against the image, because reflection-driven module needs only show up when the code path runs.

Q66 · Design. "A JVM microservice takes 25 seconds to become ready in the cluster, and autoscaling is too slow to be useful. Design the startup-time programme, with expected gains at each step."

Reveal answer

Strong answer Assumptions: Spring Boot 3.5 on JDK 21, a 2-CPU, 2 GB container, image pulled from a regional registry, readiness gated on a health endpoint.

First I would measure where the 25 seconds go, because the design depends on it: image pull time from the node, JVM start to main, Spring context start, and time from context ready to probe success. Then in order of return.

Step one, remove CPU throttling: a 25-second start on 2 CPUs is often 10 seconds on the same code with a higher CPU limit during startup, so I would raise the request or use a startup probe that tolerates it. Expected: 25 to 15 seconds.

Step two, image layout: layered jar, so the pull is one small layer on a code change, and a JRE or jlink base, so the pull is under 100 MB. Expected: pull time from 8 to 2 seconds.

Step three, AppCDS with a training run in the Dockerfile, which Spring Boot supports directly. Expected: context start cut by a third, another 3 to 4 seconds.

Step four, Spring-level trimming: lazy initialisation for rarely used beans, no classpath scanning across large packages, and no synchronous calls to slow dependencies during startup. Expected: 2 to 3 seconds. That gets most services to around 6 seconds, which makes autoscaling useful.

Step five, only if the requirement is stricter, CRaC for sub-second restore or GraalVM native image for a 100-millisecond start, both of which change how the artefact is built and tested.

Trade-offs: each step adds build complexity; AppCDS archives are tied to the exact JVM and classpath and must be regenerated on every build.

What I would not do: start with native image, because it removes JIT peak performance and makes reflection-heavy libraries a project of their own, and it should be justified by a measured need after the cheap steps.

Land it Measure the four phases, fix CPU and image pull first because they are free, then buy startup with AppCDS, and treat CRaC and native image as a separate decision with its own cost.

Likely follow-ups
"How exactly would you measure the four phases in the cluster rather than guessing?"

With timestamps that already exist plus two log lines. Pull time: kubectl describe pod shows the events "Pulling image" and "Successfully pulled image" with timestamps, and their difference is the pull; the kubelet also exposes kubelet_image_pull_duration_seconds.

JVM start to main: the JVM's own -Xlog:startuptime or simply the difference between the container's start time from kubectl get pod -o jsonpath='{.status.containerStatuses[0].state.running.startedAt}' and the first log line the application prints.

Context start: Spring Boot prints "Started Application in N seconds (process running for M)" — the two numbers separate framework time from JVM time. Probe success: the readiness transition time appears in the pod's conditions with a lastTransitionTime.

A one-off script that pulls those four timestamps for the last twenty pods gives a distribution rather than a single anecdote, which is what I want before choosing where to spend effort.

"Removing the CPU limit at startup — what are the ways to do that, and which do you prefer?"

Three ways.

Remove the CPU limit entirely and keep a request, so the pod can burst on an idle node; this is the simplest and is what many platforms recommend for latency-sensitive JVMs, at the cost of noisy-neighbour risk that the request plus cpu.weight still bounds fairly.

Use a startup probe with a long failureThreshold so the pod is not killed while it starts slowly under the limit, which does not make it faster but stops the crash loop.

Or use in-place pod resize, which as of Kubernetes 1.33 lets a controller raise the CPU limit during startup and lower it afterwards without a restart; a small operator can do that automatically.

I prefer the first for most services: no CPU limit, a realistic request, and a startup probe, because a JVM's parallel class loading and JIT genuinely benefit from several cores for ten seconds and then need one.

I would only keep hard limits where a platform's tenancy rules demand them.

"You have two days before a launch. Which steps ship and what do you promise?"

Ship the CPU change and the image layout, promise 25 to about 12 seconds, and say the rest is next sprint.

Day one: remove the CPU limit or raise it, add a startup probe with periodSeconds: 2 and failureThreshold: 30, and change the readiness probe to hit the liveness-style endpoint so it is not gated on slow dependencies. Measure.

Day two: the layered jar and a JRE base so the pull is small, verify with the pull timestamps, and lazy initialisation as a Spring property if the service tolerates it.

Not shipping: AppCDS, because the training run needs a stable build process and testing across the fleet; CRaC and native image, obviously.

The promise is conservative on purpose: I have seen the CPU change alone halve startup, so 12 seconds is likely, and if we land at 8 we look good. The measurement script from the first step is the evidence in the launch review.

"When does GraalVM native image become the right answer rather than a premature one?"

When the requirement is a cold start under a second, or when the memory per instance must be a few tens of megabytes, and the code base can afford the constraints.

Native image compiles ahead of time with closed-world assumptions: reflection, dynamic proxies, resources, and JNI must be declared in reachability metadata, which Spring Boot 3's AOT processing generates for the framework but not for every library; the build takes minutes and gigabytes of memory; there is no JIT, so peak throughput is typically 20 to 40 percent lower for long-running, hot services; and debugging and profiling use different tools.

It fits scale-to-zero functions, CLI tools, sidecars, and services with many small replicas where memory dominates cost. It does not fit a high-throughput service that runs for days, where the JIT's profile-guided optimisation wins and startup is amortised.

The trigger is a measured requirement that AppCDS and CPU changes cannot meet — and a team willing to own the reachability metadata as a maintained artefact.

Drill · PID 1, signals, exit codes & logs

These questions test whether you understand the process that runs inside the container as a Unix process — who gets the signal, what the exit code means, and where the log lines go.

Q67. "Why is being PID 1 inside a container special, and what do --init, tini, and exec in an entrypoint script each solve?"

Reveal answer

The real test Whether you can name the two distinct PID 1 duties — signal defaults and zombie reaping — rather than lumping them together.

Strong answer In every Linux process namespace, and a container is one, the first process gets PID 1 and the kernel treats it differently in two ways.

First, signals with default handlers are not delivered to PID 1 at all: if your program has not installed a handler for SIGTERM, the kernel simply drops it rather than terminating the process.

On a normal system that protects init from accidental kills; in a container it means docker stop waits its grace period and then sends SIGKILL, which cannot be ignored.

Second, PID 1 is the parent of last resort: when a process's real parent dies, the orphan is reparented to PID 1, and when it exits, PID 1 must call wait to collect its exit status.

If PID 1 never does, the dead process remains a zombie, an entry in the process table with no memory but a PID, and enough zombies exhaust the PID limit. The JVM and most language runtimes handle SIGTERM but do not reap orphans.

tini is a tiny init program that does both correctly: it forwards every signal to the child and reaps zombies. docker run --init injects Docker's bundled tini as PID 1 and runs your command as its child, with no Dockerfile change.

exec in an entrypoint script solves a third, related problem: a script that runs java -jar app.jar as a normal command makes the shell PID 1 and the JVM its child, so signals stop at the shell.

Writing exec java -jar app.jar replaces the shell process with the JVM, which then becomes PID 1 itself and receives signals directly.

entrypoint.sh
#!/bin/sh
set -eu
: "${JAVA_OPTS:=}"
if [ -n "${CONFIG_TEMPLATE:-}" ]; then
  envsubst < "$CONFIG_TEMPLATE" > /app/config/application.yaml
fi
exec java $JAVA_OPTS -jar /app/app.jar "$@"

Land it If the process that must receive SIGTERM is not PID 1, the shutdown is a SIGKILL ten seconds late, so either make it PID 1 with exec or put a real init above it with --init.

Likely follow-ups
"The JVM handles SIGTERM. Does a JVM as PID 1 still need tini?"

Only if it will have orphaned grandchildren to reap. A JVM installs handlers for SIGTERM, SIGINT, and SIGHUP, so shutdown works; and the JVM reaps the children it starts itself through ProcessBuilder, because the JDK's process reaper thread calls waitpid on them.

What it does not do is reap processes that were re-parented to it after their own parent died — for example a shell script spawned by the application that backgrounded a worker and exited.

Most services never create such processes, and for them a JVM as PID 1 is fine and is what the exec-form ENTRYPOINT gives.

If the service shells out to tools that fork, such as ImageMagick or a headless browser, tini is cheap insurance: --init at run time or ENTRYPOINT ["tini", "--", "java", ...] in the image, and the JVM remains PID 2 with its own signal handling intact because tini forwards signals.

I check with ps -eo pid,ppid,stat for Z entries during a load test.

"What is the difference between tini and tini -s, and what about dumb-init?"

tini forwards signals to its single child and reaps zombies.

By default it runs as PID 1 and expects to be PID 1; if it is not — for example when run under another init or with --pid=host — it warns that zombie reaping will not work, because only the namespace's PID 1 receives orphans.

tini -s, or the environment variable TINI_SUBREAPER, makes tini register itself as a child subreaper with prctl(PR_SET_CHILD_SUBREAPER), so orphans among its descendants are re-parented to tini instead of to PID 1, and reaping works even when tini is not PID 1.

That is the right setting for a sidecar or a nested tini. -g forwards signals to the child's whole process group, useful when the child is a shell that spawned others.

dumb-init is the same idea from Yelp with process-group forwarding on by default and a rewrite option for signals; Docker's --init bundles tini. Any of them is fine; the important thing is that one exists when needed.

"Why not put the drain logic in a shell trap in the entrypoint instead of relying on the JVM?"

Because the shell does not own the connections, so it cannot drain them; it can only forward the signal and wait, which is what tini already does without the pitfalls. A trap-based script looks like trap 'kill -TERM $child' TERM; java ... & child=$!; wait $child, and it works in the happy path, but it has traps of its own: wait returns when the signal arrives rather than when the child exits, so the script needs a second wait; the exit code must be propagated manually; stdout buffering through the shell can reorder log lines; and a script author who forgets any of this produces a container that appears to stop cleanly and does not.

The application is the only component that knows which requests are in flight and which threads to await, so the drain belongs in its shutdown hook, and the entrypoint's job is to get the signal there unchanged, which exec does in one word.

"How would you test signal handling in CI so the shell-form regression cannot ship?"

A container test that measures the stop.

Start the image with docker run -d, wait for the health endpoint, record a timestamp, run docker stop -t 30, and assert three things: the elapsed time is under a few seconds, the exit code from docker inspect --format '{{.State.ExitCode}}' is 143 or 0 depending on whether the application maps SIGTERM to a zero exit, and the logs contain the application's shutdown line.

A shell-form entrypoint fails the first two; a swallowed signal fails all three. Add a second assertion that docker top shows the JVM as the container's first process, which catches an entrypoint script without exec.

For zombies, a test that has the application shell out a few hundred times and then checks ps for Z states.

All of it runs in under a minute with Testcontainers or a shell script, and it is the single most valuable Docker test I know of because the bug it catches is invisible until production deploys go slow.

Q68 · Scenario. "Every docker stop of the payments container takes exactly 10 seconds, and the shutdown log line the app is supposed to print never appears. What is happening?"

Reveal answer

Strong answer In diagnosis order:

  1. The "exactly 10 seconds" is the fingerprint: it is Docker's default grace period. docker stop sends SIGTERM to PID 1, waits -t seconds, default 10, then sends SIGKILL. A process that handled SIGTERM would exit in well under a second; a constant 10 means the signal was never acted on. Confirm with docker inspect --format '{{.State.ExitCode}}', which will show 137, the SIGKILL code.
  2. Find out who is PID 1 with docker exec name ps -o pid,ppid,cmd or docker top name. Ranked causes: the ENTRYPOINT or CMD is in shell form, so /bin/sh -c is PID 1 and swallows the signal; an entrypoint script runs the JVM without exec; the JVM is PID 1 but a wrapper such as a supervisor script traps and ignores SIGTERM; or the application really does take longer than 10 seconds to drain and the grace is simply too short, which you would see as a partial shutdown log.
  3. Fix the Dockerfile: exec form, ENTRYPOINT ["java","-jar","/app/app.jar"], or an entrypoint script ending in exec, or --init. If the app legitimately needs longer, raise the grace with docker stop -t 30, and in Compose with stop_grace_period: 30s. For Spring Boot, also set server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase=25s so the drain fits inside the grace.
  4. Prevention: an integration test in CI that starts the container, sends docker stop, and asserts both the exit code 143 and a stop time under two seconds. It is a cheap test and it catches every regression of this class.

Land it A stop that always takes exactly the grace period is a signal that never arrived, and the fix is almost always one word, exec, or one flag, --init.

Likely follow-ups
"The ENTRYPOINT is already exec form and the JVM is PID 1 according to docker top. Still exactly 10 seconds. What next?"

Then the signal reaches the JVM and the JVM is not finishing, so I look at what the shutdown is waiting on.

Send SIGTERM with docker kill --signal=TERM and, two seconds later, docker kill --signal=QUIT to get a thread dump in the logs; the dump shows the shutdown hook thread and what it is blocked on.

Common findings: a non-daemon thread from a library or an executor without a shutdown call keeps the JVM alive, and the JVM waits for it until SIGKILL; a shutdown hook that itself blocks, such as a Kafka consumer close waiting for a rebalance or an HTTP client draining a pool with a long timeout; or Spring's graceful shutdown waiting timeout-per-shutdown-phase for a request that never completes.

Another possibility is the image's STOPSIGNAL being set to something the JVM ignores. The absence of the shutdown log line narrows it to before the hook runs, which points at the non-daemon thread case or logging being flushed only on normal exit.

"Where does the 10 seconds come from, and what are all the places it can be changed?"

It is the daemon's default stop timeout, passed by docker stop as the grace between SIGTERM and SIGKILL. It can be set per invocation with docker stop -t 30; per container at creation with docker run --stop-timeout 30, which is recorded in the container config and used by restart and by Compose; in the image with the STOPSIGNAL instruction for the signal, though there is no Dockerfile instruction for the timeout; in Compose with stop_grace_period: 30s; and in Kubernetes with terminationGracePeriodSeconds, default 30, on the pod spec. There is also docker kill, which has no grace at all, and daemon shutdown with live restore off, which uses the shutdown-timeout daemon setting, default 15 seconds, for all containers together. The value must exceed the application's worst-case drain plus a readiness delay; setting it very high hides hung shutdowns behind a long wait, so I keep it near 30 and fix the application when it needs more.

"Does Spring Boot's graceful shutdown work with the default 10 seconds?"

Only by luck. server.shutdown=graceful makes the embedded server stop accepting new connections and wait for in-flight requests up to spring.lifecycle.timeout-per-shutdown-phase, whose default is 30 seconds.

With Docker's 10-second grace, a request that takes 12 seconds to finish is cut off by SIGKILL at 10, and the application's shutdown log line never prints, which looks exactly like the swallowed-signal case.

The rule is that the phase timeout must be a few seconds shorter than the container's grace, so with the default Docker grace I would set the phase timeout to 8 seconds, or better raise the grace to 30 and the phase timeout to 25.

It is also worth knowing that graceful shutdown only covers the web server phase; a Kafka listener container or a scheduler has its own shutdown settings in Spring, and each is a phase with its own share of the timeout.

The integration test that asserts stop time and exit code catches a mismatch between these numbers.

"What exit code do you expect on a clean SIGTERM stop of a JVM, and why might it be 0?"

143 by convention, which is 128 plus 15, because the JVM's default behaviour on SIGTERM is to run shutdown hooks and then terminate with the signal's code.

It is 0 when something in the application called System.exit(0) from a shutdown path, which Spring Boot does not do by default, or when a wrapper mapped the signal. It is 137 when SIGKILL ended it, which means the grace expired.

It is 1 when the shutdown hook threw or the application chose a non-zero code.

Kubernetes and Docker treat 143 as a normal termination for restart-policy purposes with on-failure, since a signalled exit during a stop is expected, but a monitoring rule that alerts on non-zero exits needs to know 143 is benign.

In the CI stop test I assert 143 or 0 explicitly rather than "non-137", so a change to the exit code is noticed and reviewed rather than silently accepted.

Q69 · Scenario. "A long-running container executes a shell script that spawns a worker process per job. After a week, ps inside it shows thousands of <defunct> entries and new jobs fail with 'fork: retry: resource temporarily unavailable'. Walk me through it."

Reveal answer

Strong answer In diagnosis order:

  1. The <defunct> entries are zombies: processes that have exited but whose exit status nobody has collected. They hold no memory, but each holds a PID, and the container's PID limit, set by --pids-limit or the orchestrator, is exhausted. That is the fork error. Confirm with docker exec name ps -eo pid,ppid,stat,cmd | grep Z and cat /sys/fs/cgroup/pids.current against pids.max.
  2. Look at the parent of the zombies. Ranked causes: the workers were started in the background and their original parent exited or never called wait, so they were reparented to PID 1, and PID 1 is the script, which does not reap orphans; or PID 1 is a language runtime or application that handles its own children but not adopted ones; or the script backgrounds workers with & and never waits on them.
  3. Immediate relief: restarting the container clears the table. Then fix the structure: run the container with --init so tini becomes PID 1 and reaps everything reparented to it; that alone solves the adopted-orphan case. In the script, wait on the workers you start, either wait $pid per job or a trap on SIGCHLD.
  4. Prevention: set an explicit --pids-limit so exhaustion happens at a small number and is noticed in a day rather than a week; alert on pids.current approaching the limit; and standardise --init or an ENTRYPOINT of tini -- in the base image so no team has to remember it.

Land it Zombies are a bookkeeping failure of whoever is PID 1, and a two-line fix, an init process, is cheaper than teaching every script to reap.

Likely follow-ups
"--init is on and zombies still accumulate. What next?"

Then the zombies are not orphans; their parent is alive and not reaping them, and tini can only reap what is re-parented to it.

ps -eo pid,ppid,stat,cmd | awk '$3 ~ /Z/' shows the zombies with their parent PIDs; if the PPID is the script or the application rather than PID 1, that process is the culprit.

For a shell script, a worker started with & that the script never waits on stays a zombie under the script until the script exits.

The fix is in the script: wait on the PIDs, or use a job pattern where the script runs workers in the foreground with a limited concurrency, or install trap 'wait' CHLD.

For a JVM or Python parent that spawns subprocesses, the fix is to call the process's wait method or use the library's context manager.

If the parent cannot be changed, restructuring so the workers are spawned by a supervisor that reaps, such as a small Python supervisor using os.waitpid in a loop, is the alternative.

"What number would you set for --pids-limit, and what happens when a legitimate burst hits it?"

A number a few times the measured peak.

For a JVM service, threads count against the pids controller, since Linux threads are tasks, so a Spring Boot service with a 200-thread Tomcat pool, a few dozen JVM threads, and connection pools sits at around 300; I set 1024 for such a service, and 256 for a small script container that spawns a worker per job.

When a legitimate burst hits the limit, fork and clone fail with EAGAIN, which in the JVM surfaces as OutOfMemoryError: unable to create native thread — a misleading message that has cost many hours — and in a script as the "resource temporarily unavailable" error.

That is preferable to the alternative, which is one container consuming the host's whole PID space and taking every neighbour down. Kubernetes exposes it as the kubelet's podPidsLimit, default unlimited on many distributions, and I set it cluster-wide with an alert on container_processes approaching the limit.

"Are zombies actually harmful beyond the PID count?"

Not much, and that is why they go unnoticed for a week.

A zombie has released its memory, its file descriptors, and its CPU; what remains is the process table entry holding the PID, the exit status, and a small kernel structure of a few hundred bytes.

So thousands of zombies cost kilobytes of kernel memory and no CPU. The harm is entirely in the PID exhaustion: the container's pids limit, or without one the host's kernel.pid_max, default 32768 on older systems and 4 million on newer ones, and when that is reached nothing on the host can fork, including SSH logins and the container runtime — which is why an unlimited container with a zombie leak is a host outage rather than a container outage.

A secondary effect is that monitoring tools listing processes get slow, and ps output becomes unreadable. So the fix is urgent for the limit reason and cosmetic otherwise.

"How does the same problem look under Kubernetes, and is there a pod-level fix?"

The same, with a pod-level option that changes the answer. By default each container in a pod has its own PID namespace, so each container's first process is PID 1 with the reaping duty, and a zombie leak is per container.

Setting shareProcessNamespace: true on the pod makes all containers share one PID namespace whose PID 1 is the pause container, the infrastructure process that holds the pod's namespaces, and the pause process does reap orphans — it exists partly for that.

So a pod with a shared process namespace gets a reaping PID 1 for free, at the cost of containers seeing each other's processes and signals, and of the application no longer being PID 1, which changes nothing for a JVM that was not relying on it.

The pids limit is set by the kubelet's podPidsLimit or through pids.max on the pod cgroup. For a job container with a fork-heavy script, I still prefer tini in the image so the behaviour is the same under Docker and Kubernetes.

Q70. "Decode container exit codes for me: 137, 143, 139, 126, 127, and 1. And how do you tell a kernel OOM kill from a Java OutOfMemoryError?"

Reveal answer

The real test Whether you know the 128-plus-signal rule and can point to the exact places to check for an OOM kill.

Strong answer When a process is killed by a signal, the shell convention reports 128 plus the signal number.

SIGKILL is signal 9, so 137 means the process was killed forcibly, and in containers that is either docker stop giving up after the grace period, or the kernel's out-of-memory killer enforcing the memory limit.

SIGTERM is 15, so 143 means the process received a polite stop and exited on it, which is a healthy shutdown for a JVM that does not override the code.

SIGSEGV is 11, so 139 is a segmentation fault: native code, a JNI library, or a bad build touching invalid memory. 126 means the command was found but is not executable, typically a script without the execute bit or a binary for the wrong architecture.

127 means the command was not found, often curl missing in a slim image or a wrong path in ENTRYPOINT. 1 is a generic application failure with its meaning defined by the program.

To distinguish an OOM kill from a Java out-of-memory: docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' shows true 137 for a kernel kill, and the host's dmesg or journalctl -k carries a line naming the killed process and the cgroup.

A Java OutOfMemoryError is the JVM refusing to grow its heap beyond -Xmx; it appears in the application log with a stack trace, and by default the JVM keeps running in a degraded state with exit code unset until something else fails, unless -XX:+ExitOnOutOfMemoryError is set, which makes it exit immediately, or -XX:+CrashOnOutOfMemoryError, which also writes a crash dump.

The two are opposites: the kernel kill happens because total memory exceeded the container limit while the heap may have been fine; the Java error happens because the heap was full while the container may have had plenty of room.

Land it 137 with OOMKilled=true is a limit problem, a stack trace with OutOfMemoryError is a heap problem, and confusing them sends you to raise the wrong number.

Likely follow-ups
"Exit code 137, OOMKilled is false, and nobody ran docker stop. Who sent the SIGKILL?"

Something outside the container's own cgroup accounting. The candidates, in the order I check them: the host-level OOM killer rather than the cgroup one, which happens when the whole node runs out of memory and picks a container process by its badness score — dmesg shows "Out of memory: Killed process" without the "Memory cgroup" prefix; Kubernetes eviction or a pod deletion, where the kubelet's stop path ends in SIGKILL after the grace period — kubectl describe pod shows the events; a liveness probe failure, which restarts the container through the same stop path, so a slow shutdown after a failed probe also yields 137; a process inside the container calling kill -9 on PID 1, such as a supervisor or a misbehaving script; the daemon's own shutdown with live restore off; or an admin's kill -9 on the host, visible in the audit log if enabled. docker events --since shows which of these came through the daemon, and the ones that did not are the kernel and a human.

"Why is a Java OutOfMemoryError so often followed by a kernel OOM kill a few minutes later?"

Because the two are different limits on overlapping memory, and the JVM's reaction to the first pushes toward the second.

When the heap is exhausted the JVM runs repeated full garbage collections trying to free space; each is CPU-intensive and, with parallel collectors, allocates native memory for its work.

The heap stays committed at -Xmx, and if -XX:+HeapDumpOnOutOfMemoryError is set the dump writes gigabytes to the filesystem, whose page cache is charged to the cgroup.

Meanwhile threads pile up waiting on the stalled application, each with a stack, and native buffers from the connection pool grow. Total cgroup usage crosses memory.max and the kernel kills the process.

So the sequence in the logs is a Java OutOfMemoryError, a few minutes of GC thrash, then silence and a 137. That is why -XX:+ExitOnOutOfMemoryError is the right default in a container: it turns the first event into a clean exit before the second can happen.

"How do you get the exit code and reason for a container that has already been removed?"

If the container is gone, its state is gone from docker inspect, so the record must come from elsewhere.

docker events --since 24h --filter type=container --filter event=die prints each container exit with an exitCode attribute, as long as the daemon's event buffer still holds it; the daemon logs in journalctl -u docker also record exits and OOM events.

On the kernel side, dmesg or journalctl -k keeps the OOM killer lines with the cgroup path and the process name.

In Kubernetes the previous container's state is kept in the pod status as lastState.terminated with the reason and exit code until the pod itself is deleted, and kubectl logs --previous returns its logs.

If the pod is gone too, the answer is the central log store and the events collector. The lesson is to ship exit codes and OOM events as metrics — kube_pod_container_status_last_terminated_reason is the Prometheus series — so the evidence outlives the container.

"What does exit code 255 mean, and what about codes above 255?"

255 is either the process exiting with a code out of range — exit(-1) or exit(256) wraps to 255 — or the runtime's own failure to start the process at all: Docker reports 255 when runc could not exec the entrypoint, for example an "exec format error" for the wrong architecture, or when the container was killed by daemon shutdown.

Codes cannot actually exceed 255 because the exit status is a single byte; a script that does exit 300 gets 44. The 128-plus-signal convention occupies 129 through 159 for real signals; 128 alone is not a signal.

Codes from 1 to 125 are application-defined, with 2 conventionally meaning misuse of a command and Java mapping uncaught exceptions to 1.

For Docker specifically, docker run's own exit code is 125 for a daemon error, 126 and 127 for the exec problems, and otherwise the container's code, which is how a script can tell "Docker failed" from "the process failed".

Q71 · Scenario. "A container is restarting every few hours with exit code 137. The application log ends mid-request with no error, no stack trace, nothing. The memory limit is 1 GB and the JVM has -Xmx768m. Diagnose."

Reveal answer

The real test Whether you know that a fixed -Xmx below the limit does not protect you, and can list what else the JVM allocates.

Strong answer In diagnosis order:

  1. The empty log is itself evidence: SIGKILL gives the process no chance to write anything, so a silent end plus 137 points at the kernel, not the application. Confirm with docker inspect --format '{{.State.OOMKilled}}', which should say true, and with dmesg -T | grep -i 'killed process' on the host, which names the process and shows the cgroup's usage at the moment of the kill.
  2. Gather memory evidence before the next kill: docker stats for the container's total resident memory over time, and inside the JVM jcmd 1 VM.native_memory summary with -XX:NativeMemoryTracking=summary enabled, which breaks usage into heap, metaspace, thread stacks, code cache, direct buffers and internal.
  3. Ranked causes. The heap is 768 MB but the JVM's total footprint is heap plus everything else: metaspace of 50 to 150 MB for a Spring application, thread stacks at 1 MB each for a few hundred threads, the code cache of up to 240 MB, direct byte buffers used by Netty or NIO, and native memory from the garbage collector's own structures. That total comfortably exceeds 1 GB. Next: a native memory leak in a library that uses direct buffers or JNI. Less likely: another process in the same container, such as a sidecar script or a shell, sharing the cgroup.
  4. Fix by sizing from the limit instead of guessing: drop -Xmx and use -XX:MaxRAMPercentage=60 to 75 depending on thread count, cap threads with a bounded pool, set -XX:MaxDirectMemorySize when NIO is heavy, and if the numbers still do not fit, raise the limit to 1.5 GB with the data to justify it. Add -XX:+ExitOnOutOfMemoryError so a genuine heap exhaustion also fails cleanly.
  5. Prevention: alert on container memory above 85 percent of the limit, expose JVM memory pools through Micrometer, and run a load test that records peak resident memory before every limit change.

Land it The heap is only the largest tenant of the container's memory, and setting -Xmx near the limit evicts the others straight into an OOM kill.

Likely follow-ups
"You switched to MaxRAMPercentage=70 and capped threads, and it still gets killed every few hours. What next?"

A kill that still happens on a schedule after the heap is sized correctly says the footprint is growing over time, which is a native leak, not a sizing mistake.

I would take two Native Memory Tracking snapshots an hour apart with jcmd 1 VM.native_memory summary.diff and look at which category grew: if it is "Internal" or "Other", that is usually direct byte buffers or a JNI library; if it is "Thread", threads are being created and not reaped; if it is "Class" or "Metaspace", something is generating classes, often a proxy or a scripting engine.

Two things NMT does not see: memory mapped by a native library such as a compression or image library, and glibc malloc arenas, which fragment under many threads and hold memory the JVM has freed.

For the arena case the test is setting MALLOC_ARENA_MAX=2 in the container environment and watching resident memory; if it flattens, that was it, and switching the base image to one with jemalloc is the longer-term fix.

I would also confirm with cat /sys/fs/cgroup/memory.stat that the growth is in anon rather than file, because page cache growth is harmless and reclaimable.

"What is the difference between what docker stats shows and what the OOM killer counts?"

They count different things and that difference is where people get confused. docker stats on cgroup v2 reports usage minus inactive file cache, so it approximates the working set, the memory that could not be given back quickly.

The kernel's limit check uses memory.current, which includes all anonymous memory, kernel memory charged to the group, and the page cache for files the container has read or written, including log files it wrote and the layers it read at startup.

When the group hits memory.max, the kernel first reclaims the cache, so cache alone rarely causes a kill, but it does mean docker stats can show 700 MB while memory.current reads 980 MB and the next burst of allocations tips it over.

The number I actually trust is memory.peak in cgroup v2, which records the high-water mark, together with memory.events, whose oom_kill counter tells me how many kills have happened without needing dmesg access on the host.

"Why MaxRAMPercentage rather than just setting Xmx to a smaller number?"

Because the limit moves and the JVM flag does not. If the limit is raised to 2 GB by a right-sizing change, a fixed -Xmx768m leaves more than a gigabyte unused, and if the limit is lowered, the fixed heap silently becomes too large again.

-XX:MaxRAMPercentage=70 makes the heap 70 percent of whatever the cgroup says at startup, so the memory manifest is the one place to change.

The JVM has read the cgroup limit correctly since JDK 10, and since JDK 17 it reads cgroup v2 as well, so as of Aug 2026 this works on any supported runtime.

The percentage itself is the judgment: it depends on how much non-heap the application needs, and that is exactly what NMT tells me.

A Spring service with 200 threads and moderate NIO usually fits at 65 to 75 percent; a Netty service with large direct buffers might need 50. I would verify by running a load test and checking that memory.peak stays under 90 percent of the limit.

"The kill happens at the same time each night. Does that change your diagnosis?"

Yes, it makes it a workload problem rather than a slow leak, and it points me at whatever runs at that hour.

Candidates: a scheduled job inside the service that loads a large dataset into memory, a nightly report that builds a big response, a batch consumer that pulls a large backlog, or a cache warm-up.

Those produce a spike in heap and direct memory rather than a slow climb, and NMT taken at 3 a.m. would show it clearly.

The fix is often not more memory but bounding the job: stream the export instead of building it in memory, cap the batch size on the consumer with max.poll.records, or move the job to its own container with its own limit so a nightly spike cannot take down the request path.

I would confirm by correlating the kill timestamps from memory.events or the orchestrator's restart log with the scheduler's run log, which usually settles it in five minutes.

Q72 · Design. "Design logging for a fleet of 500 containers across 40 hosts. Cover what the application does, what the Docker daemon does, and what happens when the host disk fills."

Reveal answer

Strong answer Requirements: no log line lost silently under normal load, no container killed because logs filled a disk, per-request correlation across services, and a query interface for on-call.

The design starts with the application rule: write structured JSON lines to standard output and standard error, one event per line, with a timestamp, level, service name, trace identifier and message, and never write log files inside the container, because the container's writable layer disappears with the container and nobody can read it from outside.

The Docker daemon then captures those streams through a logging driver.

On each host I would set the daemon default to the local driver with rotation, "log-driver": "local" and "log-opts": {"max-size": "50m", "max-file": "5"} in daemon.json, which caps every container at 250 MB on disk and keeps docker logs working; the older json-file driver has no rotation by default and is the classic cause of a full disk.

Shipping to the central store is done by a host agent such as Fluent Bit or Vector reading the local log files, rather than by the fluentd driver sending directly from the daemon, because a direct driver blocks or drops container output when the collector is unreachable and its buffering is limited.

The agent forwards to a store such as Loki or OpenSearch, with a retention of 14 days hot and 90 days cold.

When the host disk fills anyway, the rotation bounds the damage to the configured cap, and disk-usage alerts at 80 percent give warning; I would also set --tmpfs /tmp and a read-only root filesystem for services, so a misbehaving app cannot fill the disk through other paths.

Trade-offs: local files add a hop and a few seconds of latency; the alternative, direct shipping, trades that latency for loss under collector outages, which is the wrong trade for audit logs.

What I would not do: mount a shared log directory into every container, because it recreates file permission and rotation problems that the driver already solves.

Land it Application writes to stdout, daemon rotates locally, an agent ships asynchronously — that separation is what lets a collector outage cost latency instead of data.

Likely follow-ups
"What happens to a container's output when the host agent cannot keep up and the local files rotate before they are shipped?"

Lines are lost, and the design should make that loud rather than silent. With max-size 50m and max-file 5, a container writing 10 MB per minute has about 25 minutes of buffer on disk before the oldest segment is deleted.

If Fluent Bit or Vector falls behind that far, the segment it has not read yet disappears and those lines are gone.

Two controls: the agent tracks its position per file, and both agents export a metric for files it lost or lag between write and ship, which I alert on.

And I size rotation from the loudest container's peak rate, not from an average, so the buffer covers at least an hour of the noisiest service.

Under a genuine collector outage, the agent's own disk buffer, storage.type filesystem in Fluent Bit with a size cap, holds data on the host separately from the container log files, so the rotation and the shipping backlog are two different budgets.

I would verify by stopping the collector for 30 minutes in staging and confirming no lines are missing afterwards.

"Why the local driver and not json-file with rotation options? They both rotate."

They do both rotate once you set the options, and that is the first point: json-file ships with no limits by default, so a host that has not set max-size fills its disk, while local defaults to 100 MB across five files.

The second difference is format and cost: json-file writes each line wrapped in a JSON object with the stream name and timestamp, roughly doubling the bytes for short lines, and it must escape the application's own JSON, which makes files bigger and slower to write.

local stores a compact binary framing, uses less disk and CPU, and compresses rotated files.

The cost is that local files are not human-readable with cat and third-party agents historically could not tail them; as of Aug 2026 Fluent Bit and Vector both read the json-file format directly but handle the local driver by reading through docker logs or the API, which is less efficient.

So on Kubernetes hosts, where the kubelet writes plain files under /var/log/pods and agents tail those, the question is moot; on plain Docker hosts I choose based on which agent I run.

"How does the host keep the daemon itself from blocking a container when the log pipe is full?"

By default it does not, and that is a real failure mode.

The container's stdout is a pipe into the daemon; if the daemon's logging driver stalls, the pipe buffer of 64 KB fills and the container's next write blocks, which freezes the application on a log line.

The daemon has a per-container ring buffer to decouple that: "mode": "non-blocking" with "max-buffer-size": "4m" in the log options. In non-blocking mode a stalled driver drops lines once the buffer is full instead of freezing the process.

For the local and json-file drivers the stall is only ever disk contention, so blocking mode is acceptable; for a network driver such as fluentd or gelf, non-blocking is essential, and the trade is exactly the reason I ship from files rather than from the daemon.

I would verify the setting with docker inspect --format '{{.HostConfig.LogConfig}}' and test it by pausing the collector and checking the container's request latency does not move.

"What breaks at 10 times the scale, 5,000 containers on 400 hosts?"

Three things.

The store: at that scale the log volume is probably several terabytes a day, and a single Loki or OpenSearch cluster needs sharding and tiered storage, so retention gets a cost model, 14 days hot for everything and 90 days cold only for audit and payment services, decided by label, not by default.

The agents: 400 hosts each running one agent is fine, but the configuration has to be managed as code and rolled out gradually, because a bad parser regex pushed to 400 hosts at once drops or duplicates every line simultaneously.

And cardinality: labels like request id or user id in the index make the store unusable, so the rule is that indexed labels are only service, environment, host, and level, and everything else is searched in the line.

I would also add sampling for debug-level lines at the agent, keeping every warning and error and one in ten of the rest, and a per-service byte quota with an alert, because at 5,000 containers one service in a log loop can double the bill in an afternoon.

"Why not have the application ship logs directly to the store over the network?"

Because it couples the application's request path to the log store's availability, and because it takes away every tool that works with stdout.

If the store is slow, the logging library's queue fills and the application either blocks or drops, and the developer now owns retry, buffering, and back-pressure inside every service in every language.

With stdout, the application's only dependency is a pipe that the kernel guarantees, the daemon handles durability to disk, and the agent handles the network with its own buffer and retries, so a store outage costs a few minutes of latency, not application threads.

The stdout rule also means docker logs, kubectl logs, and a developer's terminal all work without configuration, which matters more during an incident than any feature of the store.

The one exception I accept is audit events, which are a business record rather than a log; those go to a durable queue with an explicit acknowledgement, because for them loss is a compliance failure, not an inconvenience.

Q73 · Scenario. "An on-call engineer says 'the logs from before the crash are gone'. The container has restart: always and was restarted by Docker. Where did the logs go, and where might they still be?"

Reveal answer

Strong answer In diagnosis order:

  1. Establish what "restarted" means, because the answer hinges on it. A restart policy such as always, unless-stopped or on-failure restarts the same container: same identifier, same writable layer, same log file. In that case docker logs name still contains every line from before the crash, and the engineer probably ran docker logs --tail 100 or looked at a dashboard that only shows the current process's lines. Check with docker inspect --format '{{.RestartCount}} {{.State.StartedAt}}'.
  2. If instead the container was recreated, by docker compose up after an image change, by a deployment tool, or by docker run --rm, it is a new container with a new log file, and the old one was deleted along with the old container. Ranked, that is the most common cause of truly lost logs.
  3. Next, check whether the application wrote to a file inside the container rather than to standard output; docker logs shows nothing from files, and the file is gone if the container was removed. Also check rotation: with max-size and max-file set, older segments are deleted, and a crash that logged a burst of stack traces can rotate the interesting lines away in seconds.
  4. Where they might still be: a central log store if a shipper was configured; the host's journald if the driver was journald, searchable with journalctl CONTAINER_NAME=name; and the rotated files under /var/lib/docker/containers/<id>/ if the container still exists.
  5. Prevention: ship logs off the host, log to stdout only, size rotation to hold at least an hour of peak output, and name the restart policy in the runbook so the on-call engineer knows whether a restart preserves the container.

Land it A restart keeps the container and its logs, a recreate discards both, and the only logs you can rely on after a crash are the ones that already left the host.

Likely follow-ups
"The container was restarted by the policy, so the log file survived, but docker logs still starts after the crash. Why?"

Two plausible causes.

First, rotation: if the crash produced a burst of output, a stack trace repeated thousands of times, or a tight loop logging an error, the rotation could have cycled through all five 50 MB segments in seconds, and the pre-crash lines were in the segment that was deleted.

ls -la /var/lib/docker/containers/<id>/ shows the segment timestamps and answers that in one look. Second, the engineer is looking at the wrong window: docker logs --since 10m or a dashboard time picker anchored to "last restart" excludes the earlier lines.

I would run docker logs --until "$(docker inspect --format '{{.State.StartedAt}}' name)" name | tail -200 to see exactly what was written before the current start.

If that is empty and the segments are all newer than the crash, rotation ate it, and the fix is a larger rotation budget and a rate limit on repeated log lines in the application's logging configuration.

"How would you tell, after the fact, whether the container was restarted or recreated?"

The container id is the answer. A restart keeps the same 64-character id and increments RestartCount; a recreate produces a new id, and the old one is only visible if it was not removed, via docker ps -a.

So I run docker inspect --format '{{.Id}} {{.RestartCount}} {{.Created}} {{.State.StartedAt}}': if Created is older than the crash and RestartCount is greater than zero, it was restarted; if Created is after the crash, it was recreated.

The daemon's events log settles it independently: docker events --since 2h --filter container=name shows die, start for a restart, versus die, destroy, create, start for a recreate, and the destroy event names the tool that did it through its labels.

On Kubernetes the equivalent is kubectl logs --previous, which the kubelet keeps for exactly one prior container, and the pod's restartCount.

"The application does write to a file inside the container, and the container was removed. Is anything recoverable?"

Usually not, and it is worth being precise about why. The file lived in the container's writable layer, which on the overlay2 driver is a directory under /var/lib/docker/overlay2/<layer-id>/diff/.

When the container is removed, the daemon deletes that directory, and the blocks are returned to the filesystem; ordinary file recovery tools are the only remaining option and they rarely work on a busy host.

The exceptions: if the file was on a named volume or a bind mount, it is still on the host, because volumes are not deleted with the container unless docker rm -v or docker compose down -v was used; and if the process was still running when someone captured docker export or docker commit, the file is in that archive.

So the first question is "was there a volume", answered from the compose file or the deployment manifest.

The lasting fix is to stop writing files, or if a library insists on a file, to tail it to stdout with a sidecar or to point it at a volume with rotation.

"How much rotation is enough? Give me the calculation."

I size it from the noisiest container's peak rate and the time it takes someone to look.

Measure the log rate per container during a load test or from the shipper's metrics; suppose the loudest service does 2 MB per minute normally and 20 MB per minute during an error storm.

I want at least an hour of storm retained locally, which is 1.2 GB, so max-size 100m with max-file 12.

For 40 containers per host that is a worst case of about 48 GB, which has to fit on the host's disk with room to spare, and if it does not, the answer is a larger disk or a lower cap with a faster shipper, not silence.

I then set the disk alert at 80 percent and verify the rotation actually happens by filling one container with yes | head -c 300M in staging and watching the segments roll.

The number goes in the daemon configuration managed as code, because a rotation setting that lives only in one engineer's memory is the next incident.

Q74 · Design. "Design the graceful-shutdown story for an HTTP service container that must finish in-flight requests within 30 seconds, from the orchestrator's stop signal to the process exit."

Reveal answer

The real test Whether your timeline adds up — the readiness gap, the drain, and the grace period must nest inside each other.

Strong answer Assumptions: Spring Boot 3.5 on JDK 21, requests take up to 20 seconds in the worst case, and a load balancer or service mesh routes traffic based on readiness. The design is a timeline with four nested budgets.

First, the signal must reach the JVM: exec-form ENTRYPOINT or exec in the script, so SIGTERM arrives at PID 1 immediately.

Second, stop accepting new work before finishing old work: on SIGTERM the application flips its readiness endpoint to failing so the load balancer removes it, and continues to serve existing connections.

Because the load balancer needs a few seconds to observe the change, I add a pre-stop delay of about 5 seconds before the server starts closing listeners.

Third, the drain: server.shutdown=graceful makes Tomcat stop accepting connections and wait for in-flight requests, bounded by spring.lifecycle.timeout-per-shutdown-phase=20s, matching the worst-case request.

Fourth, the grace period the runtime allows before SIGKILL must cover the sum: 5 seconds of delay plus 20 seconds of drain plus a margin, so docker stop -t 30, stop_grace_period: 30s in Compose, or terminationGracePeriodSeconds: 30 in Kubernetes.

Background work is handled by the same hook: the message consumer stops polling on SIGTERM and finishes the batch it holds, and the thread pool is shut down with a bounded await.

Trade-offs: a longer drain slows rolling deployments proportionally, 30 seconds per instance, so a fleet of 50 with one at a time takes 25 minutes; I would deploy in parallel batches to compensate.

What I would not do: rely on the default 10-second grace and hope, or set the grace to 5 minutes, because that hides stuck shutdowns behind a long wait; and I would not put the drain logic in a shell trap in the entrypoint, because the application owns its connections and only it can drain them correctly.

Land it Graceful shutdown is arithmetic: readiness gap plus drain must be less than the grace period, and the signal must reach the process that owns the sockets.

Likely follow-ups
"Walk me through what happens if a request takes 25 seconds during the drain. What does the client see?"

With timeout-per-shutdown-phase=20s, Spring waits 20 seconds for in-flight requests, then proceeds to close the context; Tomcat's connector is already stopped, so no new requests arrived in that window. The 25-second request is still executing on a Tomcat thread at the 20-second mark.

Spring logs a warning that graceful shutdown timed out, then shuts the executor and the connection pool. The request thread then either completes and tries to write a response over a connection that may already be closed, or fails when it touches the closed datasource.

Either way the client gets a reset connection or a 502 from the load balancer, not a clean response.

So the phase timeout must be at least the worst-case request time, and the honest fix for a 25-second request is either to raise the drain to 25 and the grace to 35, or to make that request shorter.

If the orchestrator's grace expires first, the JVM gets SIGKILL and even the warning is not written, which is why the grace period must be the largest of the three numbers.

"How do you make the readiness endpoint fail on SIGTERM in Spring Boot, and how do you add the delay?"

Spring Boot's actuator does the first part on its own: when the context begins to close, the availability state flips to REFUSING_TRAFFIC and /actuator/health/readiness returns 503, provided management.endpoint.health.probes.enabled=true.

The delay is the piece people miss: Spring starts closing the web server immediately, so the load balancer has no time to observe the 503 before connections are refused.

On Kubernetes I add a preStop hook with sleep 5 and set terminationGracePeriodSeconds to cover it, because Kubernetes runs the hook before sending SIGTERM and removes the pod from endpoints in parallel.

On plain Docker there is no preStop, so the delay goes in the application: a ContextClosedEvent listener with the highest precedence that sets readiness to refusing and sleeps 5 seconds before the rest of the shutdown proceeds.

I verify by running a load test at 200 requests per second, issuing docker stop, and checking the error count is zero; if it is not zero, the number that is wrong is almost always the delay.

"The service also consumes from Kafka. What does the shutdown do with a batch it is halfway through?"

The consumer must stop polling, finish the records it already holds, commit the offsets, and only then leave the group, and it must all fit inside the drain budget.

With Spring Kafka, the container's shutdown does exactly that: on context close it stops the poll loop, lets the current listener invocation complete, commits, and closes the consumer, which triggers a group rebalance so another instance takes the partitions.

The knob is spring.kafka.listener.immediate-stop, which should be false so the batch completes, and the batch size, max.poll.records, which bounds how long "finish the batch" can take; 500 records at 20 milliseconds each is 10 seconds, so it fits inside the 20-second drain, but 5,000 would not.

If the grace expires mid-batch and the JVM is killed, the uncommitted records are redelivered to the next instance, which is why the consumer must be idempotent regardless.

I would verify with a deploy under load and a check that consumer lag recovers within the rebalance time and that no record was processed twice by counting guard-table conflicts.

"The rolling deploy of 50 instances is too slow at 30 seconds each. What would you change?"

The drain time per instance is a floor set by the worst-case request, so the lever is parallelism, not shortening the drain.

With a 25 percent batch, 12 or 13 instances drain at once and the deploy takes about two minutes instead of 25, at the cost of temporarily losing a quarter of capacity, which must be checked against peak load; on Kubernetes that is maxUnavailable: 25% or, better, maxSurge: 25% with maxUnavailable: 0 so new instances come up before old ones drain and capacity never dips.

The second lever is the request itself: if the p99 is 2 seconds and only a report endpoint takes 20, moving that endpoint to an asynchronous job with a 202 response drops the drain budget to 5 seconds for everyone.

What I would not do is cut the grace period below the real drain time to make the deploy faster, because that converts a slow deploy into a deploy that drops requests, and nobody will connect the dropped requests to the setting.

"How do you prove in production that shutdown is graceful, not just configured?"

Three signals. First, the shutdown log line: Spring writes "Commencing graceful shutdown" and then "Graceful shutdown complete" when it succeeds, or a warning when it times out; a log query for the warning across the fleet tells me which services have requests longer than their drain.

Second, exit code: a graceful exit is 143 or 0, and a count of 137 exits at deploy time means the grace period expired and the JVM was killed, which I get from the orchestrator's termination reason or from docker inspect.

Third, client-observed errors correlated with deploy timestamps: a 5xx or connection-reset spike lasting a few seconds at each deploy is the readiness gap being too short.

I would put those three on the deploy dashboard, so each deployment shows its own graceful-shutdown success rate, and I would run the load-test-plus-stop check in the pipeline for the template service so a regression in the platform's defaults is caught before it reaches 80 services.

Drill · Resource limits, the JVM & run-time hygiene

These questions test whether you can size a container for a JVM with numbers, explain why a throttled CPU looks like a slow application, and run containers without leaking secrets or root-owned files onto the host.

Q75. "Explain how --memory, --memory-swap, --cpus and --cpu-shares are enforced. What does the kernel actually do when a container hits each one?"

Reveal answer

Strong answer All of these are written into a cgroup, a kernel accounting group that every container's processes belong to; on any current host that is cgroup v2, where the files live under /sys/fs/cgroup/. --memory=1g writes memory.max.

When the group's usage, which counts heap, native memory, and the page cache for files the container reads, reaches the limit, the kernel first tries to reclaim cache pages; if it still cannot satisfy an allocation, the OOM killer picks the process in the group with the largest usage and sends SIGKILL, which is the 137 you see.

--memory-swap sets the total of memory plus swap, so --memory=1g --memory-swap=1g disables swap for the container, while the default of twice the memory allows 1 GB of swap; most orchestrators disable swap because swapping a JVM heap turns garbage collection into disk reads.

--cpus=1.5 writes cpu.max as a quota over a period, by default 150 000 microseconds of run time per 100 000-microsecond period.

The kernel's Completely Fair Scheduler counts run time across all the container's threads, and when the quota is used up, every thread in the group is paused until the next period starts.

That pause is throttling, visible in cpu.stat as nr_throttled and throttled_usec, and it is why a 16-thread JVM under --cpus=1 burns its quota in a few milliseconds and then waits.

--cpu-shares is different in kind: it writes cpu.weight, a relative priority that only matters when the host is contended; a container with 2048 shares gets twice the time of one with 1024 when both want the CPU, and both get everything they want when the host is idle. Limits are hard ceilings; shares are proportions.

Land it Memory limits kill and CPU limits pause, and the second one is the sneaky one because nothing dies — the application just gets slow in 100-millisecond steps.

Likely follow-ups
"Show me how you would detect CPU throttling in production and decide whether it matters."

The number lives in the cgroup: cat /sys/fs/cgroup/cpu.stat inside the container shows nr_periods, nr_throttled, and throttled_usec.

The ratio of throttled to total periods is the fraction of 100-millisecond windows in which the container ran out of quota, and throttled_usec divided by nr_throttled is the average pause per throttled window.

cAdvisor exports these as container_cpu_cfs_throttled_periods_total and container_cpu_cfs_throttled_seconds_total, so the alert is a throttled ratio above about 25 percent sustained.

Whether it matters is a latency question: a batch job throttled half the time is fine; a request-serving service throttled 10 percent of periods has a p99 with a 50 to 90 millisecond step in it that comes from nowhere in the code.

I would confirm the link by overlaying the throttled ratio and the p99 on one graph, and by temporarily raising the limit on one instance and watching its p99 drop while its siblings do not.

"Why does a 16-thread JVM under --cpus=1 get throttled even when the average CPU usage is 30 percent?"

Because the quota is enforced per 100-millisecond period, not on the average. One CPU's worth of quota is 100 milliseconds of run time per period.

If 16 threads all become runnable at once, on a host with 16 cores they each run in parallel and together consume 100 milliseconds of quota in about 6 milliseconds of wall time; for the remaining 94 milliseconds every thread in the group is stopped.

A request that arrived in that window waits 94 milliseconds for nothing. Then the next period starts and the pattern repeats.

The average across the second can be 30 percent while the request latency is dominated by the stalls, because the load is bursty and the bursts hit the cap instantly.

The mitigations are fewer threads, so the burst is smaller, a higher limit or no limit, or a request-shaped workload that stays under quota.

As of Aug 2026 the kernel's burst feature, cpu.max.burst, lets a group bank unused quota from quiet periods to cover a spike, and some runtimes expose it, which softens this considerably.

"What does the JVM do with the limit? How many GC threads and how much heap does it pick under --cpus=1.5?"

The JVM rounds the quota up to compute availableProcessors, so --cpus=1.5 gives 2.

That number drives everything sized from CPU count: the number of parallel GC threads, the common ForkJoin pool, and the default choice of garbage collector, because with fewer than 2 processors or less than 2 GB the JVM picks Serial GC rather than G1, which surprises people who expected G1's pause behaviour.

Heap comes from the memory limit, not the CPU limit: 25 percent of memory.max by default, or whatever MaxRAMPercentage says. --cpu-shares is different: older JVMs used shares to derive a CPU count, which produced absurd results, and since JDK 19 shares are ignored for that purpose.

I verify what the JVM actually decided with java -XX:+PrintFlagsFinal -version | grep -E 'ParallelGCThreads|MaxHeapSize|UseSerialGC' run inside the container with the real limits, and with -Xlog:os+container=info, which prints the cgroup values the JVM read at startup.

"When would you deliberately not set a CPU limit at all?"

For latency-sensitive request-serving services on a host or node pool where I control the neighbours.

Without a limit, the container can burst to whatever the host has spare, and the CPU request or shares still guarantees its fair share under contention, so the failure mode changes from "my p99 has 100-millisecond stalls" to "under contention I get my share", which is a better failure mode for that class of service.

The costs: capacity planning is less predictable because a runaway service can consume the whole node, and a noisy neighbour can steal from a service that has not set a request high enough.

So the rule I use is requests always, limits only where I need a hard cap: batch jobs, multi-tenant nodes, anything whose burst could starve a critical sibling.

On Kubernetes this is the "no CPU limits, always CPU requests" position that many platform teams adopted, and the check that it is safe is a node-level CPU saturation alert plus a per-pod throttling dashboard that should read zero.

"What actually happens at the memory limit before the kill? Is there anything between 'fine' and 'dead'?"

Yes, and it is worth knowing because it explains slowdowns that happen before any kill.

When the group approaches memory.max, the kernel enters reclaim: it drops clean page cache belonging to the group, writes back dirty pages, and, if swap is enabled for the group, swaps anonymous pages out.

During reclaim the allocating thread stalls, which shows up as latency with no CPU usage, visible in memory.stat as rising pgscan and pgsteal counters and in memory.pressure under pressure stall information. Only when reclaim cannot free enough does the OOM killer run.

cgroup v2 adds memory.high, a soft limit below memory.max at which the kernel throttles the group's allocations and reclaims aggressively without killing; Docker does not expose it directly as of Aug 2026, but Kubernetes can set it through the memory QoS feature.

For a JVM the practical rule is to keep memory.peak below 90 percent of the limit so the group never lives in reclaim, because a JVM in reclaim looks like a GC problem to everyone who does not check the cgroup.

Q76 · Scenario. "A Java 8 service was moved from a VM into a container with a 2 GB limit and now OOM-kills within minutes. The developer says the JVM 'ignores the memory limit'. Is that true, and what do you do?"

Reveal answer

Strong answer In diagnosis order:

  1. Check what the JVM believes it has: docker exec name java -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|UseContainerSupport', and jcmd 1 VM.info for the exact build. If MaxHeapSize is around a quarter of the host's RAM, for example 16 GB on a 64 GB node, the developer is right in effect.
  2. Ranked causes. First, an old JVM: before JDK 10, and before 8u191 for the Java 8 line, the JVM sized its default heap from the host's total memory as seen in /proc/meminfo, because it had no idea about cgroups. A 64 GB host gives a 16 GB default heap in a 2 GB container, and the kill follows as soon as the heap grows. Second, a modern JVM running on cgroup v2 but too old to read it, which needed JDK 15 or 8u372 and later. Third, -XX:-UseContainerSupport explicitly disabled somewhere in a startup script. Fourth, the limit is honoured but the percentage is wrong: the default MaxRAMPercentage is 25, which under-uses memory, while someone may have set 90, leaving nothing for non-heap.
  3. Fix: upgrade to a current Java 8 build at minimum, and preferably to JDK 21, where container support is on by default and reads both cgroup versions. Then set -XX:MaxRAMPercentage=70 or so, verify with the PrintFlagsFinal check inside the container, and confirm the CPU side with Runtime.getRuntime().availableProcessors(), which also follows the quota on a container-aware JVM.
  4. Prevention: a startup log line printing the JVM version, heap maximum and available processors, and a CI check that rejects base images with JDK builds older than the container-aware cut-off.

Land it The JVM does not ignore limits; old JVMs never learned to read them, and the fix is a build number before it is a flag. E3 covers the garbage-collector side of this sizing.

Likely follow-ups
"You upgraded the JDK and it still gets killed at 2 GB. What next?"

Then the heap is honouring the limit and something outside the heap is eating the rest. I would run jcmd 1 VM.native_memory summary after starting with -XX:NativeMemoryTracking=summary, which itemises metaspace, thread stacks, code cache, GC structures, and direct buffers.

Common culprits are a metaspace growing from a classloader leak, hundreds of threads at 1 MB stack each, and NIO direct buffers with no cap.

I would compare the cgroup's memory.current with the JVM's own total, and if they differ by hundreds of megabytes, look for native libraries or page cache from file writes, which counts against the container until reclaimed.

The fix is per pool: -XX:MaxMetaspaceSize, -Xss512k, -XX:MaxDirectMemorySize, and a lower MaxRAMPercentage so the sum fits.

"How do you tell an OOM kill from a Java OutOfMemoryError in the logs?"

They come from different layers and look completely different. A Java OutOfMemoryError is thrown by the JVM when the heap is full after a garbage collection, so it appears in the application log with a stack trace and the process may keep running.

A kernel OOM kill is silent to the application: the process gets SIGKILL, the container exits with code 137, docker inspect --format '{{.State.OOMKilled}}' prints true, and dmesg or journalctl -k on the host shows a line naming the process and the cgroup.

If I see 137 with nothing in the app log, it is the kernel. If I see the Java error, the heap is too small for the work but the container limit was never reached.

"Why is the default MaxRAMPercentage only 25?"

Because the default was chosen for a shared host, not a container. On a bare machine the JVM assumed it was one process among many and took a quarter of physical RAM for the heap by default.

When container support was added, the engineers kept that ratio but applied it to the cgroup limit, so a 2 GB container gets a 512 MB heap.

That is safe, since it leaves plenty for non-heap memory, but wasteful when the container is dedicated to one JVM. In a container I set it explicitly, usually between 60 and 75 depending on how much non-heap memory I measured, and I never leave the default because it silently throws away most of the memory I am paying for.

"Would a memory request without a limit have avoided this?"

It would have hidden it rather than avoided it.

With no limit the cgroup reports the host's total memory, so an old JVM would size its heap from a 64 GB host, and a modern one would do the same because MaxRAMPercentage is read from whatever the cgroup allows.

The service would then grow until it competed with neighbours, and the kernel's OOM killer would pick a victim across the whole node, possibly a different service. A limit is what turns a fleet-wide problem into a single-container problem with a clear exit code.

So I keep the limit and fix the JVM sizing; removing limits for memory is the wrong lesson, though for CPU it is often the right one.

Q77 · Design. "Design the JVM memory configuration for a Spring Boot service in a 2 GB container with 2 CPUs serving about 300 requests per second. Give numbers."

Reveal answer

The real test Whether the numbers you give add up to less than 2 GB once you have listed everything outside the heap.

Strong answer Assumptions: JDK 21, G1 garbage collector, Tomcat with a 200-thread pool, moderate use of NIO direct buffers, and no in-process cache larger than a few tens of megabytes. I start from the budget rather than the heap.

Out of 2048 MB, I reserve: about 120 MB metaspace for a Spring application with a few thousand classes, capped with -XX:MaxMetaspaceSize=192m so a classloader leak fails visibly instead of eating the container; thread stacks, 200 request threads plus perhaps 60 others at the default 1 MB each, so 260 MB of reservation of which perhaps 100 MB is touched, which I reduce with -Xss512k to a 130 MB reservation; code cache at up to 240 MB, which I cap at -XX:ReservedCodeCacheSize=128m because a service of this size will not fill more; direct memory, capped at -XX:MaxDirectMemorySize=128m; garbage-collector structures and native overhead, roughly 10 percent of heap, so 120 MB. That non-heap total is around 600 to 700 MB, leaving about 1300 MB, which is why I set -XX:MaxRAMPercentage=62 rather than the popular 75, giving a heap maximum of roughly 1270 MB. I set -XX:InitialRAMPercentage=62 as well so the heap is committed up front and the container's usage is stable rather than growing into a surprise.

I add -XX:+ExitOnOutOfMemoryError so a heap exhaustion restarts the process cleanly, and -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp with a tmpfs mount sized for one dump.

For 2 CPUs I keep G1, since ZGC wants more headroom and cores, and set -XX:ActiveProcessorCount=2 only if the quota is fractional, because the JVM rounds fractions up.

Trade-offs: the fixed initial heap loses the ability to share memory with neighbours, which is fine under a hard limit. I would not use 90 percent for the heap, because the kernel kill that follows tells you nothing, and I would not leave metaspace unbounded.

Land it Size the non-heap first, give the heap what is left, and cap every pool so failure comes as a Java error with a dump rather than a silent 137.

Likely follow-ups
"How would you verify those numbers are right once it is running?"

I would turn on native memory tracking for a soak run, -XX:NativeMemoryTracking=summary, and after an hour at 300 requests per second run jcmd 1 VM.native_memory summary to read committed bytes per pool.

Then I would compare the JVM's total with the cgroup's memory.current and memory.peak from /sys/fs/cgroup, since the cgroup also counts page cache and any native libraries. If the peak sits under about 85 percent of the 2 GB limit, the budget holds.

I would also graph jvm_memory_used_bytes by area from Micrometer, and the throttling counters in cpu.stat, because a heap that is too small shows up first as GC time, not as a kill.

"What changes if the traffic doubles to 600 requests per second?"

Memory pressure grows mostly through allocation rate and thread count, not steady heap. At double the rate G1 needs more young generation to keep pause frequency sane, so the heap I set aside may start collecting every second.

I would first check whether the 200-thread pool is even saturated; if not, memory barely changes and CPU is the constraint. If threads climb, stacks and per-request buffers climb with them.

My move would be to scale out with a second replica rather than push the 2 GB container harder, because the JVM runs better with headroom, and to consider a 3 GB container with MaxRAMPercentage unchanged, which keeps the same ratio and simply gives G1 room.

"Why not ZGC or Shenandoah?"

Both are low-pause collectors that do most of their work concurrently, and they pay for that with extra memory and extra CPU threads.

On 2 CPUs the concurrent GC threads compete directly with the request threads, and ZGC in particular wants perhaps 10 to 20 percent more heap than G1 for the same live set to avoid allocation stalls.

With a 1.3 GB heap and 2 cores, G1's pauses at this size are typically 10 to 30 milliseconds, which is fine for a 300 request per second API.

I would switch to ZGC only if p99 pause time became the measured problem and I could give the container 4 or more cores.

"Would you set -Xmx directly instead of the percentage?"

In a container I prefer the percentage because it moves with the limit: if someone changes the Compose or Kubernetes limit from 2 GB to 3 GB, the heap follows without a second edit, and a mismatch between the two is exactly the kind of bug that surfaces at 03:00.

-Xmx wins over the percentage if both are set, so I make sure no startup script sets it.

The exception is a service with a known fixed working set where I want identical behaviour on every machine regardless of limit; then a fixed -Xmx plus a limit with explicit headroom is clearer.

Either way the value must appear in the startup log so the on-call engineer can read it.

"What would you cut if you had five minutes to configure this?"

Three flags. -XX:MaxRAMPercentage=60, -XX:+ExitOnOutOfMemoryError, and -XX:MaxMetaspaceSize=256m. The first keeps the heap safely inside the container with room for the unmeasured non-heap pools. The second makes a heap exhaustion restart the container cleanly instead of limping.

The third bounds the one pool that a classloader leak can grow without limit.

I would skip the stack size, code cache, and direct memory caps, because their defaults fit inside the remaining 40 percent for a typical Spring service, and I would return with native memory tracking numbers to tighten them later.

Q78 · Scenario. "A service starts in 8 seconds on a laptop and 40 seconds in the container, and in steady state p99 latency is three times worse although CPU usage in the dashboard shows only 30 percent. The container runs with --cpus=1. Explain."

Reveal answer

Strong answer In diagnosis order:

  1. Read the throttling counters, which the utilisation dashboard hides: cat /sys/fs/cgroup/cpu.stat inside the container, looking at nr_periods, nr_throttled and throttled_usec. A throttled-to-periods ratio above a few percent confirms it. Also check java -XX:+PrintFlagsFinal -version | grep ActiveProcessorCount and the JIT compiler thread count.
  2. Explain the mechanism. --cpus=1 is a quota of 100 milliseconds of run time per 100-millisecond period across all threads. During startup the JVM runs many threads at once, the JIT compiler threads, garbage-collector threads and class loading, so the quota is spent in the first 20 milliseconds of each period and every thread waits 80. Startup work that takes 8 seconds of CPU on an unthrottled laptop is stretched to 40 seconds of wall time. In steady state the same happens in bursts: a request that needs 15 milliseconds of CPU spanning a period boundary waits for the next period, and the dashboard averages usage over a minute, so it reports 30 percent while the p99 sees the 80-millisecond stalls.
  3. Ranked causes: quota too small for a multi-threaded runtime; JIT and GC thread counts sized for the host's core count because ActiveProcessorCount is not honoured; and, less often, DNS timeouts or entropy starvation at startup, ruled out because those do not affect steady-state p99.
  4. Fix: raise the limit to at least 2 CPUs, or remove the CPU limit and keep only a request, which is the common Kubernetes practice for latency-sensitive JVMs; set -XX:ActiveProcessorCount=2 and -XX:CICompilerCount=2 so thread counts match; use AppCDS to cut startup CPU; and for a fractional limit, size -XX:ParallelGCThreads explicitly.
  5. Prevention: graph throttled_usec per container next to utilisation, and treat any sustained throttling as a capacity bug.

Land it A CPU quota is not a slower processor, it is a fast processor that stops for the rest of each 100-millisecond period, and average utilisation cannot see those stops.

Likely follow-ups
"You raised the limit to 2 CPUs and p99 is still bad. What next?"

First I would re-read cpu.stat to confirm throttling actually dropped; if nr_throttled is still climbing, a burst of more than 2 cores' worth of threads is still hitting the quota, and the fix is either a higher limit or fewer concurrent threads.

If throttling is gone and latency is not, the JVM itself is next: I would check GC pause logs with -Xlog:gc, because a heap that is too small produces frequent collections that look like throttling in a latency graph.

Then jcmd 1 Thread.print at a slow moment to see whether request threads are blocked on a pool or lock. Finally, CPU steal from the hypervisor, visible as st in top on the host, which no container flag can fix.

"Why does removing the CPU limit help, and what is the risk?"

With no limit the container can use any idle core, so a burst of JIT or GC work finishes in milliseconds instead of waiting for the next quota period.

The CPU request, or --cpu-shares on Docker, still guarantees a share when the node is saturated, because shares are a weight the scheduler applies only under contention.

The risk is a noisy neighbour: one service in a tight loop can take every idle core and push others toward their guaranteed minimum, which is exactly what shares protect but which raises their latency.

For latency-sensitive JVMs I accept that trade and monitor per-node saturation, and I keep hard limits on batch jobs and anything untrusted.

"What does cpu.stat look like when it is healthy?"

nr_throttled divided by nr_periods is the fraction of 100-millisecond windows in which the container was stopped early, and healthy is under 1 percent; I start worrying above 5.

throttled_usec divided by nr_throttled tells me how long each stall lasted, and anything approaching the 100-millisecond period means threads regularly lose most of a window.

I also watch usage_usec against wall time to compute true utilisation at one-second resolution rather than the dashboard's one-minute average. cAdvisor exposes these as container_cpu_cfs_throttled_periods_total and container_cpu_cfs_periods_total, so the ratio is one PromQL expression.

"How much does AppCDS actually save at startup?"

Class Data Sharing stores the parsed and verified form of classes in an archive that the JVM maps at startup instead of loading and verifying each class from the jar.

For a Spring Boot service with a few thousand classes it typically cuts startup CPU by 30 to 50 percent, so 40 seconds under a tight quota might become 20.

As of Aug 2026 the practical route is the JDK 21 or later -XX:+AutoCreateSharedArchive -XX:SharedArchiveFile=/app/app.jsa pair, or Spring Boot's own training-run support that writes the archive during the image build.

It does not help steady-state latency at all, so it is a startup fix layered on top of the quota fix, not a replacement.

Q79 · Scenario. "A contractor with access to a shared Docker host reports they can read the production database password of another team's container. No one gave them credentials. How did they get it, and what is your fix?"

Reveal answer

The real test Whether you know the three places an environment variable becomes readable, and can name the file-based alternative.

Strong answer In diagnosis order:

  1. Reproduce it: docker inspect --format '{{.Config.Env}}' name prints every environment variable of every container to anyone who can talk to the Docker socket, and membership of the docker group is exactly that access. The password was passed with -e DB_PASSWORD=… or from an --env-file.
  2. List the other leak paths while you are there, ranked by how often they bite: docker inspect as above; /proc/<pid>/environ on the host for the container's processes, readable by root; child processes inheriting the whole environment, so a crash reporter or a shell-out to a CLI tool sees and may log it; and application frameworks that dump the environment into diagnostic endpoints such as Spring Boot's /actuator/env unless it is disabled or sanitised.
  3. Fix: rotate the password immediately. Then move the secret out of the environment and into a file mounted at run time with a restrictive mode: a tmpfs mount, --mount type=tmpfs,destination=/run/secrets, populated by an init step, or a Compose secrets: entry that appears at /run/secrets/db_password, or in Kubernetes a Secret volume. The application reads the file at startup, and Spring Boot does this with spring.config.import=configtree:/run/secrets/. Files do not appear in docker inspect and are not inherited by child processes.
  4. Reduce the blast radius of the socket itself: nobody outside the platform team should be in the docker group on a shared host, and rootless Docker or per-team hosts remove the shared-daemon problem. Add --read-only and --tmpfs /tmp to the standard run flags so a compromised container cannot persist tooling either.
  5. Prevention: a CI rule that fails any Compose file or run script containing a secret-looking value in environment:, and a periodic audit that greps docker inspect output across hosts for high-entropy strings.

Land it An environment variable is a public field of the container object, readable by every socket user and inherited by every child process — secrets belong in files with a mode of 0400.

Likely follow-ups
"The secret is now a file, but the contractor is still in the docker group. Is it fixed?"

No. Anyone who can talk to the daemon socket can run docker exec name cat /run/secrets/db_password, or start a new container with --volumes-from, or mount the host root and read anything.

Moving the secret to a file closes the casual leak through docker inspect and inheritance by child processes, but socket access is root on the host and reads every file.

The real fix is that contractors and most engineers are not in the docker group on a shared host. They get rootless Docker for their own work, or their own machine, and the production containers run on hosts nobody logs into.

The file move is worth doing anyway, because it also protects against the application's own diagnostics dumping the environment.

"How do you rotate the password without downtime?"

With two valid credentials at once. In Postgres I create a second role or a second password on the same role using the dual-password support that a managed service offers, or I create app_v2 with the same grants.

Then I update the secret file and roll the containers one at a time; each new instance reads the new file at startup, while the old instances keep working on the old credential. Once every instance is on the new value I revoke the old.

If the application reads the file on a timer or on SIGHUP instead of only at startup, I do not even need a restart. What I never do is change the password in the database first and then race to update the containers.

"What would you use in production instead of a mounted file from Compose?"

A secrets manager with workload identity. The container gets a short-lived identity from the platform, for example an IAM role on the node or a projected service account token in Kubernetes, and uses it to fetch the secret from Vault or AWS Secrets Manager at startup.

Either an init step writes the value to a tmpfs file that the app reads, or the app uses a client library that caches and refreshes it.

Nothing long-lived is stored on disk or in an environment variable, rotation is a change in one place, and every read is logged with the identity that made it.

Compose file secrets are the development stand-in that keeps the application code identical: it reads /run/secrets/db_password in both worlds.

"How would you find every other secret already leaking this way across the fleet?"

A script over every host that runs docker ps -q | xargs docker inspect --format '{{.Name}} {{.Config.Env}}' and pipes it through a high-entropy string detector, the same kind gitleaks or trufflehog use, plus a keyword match on PASSWORD, TOKEN, SECRET, and KEY.

I would also grep every Compose file and run script in source control for the same patterns under environment: and -e. The output becomes a ticket per service with a deadline, and the same detector becomes a CI check so the list stops growing.

I would treat every hit as compromised and rotate, because I cannot prove who has read docker inspect output in the past.

Q80 · Scenario. "A developer runs a build container with -v $PWD:/work and afterwards cannot delete the target directory it created — the files are owned by root. Explain the mechanism and the proper fix, including what -u and user namespaces change."

Reveal answer

Strong answer In diagnosis order:

  1. Confirm with ls -ln target on the host: the numeric owner is 0. The mechanism is that a bind mount shares the host's filesystem directly, and file ownership is stored as a numeric user ID that both sides interpret without translation. The container's process ran as UID 0 because the image never set a USER, so every file it created is owned by UID 0 on the host too, and the developer's UID 1000 cannot remove them without sudo.
  2. Rank the causes: the image runs as root by default, which is the case for nearly all official build images; the Dockerfile sets a USER but the developer overrode it; or the tool inside explicitly chowns output.
  3. Immediate fix: sudo chown -R $(id -u):$(id -g) target, or run the same image once with -u 0 to delete the directory from inside.
  4. Proper fix, in order of preference. First, run the container as the host user: docker run -u $(id -u):$(id -g) -v $PWD:/work image; the process then has no entry in the container's /etc/passwd, which some tools dislike, so a Maven or Node image may need HOME=/tmp set as well. Second, for shared tooling, build a dev image whose USER is a fixed UID matching the team's convention, commonly 1000. Third, enable user namespace remapping on the daemon, "userns-remap": "default", which maps root inside the container to an unprivileged range on the host such as 100000; that stops root-owned files appearing, but it also means the container's root can no longer read the developer's own files without matching ownership, so it suits security more than convenience. Rootless Docker achieves the same effect per user without daemon configuration.
  5. Prevention: every Dockerfile in the organisation ends with a non-root USER, and the shared Makefile passes -u $(id -u):$(id -g) to any bind-mounted build container by default.

Land it A bind mount does not translate user IDs, so whoever the process is inside the container is exactly who owns the files outside — decide that identity on purpose with USER or -u.

Likely follow-ups
"You pass -u $(id -u) and Maven now fails with 'Could not create local repository'. Why?"

Because the process is now uid 1000 but the image's home directory and Maven cache belong to root. Maven wants to write ~/.m2, and with no /etc/passwd entry for uid 1000 the home directory resolves to /, which is not writable.

The fixes are cheap: set -e HOME=/tmp or -e MAVEN_CONFIG=/tmp/.m2, or bind-mount the developer's own ~/.m2 into the container at /tmp/.m2 so the cache persists and is owned by them. The Maven official image reads MAVEN_CONFIG exactly for this case.

The same pattern applies to npm with npm_config_cache and Gradle with GRADLE_USER_HOME.

"Does this problem exist on Docker Desktop for Mac?"

Mostly not, and that is why developers on Macs are surprised by it on Linux.

On macOS the containers run in a Linux virtual machine, and the file-sharing layer maps every file the VM writes back to the macOS user who owns Docker Desktop, regardless of the uid inside the container.

So files created by container root show up owned by the developer. On native Linux there is no translation layer; the bind mount is the same filesystem, so uid 0 stays uid 0.

This is one of the reasons a Compose file that works on a Mac leaves root-owned build directories on a Linux CI runner, and why the -u flag belongs in the shared Makefile even though half the team never needs it.

"What does userns-remap change for a CI runner specifically?"

With "userns-remap": "default" the daemon maps container uid 0 to a host uid in the dockremap range from /etc/subuid, typically starting at 100000.

Files a root-in-container build writes to a bind mount then appear on the host owned by 100000, not by root, so the runner user cannot delete them either, unless the workspace is cleaned by the daemon or a container.

It also means the container cannot read files owned by the runner user unless they are world-readable. For CI the practical recipe is -u $(id -u):$(id -g) without remapping, or a runner that cleans the workspace with a container.

User namespaces are a security feature for shared hosts, not a convenience feature for bind mounts.

"How do you set this up so nobody has to remember the flag?"

Three layers. The Dockerfile for any internal build image ends with a fixed non-root user, USER 1000:1000, which matches the first user on most Linux machines.

The team's Makefile or task runner has one target that wraps docker run with -u $(id -u):$(id -g) -e HOME=/tmp, and every documented command uses it.

And the Compose file for local development sets user: "${UID:-1000}:${GID:-1000}" with those variables exported in the shell profile, since Compose does not expand $(id -u) itself. Rootless Docker on the developer's own machine makes the whole problem vanish, because container root is the developer's own uid.

09 · DrillNetworking, Storage, Compose & Security — Q81–Q115

This section is where Docker stops being "a way to run a JAR" and becomes a Linux system you are responsible for.

The questions cover the four things that actually page people: a container that cannot reach another container, data that disappeared or belongs to the wrong user, a Compose file that starts things in the wrong order, and a container that turned out to be root on the host.

Every scenario answer goes in diagnosis order — symptom, the exact commands that produce evidence, causes ranked by likelihood, the fix, and the prevention — because that is the order an interviewer wants to hear it in. Say the answer out loud before you reveal it.

Drill · Networking

These questions test whether you can explain what Docker actually does with Linux network namespaces, bridges, and NAT rules — and whether you can find, in under five minutes, why one container cannot talk to another.

Q81. "What is the difference between the default bridge network and a user-defined bridge network? Why does the documentation tell you never to use the default one?"

Reveal answer

The real test Whether you know the difference is DNS, not plumbing — both are ordinary Linux bridges.

Strong answer A bridge network is a virtual Ethernet switch that lives inside the host kernel. Every container on it gets a virtual cable, called a veth pair, with one end inside the container's network namespace and the other end plugged into the bridge.

The default bridge is the one called docker0, usually on 172.17.0.0/16, and every container you start without --network lands on it. A user-defined bridge is created with docker network create mynet and gets its own subnet, typically 172.18.0.0/16 and upward. Plumbing-wise they are identical.

The practical difference is name resolution.

On a user-defined network Docker runs an embedded DNS server at 127.0.0.11 inside each container, and it answers container names and network aliases with the right IP. On the default bridge there is no such resolver; containers can only reach each other by IP address or through the deprecated --link flag, which rewrites /etc/hosts.

User-defined networks also give isolation, because containers on different user-defined networks cannot see each other at all, while everything on docker0 can reach everything else on docker0.

You can also connect and disconnect a running container from a user-defined network with docker network connect, which does not work on the default bridge. Compose creates a user-defined network per project for exactly these reasons.

Land it The default bridge is a compatibility artifact from 2014 — the moment you need one container to find another by name, you are on a user-defined network or you are debugging for an hour.

Likely follow-ups
"How does the embedded DNS at 127.0.0.11 actually answer, and what happens for names it does not know?"

The daemon runs a small resolver and rewrites the container's /etc/resolv.conf to point at 127.0.0.11, which is a loopback address inside the container's namespace that the daemon intercepts with an iptables rule to a random high port.

For a container name, service name, or network alias on a shared network it returns the container's IP from its own table, so there is no external lookup.

For anything else it forwards to the host's configured resolvers, the real ones from the host's /etc/resolv.conf or systemd-resolved's upstreams. That forwarding is why a user-defined network fixes the five-second DNS delay from a stripped loopback resolver. Verify with docker exec app cat /etc/resolv.conf and getent hosts db.

"Can a container on one user-defined network reach another network's container by IP?"

No, and that isolation is the second reason to use them. Each user-defined bridge is a separate Linux bridge with its own subnet, and Docker installs DOCKER-ISOLATION iptables rules that drop packets forwarded between bridges.

So even if the web container guesses that the database is 172.19.0.2, the packet is dropped. The exceptions are a container connected to both networks, which routes between them like any dual-homed host, and --network host containers, which sit outside the scheme entirely.

On the default docker0 bridge there is no such isolation: every container can reach every other. Verify with iptables -L DOCKER-ISOLATION-STAGE-2 -n on the host.

"When would you still use --link or the default bridge?"

Only to keep a legacy script alive for a day. --link is deprecated, works only on the default bridge, and injects the target's environment variables into the source container, which leaks secrets in the same way as environment variables always do.

The default bridge remains for a one-off docker run where the container talks only to the outside world and nothing needs to find it by name, such as running a CLI tool.

For anything with two containers I create a network, because docker network create costs nothing and Compose does it automatically. If I inherit a script that relies on --link, converting it is a five-minute change I would make before touching anything else.

"What are the tuning knobs on a user-defined bridge that matter in production?"

Subnet and gateway with --subnet 10.10.0.0/24 --gateway 10.10.0.1, to avoid colliding with corporate ranges; Docker's default pool is configurable in daemon.json under default-address-pools, which matters when a VPN uses 172.17 or 172.18.

The MTU with -o com.docker.network.driver.mtu=1450 when the host sits on a VXLAN or VPN. --internal to cut off external access for data networks. And -o com.docker.network.bridge.enable_icc=false to stop containers on the same network from talking to each other, which turns the network into hub-and-spoke.

Finally --ipv6 with a subnet if the service must be reachable over IPv6, because Docker networks are IPv4-only by default.

Q82 · Scenario. "A Spring Boot container logs Connection refused: localhost:5432 on startup. The Postgres container is running and psql from the host connects fine. What do you check, in order?"

Reveal answer

The real test Whether you understand that localhost inside a container is the container's own loopback, not the host's.

Strong answer I would go through this in order:

  1. Symptom: connection refused means a packet reached an IP address and that address answered "nothing is listening on that port". This is different from a timeout, where nothing answered at all. So the app reached something and that something was not Postgres.
  2. Evidence: docker inspect app --format '{{.HostConfig.NetworkMode}}' shows which network the app is on, and docker network inspect <net> lists the containers attached and their IPs. docker exec app sh -c 'getent hosts db' tells me whether the name resolves. docker exec app sh -c 'cat /proc/net/tcp' or a quick nc -zv db 5432 proves reachability without relying on the app.
  3. Most likely cause: the JDBC URL says localhost:5432. Inside the app container, localhost is the app's own network namespace, and nothing there listens on 5432. The host's psql works because the host published the port with -p 5432:5432. The fix is to use the service name: jdbc:postgresql://db:5432/app, with both containers on the same user-defined network.
  4. Second cause: the containers are on different networks, so the name does not resolve or the IP is unreachable. Attach both to one network, or in Compose just put them in the same project.
  5. Third cause: Postgres is still initialising and has not opened the socket yet. That shows up as refused for a few seconds and then works. A healthcheck plus depends_on: condition: service_healthy removes it.
  6. Prevention: never hard-code localhost for a dependency in a container image. Read the host from an environment variable such as SPRING_DATASOURCE_URL, so the same image works on a laptop, in Compose, and in Kubernetes.

Land it Ninety percent of "cannot reach the database" tickets are the word localhost in a config file — say that first, then prove it with getent hosts.

Likely follow-ups
"You changed the URL to db:5432 and it still says connection refused. What next?"

Now the name resolved, so the packet reached the database container's IP and nothing was listening on 5432 there at that moment.

The most common reason is timing: Postgres on first boot runs initdb, starts once for setup scripts, stops, and starts again, so there is a window of refused connections after the container is already running. docker compose logs db shows two "ready to accept connections" lines.

The fix is a healthcheck with pg_isready and condition: service_healthy, plus a Hikari initialisation timeout so the app retries.

Less commonly, Postgres is configured to listen on a non-default port through PGPORT, or listen_addresses was set to localhost in a custom postgresql.conf, which I would check with docker exec db ss -ltn.

"What if the app must talk to a Postgres that runs on the host, not in a container?"

Then the app needs the host's address, and inside a container that is not localhost. On Docker Desktop the name host.docker.internal resolves to the host.

On Linux I add --add-host=host.docker.internal:host-gateway, or in Compose extra_hosts: ["host.docker.internal:host-gateway"], which maps the name to the bridge gateway address, typically 172.17.0.1.

The host's Postgres must then listen on that interface, so listen_addresses = '*' or the bridge IP, and pg_hba.conf needs a line allowing the container subnet.

The alternative is --network host, which makes localhost mean the host again, at the cost of every isolation property.

"How would you confirm the fix in a pipeline so it never regresses?"

An integration test that starts the stack with docker compose up --wait and fails if the wait times out, because --wait blocks until every healthcheck passes and returns non-zero otherwise.

The API's own readiness endpoint includes a database ping, so if the URL were wrong the API would never become healthy and the pipeline would stop.

I would also assert in a test that the effective datasource URL contains no localhost, which is a one-line check against the Spring environment. In Kubernetes the same readiness probe stops a misconfigured pod from receiving traffic, so the check I write once protects three environments.

"Why not just use network_mode: host for the app and be done with it?"

Because it trades a one-word config fix for a permanent loss of isolation.

With host networking the app shares the host's port space, so two projects or two replicas collide on 8080, and every port the app opens is exposed on every host interface with no firewall in between.

It does not work on Docker Desktop in the way people expect, since "host" there is the virtual machine. It also hides the bug: the moment the same image goes to Kubernetes, where pods have their own namespace, localhost breaks again.

The environment variable fix costs one line and makes the image correct everywhere.

Q83. "Explain what -p 8080:80 actually does at the kernel level. Why do published ports ignore ufw on Linux, and what does -p 127.0.0.1:8080:80 change?"

Reveal answer

The real test Whether you know a published port is a NAT rule in the FORWARD path, which is exactly where host firewalls do not look.

Strong answer When you publish a port, Docker writes packet-rewriting rules into the kernel firewall, iptables or its successor nftables.

The rule is a DNAT, which stands for destination network address translation: any packet arriving at the host on port 8080 has its destination rewritten to the container's IP on port 80, and the reply is rewritten back on the way out.

Docker also starts a small userland process, docker-proxy, to cover the cases the kernel rules miss, such as traffic from the host's own loopback address.

The rules live in Docker's own chains, DOCKER in the nat table and DOCKER plus DOCKER-USER in the filter table's FORWARD chain. Now the ufw problem.

ufw is a friendly front end that writes its rules into the INPUT chain, which only sees packets addressed to the host itself.

A published port's packets are forwarded to the container, so they travel through the FORWARD chain, where Docker's rules say "accept", and ufw never sees them. The result is that ufw deny 8080 does nothing and your database is on the internet.

The fixes are to put deny rules in DOCKER-USER, which Docker evaluates first and never touches, or to bind to loopback. -p 127.0.0.1:8080:80 makes the DNAT rule match only packets whose destination is 127.0.0.1, so only processes on the host can connect.

You can make that the default for every container with "ip": "127.0.0.1" in /etc/docker/daemon.json. Remember that Docker also publishes on IPv6 by default when it is enabled, so a rule that only covers IPv4 is half a rule.

Land it A published port is a firewall rule Docker writes on your behalf, and it lands in a chain your host firewall does not inspect — so bind to 127.0.0.1 unless you truly want the world in.

Likely follow-ups
"Show me the exact DOCKER-USER rule that blocks a port from the internet but not from the office."

The chain sits at the top of FORWARD and Docker never rewrites it, so rules there survive daemon restarts.

To allow 10.20.0.0/16 and drop everyone else for published ports on the external interface: iptables -I DOCKER-USER -i eth0 -s 10.20.0.0/16 -j RETURN followed by iptables -I DOCKER-USER 2 -i eth0 -m conntrack --ctstate NEW -j DROP.

RETURN hands matching packets back to Docker's own chains, DROP kills the rest. Order matters, so I insert the allow first.

I persist the rules with the distribution's iptables-persistent or a systemd unit, and I must add the equivalent ip6tables rules when IPv6 is enabled, or the block is only half a block.

"What is docker-proxy for, and can you turn it off?"

It is a small userland process per published port that listens on the host port and copies bytes to the container.

It exists for the cases the DNAT rule does not cover: connections from the host itself to 127.0.0.1 on that port, because locally generated packets do not traverse the PREROUTING chain where DNAT lives, and hosts where route_localnet is off.

You can disable it with "userland-proxy": false in daemon.json, which saves a process and a copy per port and is common on high-throughput hosts; Docker then adds extra rules to handle loopback.

The cost is that some edge cases, such as a container connecting to its own published port through the host address, behave differently, so I test before flipping it fleet-wide.

"How does this change with nftables and with Docker 28 and later?"

Modern distributions run nftables, and as of Aug 2026 Docker still writes its rules through the iptables-nft compatibility layer by default, so the chain names and the FORWARD-path behaviour are unchanged; a native nftables backend exists in newer engines as an opt-in.

Docker 28 tightened one thing that matters here: published ports on a bridge network are no longer reachable from other hosts on the LAN unless they are routed through the host's IP, closing an old hole where a neighbour could hit a container's bridge IP directly.

The DOCKER-USER chain remains the documented place for your own rules in every version, and the loopback-binding advice is unchanged.

"How would you audit a fleet for ports accidentally open to the world?"

From inside: docker ps --format '{{.Names}} {{.Ports}}' on every host, flagging any entry bound to 0.0.0.0 or :::, and iptables -t nat -S DOCKER to catch rules for containers that docker ps no longer shows. From outside, which is the one that counts: a scheduled nmap or cloud-provider port scan of every public IP compared against an allow-list of 443 and the SSH bastion. Then I fix the defaults so the audit stays clean: "ip": "127.0.0.1" in daemon.json, cloud security groups that only open 443 to the load balancer, and a Compose lint that rejects ports: entries without a 127.0.0.1 prefix except on the proxy.

Q84 · Scenario. "A service published with -p 8080:8080 answers curl localhost:8080 on the host, but from any other machine the connection times out. Diagnose it."

Reveal answer

Strong answer Diagnosis order:

  1. Symptom: works on loopback, times out remotely. A timeout means packets are being dropped somewhere, not rejected. That points at a firewall, a binding, or routing, not at the application.
  2. Evidence: docker port <container> shows exactly what was bound. If it prints 127.0.0.1:8080, the port was published on loopback only, either by an explicit -p 127.0.0.1:8080:8080 or by "ip": "127.0.0.1" in daemon.json. That is the first and most common cause, and the fix is -p 0.0.0.0:8080:8080 if you genuinely want external access.
  3. If it shows 0.0.0.0:8080, check the cloud layer next: an AWS security group, an Azure NSG, or a GCP firewall rule that allows 22 and 443 but not 8080. sudo ss -ltnp | grep 8080 confirms the host is listening; if the cloud drops the packet before it arrives, nothing on the host will ever log it.
  4. Then check the host firewall's forward path. Run sudo iptables -L DOCKER-USER -n -v; a DROP rule someone added to close the ufw hole would produce exactly this symptom. sudo iptables -t nat -L DOCKER -n should show the DNAT rule for 8080.
  5. Rarer: the host has two interfaces and the reply leaves on the wrong one, or net.ipv4.ip_forward was set to 0 by a hardening script after Docker started. sysctl net.ipv4.ip_forward should be 1.
  6. Prevention: decide per port whether it should be public. Put the reverse proxy on 0.0.0.0:443 and everything else on 127.0.0.1, and manage cloud firewall rules in code alongside the deployment.

Land it "Works on localhost, dead remotely" is a binding or a firewall in that order — docker port answers the first in one line, and the cloud console answers the second.

Likely follow-ups
"docker port says 0.0.0.0:8080 and the security group allows it. Still timing out. What next?"

Then I prove where the packet dies.

On the host, sudo tcpdump -ni eth0 port 8080 while the remote machine connects: no packets means the cloud or an upstream firewall dropped them before arrival, and I go back to the network ACL, a second security group on the interface, or a load balancer that was supposed to forward.

SYN packets arriving with no reply means the host received them and dropped them, so I check iptables -L DOCKER-USER -n -v for counters incrementing, sysctl net.ipv4.ip_forward, and whether the packets are hitting a different interface than the one the route replies on.

SYN plus reply means the host works and the problem is the return path, usually asymmetric routing on a multi-homed VM.

"Could a remote client see a different behaviour than timeout, and what would each mean?"

Yes, and the difference is diagnostic. A timeout means silent drop, which is a firewall or route.

"Connection refused" from remote means the packet reached the host and was rejected, so the port is not published on that address or the DNAT rule is missing, and I would suspect a daemon restart that lost its rules after someone ran iptables -F.

"No route to host" means an ICMP reject came back, usually from a firewall configured with REJECT rather than DROP, which is actually friendlier. A connection that opens but hangs points at MTU or the application.

I always ask the reporter for the exact error text before I start.

"How would you prevent someone from accidentally exposing the next port publicly?"

Make private the default and public an explicit act. "ip": "127.0.0.1" in daemon.json means -p 8080:8080 binds loopback unless someone writes -p 0.0.0.0:8080:8080.

The cloud security group only opens 443 to the load balancer and 22 to the bastion, managed in Terraform so a change is a reviewed diff. A Compose lint in CI rejects any ports: line without the 127.0.0.1 prefix outside the proxy service.

And an external scan runs nightly against every public IP and pages on any new open port. With those four, "accidentally public" requires three deliberate mistakes in three different places.

"What if ip_forward is 0 and Docker is running — how did that happen and what breaks?"

Docker sets net.ipv4.ip_forward=1 at daemon start because forwarding is what carries packets from the host interface to the bridge.

A hardening script or a config-management run applying a CIS benchmark commonly sets it back to 0 afterwards, and from that moment every published port stops working for remote clients while loopback keeps working through docker-proxy.

Outbound traffic from containers also fails because the reply cannot be forwarded back. I would confirm with sysctl net.ipv4.ip_forward, restore it, and then fix the sysctl file so the benchmark exception is recorded.

The lesson is that the host hardening baseline and the Docker requirements must be reconciled in one place.

Q85 · Scenario. "A Node service inside a container listens on port 3000, docker ps shows 0.0.0.0:3000->3000/tcp, but curl localhost:3000 on the host returns 'connection reset' or 'empty reply'. docker exec into the container and curling works. Why?"

Reveal answer

The real test Whether you know a process must bind 0.0.0.0 to be reachable through the container's veth interface.

Strong answer In order:

  1. Symptom: the port is published, the process is alive, and it answers on its own loopback but not from outside. That combination almost always means the process bound to 127.0.0.1 inside the container.
  2. Evidence: docker exec app sh -c 'cat /proc/net/tcp' and look at the local address column; 0100007F:0BB8 is 127.0.0.1 port 3000 in hex, while 00000000:0BB8 is 0.0.0.0. If the image has ss, ss -ltn is friendlier. Compare it with docker inspect app --format '{{.NetworkSettings.IPAddress}}', which is the address the DNAT rule delivers to.
  3. Cause: the DNAT rule rewrites the packet's destination to the container's bridge IP, say 172.18.0.5:3000. A socket bound to 127.0.0.1 only accepts packets addressed to 127.0.0.1, so the kernel inside the container namespace sends back a reset. Many frameworks default to loopback — Express when you pass 'localhost', Flask, Rails in older versions, and Spring Boot only if server.address was set.
  4. Fix: bind to 0.0.0.0, or to :: for dual stack. In Node that is app.listen(3000, '0.0.0.0'); in Spring Boot leave server.address unset.
  5. Prevention: a healthcheck that connects through the published port from the host, rather than from inside the container, would have caught this on the first run. Add a note to the team's Dockerfile template that "bind to all interfaces inside a container" is the rule, since the container namespace is the isolation boundary anyway.

Going deeper Two subtleties are worth having ready.

First, the IPv6 variant: a process bound to ::1 or only to :: with IPV6_V6ONLY set will refuse IPv4-mapped connections from the DNAT rule, so "bound to all interfaces" must mean 0.0.0.0 for IPv4 or a dual-stack :: socket; ss -ltn shows *:3000 for a dual-stack bind and [::1]:3000 for the broken case.

Second, the empty-reply variant: if the port was published but the process listens on a different port, say 3001, the DNAT delivers to 3000 and the kernel answers with a reset, which curl reports as "connection reset by peer"; if a proxy such as nginx inside the container accepts and immediately closes, curl reports "empty reply from server".

The distinction tells you whether the socket exists at all.

The fastest single check from the host with no tools in the image is sudo nsenter -t $(docker inspect -f '{{.State.Pid}}' app) -n ss -ltnp, which lists listening sockets inside the container's namespace using the host's binary.

Land it Loopback binding is a security habit from bare-metal days that becomes a bug inside a container — the network namespace already does the isolating, so bind to 0.0.0.0 and publish on 127.0.0.1 if you need the host-only behaviour.

Likely follow-ups
"Isn't binding 0.0.0.0 inside the container a security risk?"

Not in the way it is on a bare host. The container's 0.0.0.0 means every interface in the container's network namespace, which is just its loopback and its one veth interface on the bridge.

Nothing outside the host can reach that interface unless a port is published, and nothing on other user-defined networks can reach it because of the isolation rules.

So the exposure decision moves from the application's bind address to the -p flag, where it belongs: publish on 127.0.0.1 for host-only, on 0.0.0.0 for public.

The one caveat is containers on the same network, which can reach the port directly, and that is what network segmentation with per-relationship networks is for.

"The framework has no bind option. What are your choices?"

Rare, but it happens with vendor binaries. Option one: run a tiny reverse proxy in the same container or a sidecar sharing its network namespace, --network container:app, that listens on 0.0.0.0 and forwards to 127.0.0.1:3000; socat does this in one line, socat TCP-LISTEN:3001,fork,reuseaddr TCP:127.0.0.1:3000.

Option two: --network host, which makes the process's loopback the host's loopback, so the host can reach it, at the cost of isolation. Option three: check whether the tool reads an environment variable such as HOST or BIND_ADDRESS, which many do without documenting it.

I would pick the sidecar for anything long-lived and note the vendor request.

"How would you catch this class of bug before it reaches a shared environment?"

With a healthcheck that connects from outside the container rather than inside.

A HEALTHCHECK in the image runs inside the namespace and passes even when the bind is wrong, so I also add a pipeline smoke test: docker run -d -p 127.0.0.1:3000:3000 image then curl --fail http://127.0.0.1:3000/health from the runner, which traverses the DNAT path.

That test takes two seconds and fails on exactly this bug. In Compose, up --wait plus a test container on a separate network that calls the service by name is the equivalent.

And the Dockerfile template's comment says "bind all interfaces; publish on loopback if you want host-only".

"Express with 'localhost' works on a colleague's machine. Why the difference?"

Almost certainly the colleague runs it without Docker, or on Docker Desktop where the port-forwarding path is different.

On Docker Desktop for Mac and Windows the published port is handled by a proxy inside the virtual machine that connects to the container over the bridge, so the same 127.0.0.1 bind fails there too; but if the colleague uses --network host on Linux, the process's localhost is the host's localhost and it works by accident.

Another possibility is that localhost resolved to ::1 on one machine and the framework opened a dual-stack socket there, while it resolved to 127.0.0.1 on the other.

Either way the fix is the same: bind explicitly to 0.0.0.0 and stop depending on name resolution for the bind address.

Q86. "Compare host, none, overlay, and macvlan networking. When would you pick each over the bridge?"

Reveal answer

The real test Whether you can say what each driver gives up — isolation, portability, or host access — rather than just listing names.

Strong answer Host networking, chosen with --network host, skips creating a network namespace, so the container shares the host's interfaces, IPs, and port space.

There is no NAT and no veth, so it is the fastest option and the only one where a process can see the host's real interfaces, which matters for monitoring agents, packet capture, and some high-throughput proxies.

The cost is that port conflicts are back and there is no network isolation at all. It is Linux-only in the true sense; Docker Desktop emulates it inside its virtual machine. None, with --network none, gives the container only a loopback interface.

I use it for batch jobs that must not talk to anything, and for build or test steps where any outbound call is a bug.

Overlay networks, created with docker network create -d overlay, span multiple hosts by wrapping container traffic in VXLAN, a tunnelling protocol that carries Ethernet frames inside UDP packets on port 4789.

They only work with Swarm mode enabled, and in 2026 that means they are mostly historical; Kubernetes uses its own CNI plugins for the same job, covered in E10.

Macvlan and ipvlan give the container its own address on the physical LAN, so it looks like a separate machine to the switch.

Macvlan assigns a distinct MAC address per container; ipvlan shares the host's MAC and differs only by IP, which is what you need when the switch or the cloud provider refuses unknown MACs.

They suit appliances that must be discoverable by broadcast, such as a DHCP server or a legacy system that identifies clients by IP. The trade-off is that the host itself often cannot talk to its macvlan containers, and cloud networks usually block it.

Land it Bridge is the default because it is the only one that gives both isolation and portability — every other driver buys one specific thing by giving one of those up.

Likely follow-ups
"How much faster is host networking really, and when does it matter?"

The bridge path costs a veth hop, a bridge forward, and a NAT rewrite with a conntrack entry per connection.

For an ordinary HTTP service doing a few thousand requests per second the overhead is under a few percent of CPU and tens of microseconds of latency, which nobody notices.

It matters at the edges: a gateway handling tens of thousands of new connections per second, where conntrack becomes the bottleneck; UDP-heavy workloads such as DNS or video where per-packet cost dominates; and anything that needs to see the real interface, such as a packet-capture agent.

I would measure with wrk against both modes before choosing host mode, because the isolation I give up is permanent and the performance gain is often imaginary.

"Why can't the host talk to its own macvlan containers, and how do you work around it?"

Macvlan creates sub-interfaces on the physical NIC, and the kernel deliberately does not loop traffic between the parent interface and its macvlan children; frames from the host go out to the switch, and the switch does not send them back on the same port.

So ping from the host to a macvlan container fails while every other machine on the LAN succeeds.

The workaround is to give the host its own macvlan sub-interface: ip link add mv0 link eth0 type macvlan mode bridge, assign it an address in the same subnet, and add a route to the container range via mv0.

Then host and containers are siblings on the same virtual bridge. In cloud environments the provider usually blocks unknown MACs anyway, so ipvlan in L2 mode is the alternative there.

"Does 'none' really prevent all network access?"

It gives the container only a loopback interface, so it cannot send a packet anywhere, and that holds regardless of what the process tries, because there is no route out.

What it does not prevent is other channels: a bind-mounted Unix socket such as the Docker socket, a shared volume another container writes to, or shared IPC if you passed --ipc. So "no network" is exactly that and nothing more.

I use it for build and test steps that must prove they have no hidden downloads, with a build failing if a step tries to fetch anything, and for batch jobs that read from a mounted input and write to a mounted output.

You can still docker cp and docker exec into it, since those go through the daemon, not the network.

"In a greenfield design in 2026, would you ever choose overlay?"

Only inside Swarm, because that is the only place Docker's overlay driver runs, and I would only choose Swarm for a small fleet that will stay small. If the requirement is multi-host container networking, the real answer is Kubernetes with a CNI plugin such as Cilium or Calico, which give the same VXLAN or native routing plus network policy, observability, and encryption, and which the rest of the ecosystem assumes. For a handful of hosts without an orchestrator, I would rather run a WireGuard mesh between hosts and let bridge networks route across it, which is simpler to debug than an overlay whose control plane I do not otherwise need.

Q87 · Scenario. "Every outbound HTTP call from a container takes exactly five seconds longer than it should, then succeeds. The same call from the host is instant. What is going on?"

Reveal answer

The real test Whether the number five triggers "DNS timeout" for you immediately — it is the resolver's default per-server timeout.

Strong answer Diagnosis order:

  1. Symptom: a fixed five-second delay before success. That is the default timeout:5 in glibc's resolver: it asks the first nameserver, waits five seconds, then tries the next one. So the first DNS server in the container's list is unreachable and the second one works.
  2. Evidence: docker exec app cat /etc/resolv.conf. On a user-defined network it should show nameserver 127.0.0.11. On the default bridge Docker copies the host's /etc/resolv.conf into the container, minus any loopback entries. If the host runs systemd-resolved, its file says nameserver 127.0.0.53, which Docker strips as unusable, and it falls back to 8.8.8.8 and 8.8.4.4. If a corporate firewall blocks 8.8.8.8, you get exactly this five-second pause. Confirm with docker exec app sh -c 'time getent hosts api.example.com'.
  3. Other causes, less likely: a VPN on the laptop that changed the host resolver after the container started; IPv6 lookups timing out because AAAA queries are dropped while A queries work, which shows as a delay only for dual-stack hostnames; and a search domain list that turns every lookup into several queries.
  4. Fix: set "dns": ["10.0.0.2"] in /etc/docker/daemon.json with your real resolver, or pass --dns per container. Move the workload to a user-defined network so the embedded DNS forwards to the host's actual configured resolvers. For the IPv6 case, options single-request in resolv.conf or disabling IPv6 on the network helps.
  5. Prevention: bake the resolver into daemon configuration on every host by the same config-management tool that installs Docker, and add a startup check that resolves one known name in under 200 ms.

Land it A delay that is exactly five seconds is never the application — it is a resolver waiting on a nameserver it cannot reach, and the fix lives in daemon.json, not in the code.

Likely follow-ups
"You set the daemon dns option and it is still five seconds. What next?"

First I confirm the setting took: docker exec app cat /etc/resolv.conf must show my resolver, and it will not for containers created before the daemon restart.

If it does show the right server and the delay persists, I time the two record types separately: dig A api.example.com @10.0.0.2 and dig AAAA api.example.com @10.0.0.2.

A fast A and a five-second AAAA means the resolver or a firewall drops IPv6 queries, and glibc waits for both before returning. The fix there is options single-request-reopen, disabling IPv6 in the container with --sysctl net.ipv6.conf.all.disable_ipv6=1, or fixing the resolver.

If both records are fast from dig but the application is still slow, the delay is not DNS and I move to strace -f -e connect on the process.

"Why does the delay not appear on the host?"

Because the host is using a different resolver.

With systemd-resolved, the host's /etc/resolv.conf points at the stub listener on 127.0.0.53, which forwards to the real corporate servers that resolved learned from DHCP or the VPN. Docker copies the host's file into containers on the default bridge but strips loopback addresses since they would point at the container's own loopback, and having nothing left, it substitutes Google's public resolvers.

Those are blocked by the corporate firewall, so the first query times out. The host never touches 8.8.8.8 at all. Checking resolvectl status on the host and cat /etc/resolv.conf in the container side by side makes the divergence obvious in one screen.

"How would you make the check automatic so the next host is never misconfigured?"

Two checks. At provisioning time, the config-management role that installs Docker also writes daemon.json with the dns and dns-search keys from the same variable that configures the host resolver, so they cannot drift.

At run time, a canary container on every host runs on a schedule and does time getent hosts registry.internal, exporting the duration as a metric; anything over 200 milliseconds pages.

The canary also checks that /etc/resolv.conf contains no 8.8.8.8, which is the specific signature of this fault. Both checks together take an hour to build and remove a class of tickets that otherwise reappears every time a laptop joins a new VPN.

"What does ndots and the search list have to do with it?"

The search list is a set of domains the resolver appends to short names, and ndots is how many dots a name needs before it is tried as-is first.

With a search list of three domains and the default ndots:1, the name api becomes four queries in sequence, and api.example.com is tried as-is first because it already has dots.

Kubernetes famously sets ndots:5, so even api.example.com is tried against every search domain before the real lookup, multiplying the cost of any slow resolver by five.

Inside Docker the search list is copied from the host, so a laptop with a long corporate list inherits the cost. Using fully qualified names with a trailing dot, or lowering ndots, cuts the queries to one.

Q88. "How do you tell 'connection refused', 'connection timed out', and 'connects but hangs mid-transfer' apart, and what tool do you use when the container image has no shell and no curl?"

Reveal answer

Strong answer The three symptoms map to three layers. Connection refused is a TCP reset: a packet reached the destination IP and the kernel there said nothing is listening. So routing works; check the port, the bind address, and whether the process is up.

Timed out means no reply at all, which points at a firewall dropping packets, a wrong IP, a missing route, or a security group. Connects but hangs on large responses while small ones work is the classic sign of an MTU problem.

The MTU is the biggest packet a link will carry; if the container's interface says 1500 but a VPN or VXLAN tunnel in the path only carries 1450, big packets are silently dropped and the handshake, which is tiny, succeeds anyway.

You check it with ip link inside the container and fix it with "mtu": 1450 in daemon.json or the com.docker.network.driver.mtu option on the network. For the tooling question: when the image is distroless and has nothing to run, I do not modify the image.

I either start a throwaway container that shares the target's network namespace, docker run --rm -it --network container:app nicolaka/netshoot, which gives me ss, tcpdump, dig, and curl looking at exactly the same interfaces and routes as the app, or I use nsenter from the host.

nsenter is a utility that runs a command inside another process's namespaces: sudo nsenter -t $(docker inspect -f '{{.State.Pid}}' app) -n ss -ltnp runs the host's ss inside the app's network namespace.

The -n flag picks only the network namespace, so the host's binaries and files are still visible. Both approaches leave the production image untouched.

Land it Refused is the port, timeout is the path, hangs-on-big is the MTU — and --network container: or nsenter lets you prove which one without shipping a shell in production.

Likely follow-ups
"How do you confirm an MTU problem rather than guess it?"

With a ping that forbids fragmentation. From inside the container's namespace, ping -M do -s 1472 target sends a 1500-byte packet with the do-not-fragment bit set; if it fails with "message too long" or silently drops while -s 1400 succeeds, the path cannot carry 1500.

I narrow down the largest size that works, add 28 bytes of headers, and that is the path MTU. The reason the handshake works is that SYN packets are tiny; the hang appears on the first full-sized data segment.

tracepath reports the path MTU directly if ICMP is not blocked. Then I set the network's MTU 50 bytes below the path value for VXLAN, or 80 below for a WireGuard tunnel.

"The distroless container has no shell and you have no root on the host. What can you still do?"

The --network container:app trick needs only Docker socket access, not host root, so a debug container with netshoot still works and sees the same interfaces and sockets. docker logs, docker inspect, and docker cp also go through the daemon.

In Kubernetes the same thing is kubectl debug -it pod --image=nicolaka/netshoot --target=app, which starts an ephemeral container sharing the pod's namespaces.

If the security policy forbids even that, then the image itself must expose enough: a health endpoint that reports dependency reachability, and structured logs that record connection errors with the resolved IP and errno.

I would rather have the platform allow a pinned debug image than have every production image carry a shell.

"What about 'connects, sends the request, and the response is slow' — which layer is that?"

That is the application or the thing behind it, not the network, and I split it with timestamps. curl -w '%{time_connect} %{time_starttransfer} %{time_total}' shows connection time, time to first byte, and total.

A fast connect and slow first byte means the server took long to produce the response: database, lock, GC pause, or an upstream call. A fast first byte and slow total means bandwidth or large payload.

A slow connect on a warm path means DNS or a SYN retry, which I would then chase with the resolver checks.

Inside a container I add one more suspect, CPU throttling, and read cpu.stat, because a service stalled by its quota looks exactly like a slow upstream from the client's side.

"When would you reach for tcpdump instead of the simpler tools?"

When the symptoms disagree with each other, or when I need proof of which side stopped talking. Refused versus timeout I can settle with nc -zv in seconds.

But a connection that sometimes hangs, a TLS handshake that fails with an unhelpful error, or a suspicion that a middlebox is resetting connections needs the packets.

docker run --rm --network container:app nicolaka/netshoot tcpdump -ni eth0 -w /tmp/cap.pcap port 5432 captures from inside the namespace, and I open the file in Wireshark to see retransmissions, resets, and MTU-sized packets never acknowledged.

I limit the capture with a port filter and a packet count, since a busy service writes gigabytes in minutes.

Q89 · Scenario. "A gateway container starts dropping new connections at roughly 65,000 concurrent, CPU is idle, and dmesg on the host says nf_conntrack: table full, dropping packet. Walk me through it."

Reveal answer

The real test Whether you know that NAT costs a kernel table entry per connection and that the table has a fixed size you have to tune.

Strong answer Diagnosis order:

  1. Symptom: new connections fail while existing ones are fine, CPU is idle, and the kernel log names the culprit. Conntrack is the kernel's connection-tracking table; NAT needs it, because to rewrite the reply packets of a DNAT-ed connection the kernel must remember every connection it has rewritten. Every published port and every outbound container connection creates an entry.
  2. Evidence: sysctl net.netfilter.nf_conntrack_max and sysctl net.netfilter.nf_conntrack_count. On many distributions the maximum defaults to 65,536 or a value derived from RAM, and that number matches the symptom. conntrack -L | wc -l, or cat /proc/net/nf_conntrack, shows what is filling it. Look at the TIME_WAIT proportion: short-lived connections from a client that does not reuse connections leave entries alive for the nf_conntrack_tcp_timeout_time_wait default of 120 seconds after they close.
  3. Ranked causes: first, the limit is simply too low for a gateway doing 1,000 connections per second times 120 seconds of lingering entries. Second, a client or the gateway itself is opening a fresh connection per request instead of keeping a pool. Third, a health checker or scanner is hammering the published port.
  4. Fix, in two steps. Immediately, raise the table: sysctl -w net.netfilter.nf_conntrack_max=1048576 and set the hash table size nf_conntrack_buckets to a quarter of that, both persisted in /etc/sysctl.d/. Then reduce the churn: shorten nf_conntrack_tcp_timeout_time_wait to 30 seconds, and enable keep-alive and connection pooling in the client, which in Java means a shared HttpClient instance rather than one per request.
  5. Longer term: run the gateway with --network host so its traffic is not NAT-ed and never enters the table, or let a real load balancer in front terminate the connections. In Kubernetes the same problem appears with kube-proxy in iptables mode, covered in E10.
  6. Prevention: alert when nf_conntrack_count exceeds 70 percent of the maximum. node_exporter already exports both numbers.

Land it NAT is not free — every published port is a row in a fixed-size kernel table, and the day a gateway gets popular is the day that table needs to be a sysctl you have already tuned.

Likely follow-ups
"You raised nf_conntrack_max and it filled again in an hour. What next?"

Then the churn is the problem, not the ceiling, and I need to see what is in the table.

conntrack -L -p tcp | awk '{print $4}' | sort | uniq -c groups entries by state; if most are TIME_WAIT, connections are being opened and closed at a rate the timeout cannot drain.

conntrack -L | awk '{print $5}' | sort | uniq -c | sort -rn | head groups by source and finds the one client or health checker responsible.

The fix then is on the client: keep-alive and a connection pool, or a load balancer that terminates connections.

I would also shorten nf_conntrack_tcp_timeout_time_wait to 30 seconds and nf_conntrack_tcp_timeout_established from its default of five days to a few hours, because idle established entries from dead clients otherwise never leave.

"What is the cost of a huge conntrack table?"

Memory and lookup time. Each entry costs roughly 300 bytes, so a million entries is about 300 MB of unswappable kernel memory, which on a small host is significant.

The hash table, nf_conntrack_buckets, must scale with it: the default is a quarter of the max, and if buckets stay small while max grows, each lookup walks a longer chain and every packet gets slower.

The bucket count is set through the module parameter or /sys/module/nf_conntrack/parameters/hashsize and needs the memory up front. So I size for the real connection rate times the effective timeout, with double headroom, rather than setting a giant number and forgetting it.

"Would host networking have prevented this, and what does it cost?"

Partly. With --network host the gateway's inbound connections are not DNAT-ed, so they do not need a conntrack entry for translation.

But conntrack still tracks every connection if any rule in the firewall uses connection state, which most host firewalls do, so the table still grows unless I add a -j NOTRACK rule in the raw table for the gateway's port.

The cost of host networking is port conflicts, no isolation, and a gateway that can see every host interface.

For a real gateway I would instead put a load balancer in front, so the box handles a few persistent upstream connections rather than every client's, which fixes the table size at the source.

"How does the same problem look on Kubernetes?"

The same table, filled by the same mechanism, because kube-proxy in iptables mode uses DNAT for every Service, and every pod's outbound traffic is masqueraded.

The symptom is the same nf_conntrack: table full on the node, and kube-proxy sets nf_conntrack_max per core by default, typically 32768 per CPU, with a floor of 131072. On a busy ingress node that still fills.

Fixes are the same sysctl tuning via a node config, plus a modern data plane: kube-proxy in IPVS mode or Cilium with eBPF replaces the iptables DNAT and removes most conntrack pressure. Node exporter's node_nf_conntrack_entries against node_nf_conntrack_entries_limit is the alert.

Q90 · Design. "Design the network layout for a Compose stack with a reverse proxy, two application services, Postgres, and Redis, so that a compromised app container cannot reach anything it does not need."

Reveal answer

Strong answer Requirements: only the proxy is reachable from outside, each app reaches only its own data stores, and the databases are never published. Assumptions: single host, Compose v2, Linux. The design uses three user-defined networks.

A frontend network holds the proxy and both apps, so the proxy can route to them by name. A data-orders network holds the orders app and Postgres, and a data-sessions network holds the web app and Redis.

Postgres and Redis are on their data network only and have no ports: section at all, so there is no DNAT rule and no way in from the host or the internet. The proxy is the only service with ports: ["443:443"].

Data networks get internal: true, which means Docker does not attach them to the host's routing, so a process on that network cannot reach the internet, which blocks the "exfiltrate the dump to a pastebin" step of an attack.

compose.yaml
services:
  proxy:
    image: caddy:2
    ports: ["443:443"]
    networks: [frontend]
  orders:
    image: registry.example.com/orders:1.4.2
    networks: [frontend, data-orders]
  web:
    image: registry.example.com/web:3.0.1
    networks: [frontend, data-sessions]
  db:
    image: postgres:17
    networks: [data-orders]
    volumes: [pgdata:/var/lib/postgresql/data]
  cache:
    image: redis:7
    networks: [data-sessions]
networks:
  frontend: {}
  data-orders:
    internal: true
  data-sessions:
    internal: true
volumes:
  pgdata: {}

Trade-offs: the orders app on an internal network cannot call an external payment API, so any service that needs egress must sit on a non-internal network too, which is why the apps stay on frontend. The embedded DNS only resolves names on networks the requesting container shares, so web cannot even resolve db, which is the point. What I would not do: put everything on one network and rely on application passwords, because a leaked Redis with no auth on a shared network is a five-minute compromise. I would also not use network_mode: host for the proxy just to save the NAT hop; it removes every boundary above.

Land it Networks in Compose are free and named, so the cheapest segmentation you will ever buy is one network per trust relationship and internal: true on the ones holding data.

Likely follow-ups
"The orders app now needs to call an external payment API but must not reach the internet freely. How do you change the design?"

I keep the app off any non-internal network for general egress and add a controlled path. A small forward proxy, such as Squid or Envoy, sits on both the frontend network and a new egress network, with an allow-list of hostnames limited to the payment provider.

The orders app moves to data-orders plus egress, and gets HTTPS_PROXY=http://egress:3128. It can then reach exactly one external hostname, every call is logged with a URL, and the proxy can pin the provider's certificate. The proxy is the only thing with real outbound access.

If the app framework cannot use a proxy, an iptables rule in DOCKER-USER restricting the bridge's outbound to the provider's IP range is the fallback, less precise because IP ranges change.

"What would you cut if you had ten minutes to ship this?"

I would keep two networks instead of three: a frontend network with the proxy and both apps, and one internal: true data network with both stores and both apps.

That loses the separation between the two apps' data stores, so a compromised web app could reach Postgres if it knew the password, but it still keeps the databases unpublished and cut off from the internet, which are the two controls that stop the common attacks.

I would also drop nothing else: no ports: on the stores and internal: true are single lines. Splitting the data network per app is a follow-up ticket that takes another ten minutes once the first version is running.

"How do you verify the segmentation actually works?"

With a test that tries to break it.

A throwaway container joined to the web app's namespace, docker run --rm --network container:web nicolaka/netshoot, runs getent hosts db, which must fail to resolve, and nc -zv 172.20.0.3 5432 using the database's real IP, which must time out because of the bridge isolation rules.

From the data network I try curl https://example.com and expect a failure because the network is internal. From the host I run ss -ltn and confirm only 443 is listening.

I put those four checks in a CI job that runs after docker compose up --wait, so a future edit that adds ports: to Redis fails the pipeline.

"Redis has no password here. Is the network enough?"

The network is the primary control, and the password is the second layer I would still add.

Network isolation stops a compromised web app from reaching Postgres, but the web app is meant to reach Redis, so if the web app is compromised, Redis is fully exposed to it either way.

The password limits what a different neighbour could do if segmentation was misconfigured later, and Redis 7 supports ACLs so the app user can be restricted to its own key prefix and denied FLUSHALL and CONFIG.

Two lines in the Compose file: command: redis-server --requirepass-file /run/secrets/redis_pw and a secrets: entry. Defence in depth is cheap here, and an unauthenticated Redis is a known way to get code execution.

Q91 · Design. "Your production images are distroless — no shell, no package manager. Design the debugging toolkit the on-call engineer uses when one of them misbehaves."

Reveal answer

Strong answer Requirements: inspect processes, network, files, and JVM state of a running distroless container without rebuilding or restarting it, and without giving on-call engineers root on the host. The design has four tools, each for one namespace.

First, for network questions, a pinned debug image such as nicolaka/netshoot started with docker run --rm -it --network container:<app> --pid container:<app>. Sharing the network namespace means ss, tcpdump, and curl see the app's sockets; sharing the PID namespace means ps and strace -p see its processes.

Second, for filesystem questions, docker cp app:/app/config /tmp/config and docker export app | tar -tv read the container's files from outside, and docker diff app lists what changed since start, which catches an app writing where it should not.

Third, for JVM questions, the debug image carries a matching JDK so jcmd <pid> Thread.print and jcmd <pid> GC.heap_info work through the shared PID namespace; the app must run with the same UID or the attach socket in /tmp is refused, so I mount --volumes-from app too.

Fourth, for kernel-level questions on the host, nsenter -t <pid> -n -m as a sudo-allowlisted command, which enters the network and mount namespaces with the host's own tools.

Trade-offs: the debug image is a second image to keep patched and pinned by digest, and PID sharing lets the debugger signal the app, so the runbook says "read-only commands only".

What I would not do: add busybox or curl to the production image "just in case", because every binary you ship is one an attacker can use, and it undoes the reason for distroless. I would also not enable SSH into containers.

Land it Distroless moves the tools out of the image and into a namespace you join at debug time — the same wins that Kubernetes formalises as ephemeral debug containers.

Likely follow-ups
"jcmd through the shared PID namespace fails with 'Unable to open socket file'. Why, and what is the fix?"

The JVM attach mechanism works through a Unix socket at /tmp/.java_pid<pid> and a trigger file in the target's working directory, and the JVM only accepts the attach if the requesting process has the same effective uid and can see the same /tmp.

Two things are usually wrong: the debug container runs as root while the app runs as 10001, and the debug container has its own /tmp.

The fix is --user 10001 --pid container:app --volumes-from app plus a shared tmp, or simplest, run jcmd from inside the app's mount namespace with nsenter -t <pid> -m -p -u <jdk>/bin/jcmd 1 Thread.print as that uid.

Since JDK 17, jcmd inside a container with the same namespaces works reliably; the uid rule is the one that catches people.

"Why not just build a debug variant of the production image with tools included?"

It is a reasonable second option and distroless itself publishes :debug tags with busybox for exactly this.

The problem is that the debug variant is a different digest, so to use it I must redeploy, which restarts the process and destroys the state I wanted to inspect, and it must be scanned and signed separately or it becomes the way untracked images reach production.

Sidecar debugging joins the namespaces of the running process, so the evidence stays. I keep the debug variant for reproducing a problem in staging where a restart is fine, and the namespace-joining toolkit for production incidents where the running state is the whole point.

"How do you stop the debug toolkit becoming a privilege escalation path?"

By constraining what it can do rather than who can run it. The debug image is pinned by digest, built by the platform team, and scanned like any other.

It runs with --cap-drop=ALL --read-only, and with --pid container:app it inherits the app's uid so it cannot signal or ptrace anything the app could not. It never gets the Docker socket or host mounts.

The sudo allow-list for nsenter on the host permits only the network and mount namespace flags and only against Docker container PIDs, with every invocation logged to the audit trail.

And the runbook lists the exact commands, so an on-call engineer copying from it never improvises a --privileged flag at 03:00.

"What would you do differently on Kubernetes?"

The same design, formalised. kubectl debug -it <pod> --image=registry.internal/debug@sha256:… --target=app creates an ephemeral container that shares the pod's network and, with --target, the app container's PID namespace, so it is the sidecar approach without the Docker flags.

kubectl debug node/<node> gives a host-level shell for the nsenter cases. The security controls become a policy: the debug image is allow-listed, ephemeral containers are permitted only from a specific role, and the pod security standard forbids privileged debug containers.

JVM attach rules are unchanged, so the debug image runs as the app's uid and shares /tmp via an emptyDir both containers mount.

Drill · Storage & data persistence

This group tests whether you know where a container's bytes actually live, which of them survive, who owns them, and why a database on the wrong layer is a slow-motion outage.

Q92. "Volumes, bind mounts, tmpfs — what is each one physically, and when do you choose which?"

Reveal answer

The real test Whether you can say who owns the directory on the host side, because that decides ownership, copy-in, and survival.

Strong answer All three are directories that appear inside the container, and the difference is who owns the directory on the host side.

A volume is a directory that Docker creates and manages, under /var/lib/docker/volumes/<name>/_data by default, using the local driver, though other drivers can put it on NFS or a cloud disk. You create it with docker volume create pgdata or just by naming it in -v pgdata:/var/lib/postgresql/data.

Docker sets its ownership to match whatever the image had at that path and copies the image's existing files into it on first use.

A bind mount is any host path you choose, given with an absolute path such as -v /home/me/src:/app or, more explicitly, --mount type=bind,src=/home/me/src,dst=/app.

Docker does nothing to it: no ownership fix, no copy-in, and if the host path does not exist the -v form silently creates an empty root-owned directory, which is a classic trap.

A tmpfs mount, from --tmpfs /tmp or --mount type=tmpfs, lives only in memory, is gone when the container stops, and counts against the container's memory limit.

The decision: volumes for data that must outlive the container and that only containers touch, so databases, message broker logs, and uploaded files. Bind mounts for things the human on the host edits, so source code in development and config files you want to reload.

Tmpfs for secrets and scratch space that must never hit disk. The one thing to remember in interviews is that bind mounts are the only option that lets the host escape into the container, which is why the security group frowns on them in production.

Land it Volumes are Docker's directory, bind mounts are yours, tmpfs is RAM — pick by who needs to touch the files and whether they must survive.

Likely follow-ups
"What is the difference between -v and --mount, and which do you use?"

They create the same kinds of mounts but behave differently at the edges.

-v is the short syntax: a path with a slash is a bind mount, anything else is a volume name, and if a bind source does not exist Docker creates it as an empty root-owned directory.

--mount type=bind,src=...,dst=... is explicit, and it fails with an error if the source is missing, which is the behaviour I want in production scripts. --mount also exposes options that -v cannot, such as bind-propagation, volume-driver, tmpfs-size, and read-only for tmpfs.

I use -v when typing at a terminal and --mount in anything committed, because the loud failure on a typo has saved me from mounting an empty directory over a database more than once.

"When does a volume get the image's files copied in, and when does it not?"

Only for a named or anonymous volume that is empty on first use, and only with the local driver by default.

Docker copies the contents of the image at the mount path into the volume, including ownership and permissions, which is why a Postgres volume ends up owned by uid 999 without any chown.

If the volume already has files, nothing is copied and the volume's contents shadow the image's. Bind mounts never get copy-in; the host directory shadows whatever the image had, so mounting an empty host directory over /app hides the application.

The --mount option volume-nocopy disables the copy-in for volumes, which matters when the image path holds gigabytes you do not want duplicated.

"Does tmpfs really count against the memory limit, and what happens when it fills?"

Yes. A tmpfs mount is page cache that cannot be evicted, and it is charged to the cgroup of the process that wrote it.

With --memory 1g and --tmpfs /tmp:size=512m, a process that writes 512 MB to /tmp has 512 MB less for its heap, and if it then allocates past the limit the OOM killer fires even though the heap alone would fit.

Writing past the tmpfs size returns ENOSPC to the application, which is the friendlier failure, so I always set a size. Tools should also be told where the scratch space is, for example -Djava.io.tmpdir, so a heap dump does not land on a 64 MB tmpfs.

On restart the contents are gone, which for secrets is the point.

"How do you move a volume to another host?"

Through a container, never by copying /var/lib/docker. On the source host, docker run --rm -v pgdata:/data:ro -v $PWD:/out alpine tar czf /out/pgdata.tgz -C /data . writes an archive with ownership preserved as numeric uids.

Copy the archive over, then on the target, docker volume create pgdata and the mirror command with tar xzf. For a database, stop the container first or use a consistent snapshot, because a tar of a live data directory is not a valid backup.

For repeated moves, a volume driver that backs volumes with network or cloud storage, or simply a managed database, removes the need. docker volume has no export subcommand, and that is deliberate.

Q93 · Scenario. "A developer ran docker compose down -v to 'clean up' and the team's shared staging Postgres is empty. They also report that a plain docker compose down earlier had never lost data. Explain what happened and how you would have prevented it."

Reveal answer

The real test Whether you know exactly which resources each Compose command destroys, and that a named volume is a separate object with its own lifecycle.

Strong answer In order:

  1. Symptom: data gone after down -v, fine after plain down. docker compose down stops and removes the containers and the project's networks but leaves volumes alone, because a container is disposable and its volumes are the whole point of volumes. The -v flag, spelled out as --volumes, additionally deletes every named volume declared in the file plus the anonymous volumes attached to the containers. That is the data.
  2. Evidence: docker volume ls no longer shows staging_pgdata; the daemon log, journalctl -u docker, records the volume removal with a timestamp; and the Compose file will show the volume declared under the top-level volumes: key without the external: true flag.
  3. Cause: a single flag. There is no undo; a removed local volume is an rm -rf of its directory.
  4. Fix: restore from the last backup, and if there is none, this incident is the reason there will be one. The E8 point-in-time recovery discussion applies once the database is back.
  5. Prevention, three layers. Declare the volume as external: true and create it once by hand with docker volume create staging_pgdata; Compose then refuses to delete it even with -v. Run a nightly pg_dump from a sidecar container into object storage. And stop sharing a mutable staging database through Compose on one box; a shared environment deserves a managed database or at least a host where developers do not have the Docker socket, since anyone who can run docker on that host can delete anything on it.

Land it The difference between down and down -v is the difference between "restart the app" and "drop the database" — external: true is the seat belt that makes the second one impossible by accident.

Likely follow-ups
"The volume is gone and there is no backup. Is there any recovery?"

Very little, and I would be honest about it early. Removing a local volume unlinks the files under /var/lib/docker/volumes/<name>/_data.

If the filesystem is ext4 or XFS and nothing has written since, forensic tools such as extundelete or photorec on an unmounted copy of the block device can sometimes recover raw files, but Postgres data files without a consistent WAL are rarely usable.

If the host is a cloud VM with disk snapshots enabled, the last snapshot is the real hope, and I would check that first.

Otherwise the recovery is a rebuild from the sources that fed staging, usually a sanitised copy of production, which is what the team should have been refreshing from anyway.

"With external: true, can anything else still delete the data?"

Yes: docker volume rm staging_pgdata by any socket user, docker volume prune -a when no container is attached, a host rebuild that recreates /var/lib/docker, and disk failure. external: true only removes Compose from the list.

So the seat belt is one layer, and the backup is the real protection. I would also label the volume, docker volume create --label keep=true, so the nightly prune with --filter label!=keep skips it, and move the host's Docker data directory onto a disk with snapshots.

Removing developers from the docker group on that host addresses the human vector entirely.

"How would you make the backup automatic in the same Compose file?"

A sidecar service on the data network that runs pg_dump on a schedule.

In Compose I use a small image such as prodrigestivill/postgres-backup-local or my own Alpine with the Postgres client, with SCHEDULE set to daily at 02:00, the database password from a Compose secret, and a bind mount or volume for the output that a host cron job syncs to object storage with rclone or aws s3 sync.

The dump uses -Fc custom format so restore can be selective. A second tiny service, on a profiles: [verify] profile, restores the latest dump into a scratch database and runs a row count.

Both are in the file so every environment that copies it inherits the backup.

"What should the developer have run instead of down -v?"

It depends what they wanted to clean. To stop and remove the containers and networks while keeping data, plain docker compose down. To remove images too, down --rmi local.

To reset their own throwaway local database, down -v is right, which is exactly why it exists and why it is dangerous on a shared host. To reclaim space from dangling things, docker system prune without --volumes.

The teaching point is that a command safe on a laptop was run on a shared host with the same muscle memory, so the fix is to make the shared host different: no interactive Docker access, and the data marked external and labelled.

Q94 · Scenario. "A Postgres container keeps restarting with could not open directory /var/lib/postgresql/data: Permission denied or initdb: directory exists but is not empty. The data directory is a bind mount. What is wrong?"

Reveal answer

Strong answer Diagnosis order:

  1. Symptom: the two messages point at two different causes that both come from bind mounts. Permission denied is a uid mismatch; "exists but is not empty" is a mount-point layout problem.
  2. Evidence: ls -ln /srv/pgdata on the host shows the numeric owner. The official image runs Postgres as user postgres with uid 999, and file permissions travel by number, not by name. If the host directory is owned by uid 1000, your login user, or by root because -v auto-created it, Postgres cannot write. docker logs db shows which message you actually get. ls -la /srv/pgdata reveals a lost+found directory if the bind mount is the root of a separate ext4 filesystem or a cloud disk.
  3. Cause one: ownership. Fix with sudo chown -R 999:999 /srv/pgdata, or run the container with --user 1000:1000 so Postgres runs as your uid and the directory is already yours. The entrypoint supports that, but then /etc/passwd inside has no entry for 1000, so also mount /etc/passwd read-only or accept the "I have no name" warning.
  4. Cause two: a non-empty mount root. initdb, the program that creates a new cluster, refuses to run in a directory that has anything in it, and lost+found counts. The fix is the PGDATA environment variable: set PGDATA=/var/lib/postgresql/data/pgdata so the cluster lives in a subdirectory the image creates itself.
  5. Prevention: prefer a named volume, since Docker sets the owner to 999 automatically on first use by copying the image's directory metadata. If you need a bind mount, create it in provisioning with the right uid, and put the PGDATA subdirectory in the Compose file from day one. On SELinux hosts you additionally need :Z on the mount, or you get permission denied even with the correct uid.

Land it Permissions inside a container are just numbers on the host's disk — match the uid, or let a named volume match it for you, and give Postgres a subdirectory so the mount point's furniture does not block initdb.

Likely follow-ups
"You chowned the directory to 999 and it still says permission denied. What next?"

Then something other than the uid is blocking the write.

On a Fedora, RHEL, or Rocky host, SELinux denies the container access to a host directory that does not carry the container file label, and the error is the same permission denied; ls -Z /srv/pgdata shows the label, ausearch -m avc -ts recent shows the denial, and :Z on the mount fixes it.

Second suspect: the directory is on NFS or a cloud file share with root squash or a different uid mapping, which mount | grep pgdata reveals.

Third: the daemon runs with userns-remap, so uid 999 in the container is 100999 on the host and the chown target should be that. Fourth: a parent directory lacks execute permission for others, so the path cannot be traversed even though the leaf is owned correctly.

"Why is it uid 999 and does it matter if the next image version changes it?"

The official image creates the postgres system user at build time, and on Debian system users are allocated from 999 downward, so it lands on 999 and the maintainers pin it there for stability.

It matters because permissions on a bind mount are numeric: if a future image used 70, as the Alpine variant does, the existing directory owned by 999 would be unreadable.

That is one reason to prefer a named volume, where Docker set the owner from the image the first time, and one reason to pin images by digest and read the changelog on upgrade.

If I switch variants I chown the data directory as part of the upgrade runbook.

"What are the alternatives to running with --user 1000:1000 when the entrypoint needs root?"

The Postgres entrypoint starts as root to fix ownership and then drops to the postgres user with gosu, so running it as root inside is normal and safe with userns-remap.

If policy forbids container root entirely, the entrypoint supports starting directly as the target uid, provided the data directory is already owned by that uid and /var/run/postgresql is writable, which a tmpfs mount gives it.

A cleaner option is an init container or a one-off docker run --rm -v /srv/pgdata:/d alpine chown 999:999 /d during provisioning, so the database container never needs root.

The "I have no name" warning from a missing passwd entry is cosmetic for Postgres but breaks some tools, so I mount a minimal passwd file read-only when using an arbitrary uid.

"How would you catch these mistakes in CI?"

With the same Compose file started in CI on a Linux runner using docker compose up --wait, which fails if the database never becomes healthy, and a bind mount deliberately created with the wrong owner in a negative test to make sure the healthcheck catches it rather than a later application error.

I would also run the stack once on a Fedora runner with SELinux enforcing, because most teams test only on Ubuntu and discover the label problem in production.

A Hadolint-style lint for Compose files that requires PGDATA to point at a subdirectory whenever the data path is a bind mount closes the initdb variant. These take an afternoon and turn a recurring ticket into a pipeline failure.

Q95. "Why is it a bad idea to keep a database's data directory on the container's writable layer, and what does fsync have to do with the answer?"

Reveal answer

The real test Whether you can explain copy-up and the container lifecycle, not just repeat "use a volume".

Strong answer The container's writable layer is provided by overlay2, a union filesystem that stacks the read-only image layers under one thin read-write directory. It is built for small, short-lived writes such as logs and caches, and it has three properties that hurt a database.

First, it is deleted with the container: docker rm or a Compose recreate takes the data with it, and a plain image upgrade means a fresh empty layer.

Second, it uses copy-up: the first write to any file that exists in a lower layer copies the whole file into the upper layer before modifying it.

A database that writes 8 KB into the middle of a 1 GB table file pays for a 1 GB copy the first time.

Third, and this is where fsync comes in, fsync is the system call a database makes at commit time to force data from the operating system's cache onto the disk before it tells the client "committed".

Overlay2 passes fsync through to the underlying filesystem, so durability itself is honoured, but the extra layer adds latency to each call and, more importantly, the metadata for the union view is separate from the backing files, so certain crash sequences have left the upper directory inconsistent in ways a plain ext4 or XFS directory would not be.

A named volume gives them exactly that, because a volume is a plain directory on the host filesystem bind-mounted into the container, with no union layer in the path.

The performance delta is measurable: benchmarks of heavy write workloads commonly show 20 to 50 percent lower throughput on overlay2 than on a volume, and the copy-up spikes are worse than the average suggests.

Land it Overlay2 is a clever trick for images, and a database is the one workload that punishes every part of that trick — put the data directory on a volume and let the engine talk to a real filesystem.

Likely follow-ups
"How would you measure the overlay2 penalty on your own hardware?"

With the database's own benchmark, run twice on the same host.

pgbench -i -s 100 to load, then pgbench -c 16 -j 4 -T 300 for five minutes, once with the data directory on a named volume and once left on the writable layer, same container limits and same disk.

I would record transactions per second and the p99 latency, and watch iostat -x 1 during both to see write amplification.

I would run each three times and discard the first, because the first run on overlay2 includes copy-up of the loaded tables and would exaggerate the gap.

Whatever the numbers, the lifecycle argument alone decides it, so the benchmark is for the write-up rather than the decision.

"Does this apply to a volume on a network filesystem like NFS or EFS?"

A volume avoids the union layer, but the filesystem under it still matters, and NFS is its own problem.

Postgres documents that it works on NFS only with hard mounts and synchronous writes, because fsync on a soft or async NFS mount can return before the server has the data on disk, which breaks the durability promise entirely.

Latency per fsync on a network filesystem is also several times a local SSD, and Postgres fsyncs the WAL at every commit, so commit throughput drops accordingly.

So the ranking is: local SSD volume best, cloud block storage such as EBS fine, network file storage acceptable only for read-heavy or test workloads. Overlay2 on top of any of them is the worst of both.

"What about SQLite or an embedded store — same rule?"

Same rule, milder consequences. SQLite fsyncs at commit too and rewrites pages in place, so it suffers copy-up on the first write to a database file that exists in the image, which for an image that ships a seeded database means copying the whole file.

The bigger issue is still lifecycle: a container recreate loses the file. For anything the user expects to persist, mount a volume at the database's directory.

For a read-only reference database baked into the image, leaving it on the image layer is fine, since reads on overlay2 are near native and nothing is ever copied up.

The question I ask is "does this file change and must it survive", and the answer places it.

"Are there Docker storage drivers where this is less of a problem?"

Historically devicemapper and btrfs had different characteristics: block-level copy-on-write rather than file-level, so a small write to a large file did not copy the whole file.

They had other costs and are deprecated or rarely used as of Aug 2026; overlay2 is the default everywhere and the only one worth knowing for interviews.

ZFS as a storage driver still exists and does block-level copy-on-write with snapshots, which some people use for fast database cloning in test environments.

None of that changes the answer for production: the writable layer is disposable by design, and a database wants a directory that is not.

Q96 · Scenario. "On Docker Desktop for Mac, a Node project bind-mounted from the laptop takes 40 seconds for a change to show up and npm install takes ten minutes. On a colleague's Linux box the same setup is instant. Why, and what do you change?"

Reveal answer

Strong answer In order:

  1. Symptom: file-heavy operations on a bind mount are dramatically slower on macOS and Windows than on Linux. That is the fingerprint of the file-sharing boundary in Docker Desktop.
  2. Evidence: docker info shows the Desktop version and the file-sharing implementation. Inside the container, time find /app/node_modules | wc -l against time find /tmp/x | wc -l on a volume shows the gap. On macOS, Desktop's settings show whether VirtioFS or the older gRPC FUSE is selected.
  3. Cause: on Linux, Docker is native and a bind mount is the same directory with zero overhead. On macOS and Windows the containers run inside a Linux virtual machine, and every file access on a bind mount crosses from the VM to the host file system through a sharing protocol. Since 2022 that protocol is VirtioFS, which is far faster than the earlier osxfs, but every stat and open is still a round trip, and node_modules holds hundreds of thousands of small files. The 40-second delay is the file watcher polling that tree over the boundary.
  4. Fix: keep the source as a bind mount but put node_modules on a named volume that shadows it: -v ./src:/app -v node_modules:/app/node_modules. The volume lives inside the VM's own disk, so the dependency tree is native speed, while the ten source files you actually edit still sync from the laptop. Better still, use Compose's develop.watch with action: sync, which copies changed files into the container instead of mounting at all, and action: rebuild on package.json.
  5. Prevention: write this into the team's compose.yaml so nobody rediscovers it, and set the watcher to use native events rather than polling.

Land it On a Mac every bind-mounted file is a network call to the host — mount the code you edit and volume the tree you do not, or sync instead of mounting.

Likely follow-ups
"You moved node_modules to a volume and now npm install on the host and in the container disagree. What broke?"

The volume shadows the host's node_modules, so there are now two dependency trees: one on the laptop that the editor and any host-side tooling see, and one inside the container that the app runs against.

When someone adds a package on the host, the container does not have it until npm install runs inside.

The rule is that dependencies are installed only in the container, with a develop.watch entry of action: rebuild on package.json and package-lock.json, and the host tree exists only for editor completion.

Native modules compiled on macOS would not run in Linux anyway, so the split is correct. I document the one command, docker compose exec app npm install <pkg>, and stop running npm on the host.

"What are the Docker Desktop settings that affect this, as of Aug 2026?"

Under Settings, General, the file-sharing implementation: VirtioFS is the default and the fastest; the older gRPC FUSE exists for compatibility and is noticeably slower. Under Resources, File sharing, only the directories listed can be bind-mounted, and a shorter list makes lookups faster.

Synchronized file shares, a feature Docker added in 2024 built on Mutagen, replaces the live share with a background two-way sync and gives near-native speed for large trees at the cost of a short delay before changes appear.

The virtual machine's CPU and memory allocation matters for compile-heavy work. And the choice of virtualisation framework, Apple Virtualization with Rosetta enabled for amd64 images on Apple silicon, avoids QEMU emulation, which would otherwise be a separate slowdown.

"Why is Compose watch better than a bind mount for source?"

Because it removes the shared filesystem from the runtime path entirely.

With action: sync, Compose watches the host directory for changes and copies only the changed files into the running container's own filesystem, so the container reads local disk at native speed and nothing crosses the VM boundary per file access.

The file watcher inside the container then sees a native inotify event instead of polling a slow mount.

The trade-off is that the copy is one-way and takes a fraction of a second, so files the container writes, such as generated code, do not appear on the host unless you add a reverse path, and the image must already contain the tree at first start.

For the edit-run loop it is faster and simpler than tuning mount options.

"The colleague on Linux is fast, so is there any reason for the Mac developer to use Docker for this at all?"

The reason is parity: the same Postgres, Redis, and Node version as production, started with one command. But for a pure Node service, running the dependencies in Compose and the Node process natively on the laptop is a legitimate pattern.

Node on macOS is fast, the debugger attaches trivially, and the app connects to the containers on published loopback ports. What is lost is the Linux runtime parity for the application itself, which for Node rarely matters unless there are native modules.

I offer both in the repository: docker compose up for the full stack, and docker compose up db cache plus npm run dev for people who want native speed and know the trade.

Q97. "Where do anonymous volumes come from, what does docker volume prune actually remove, and what do :ro, :z, and :Z do on a mount?"

Reveal answer

Strong answer An anonymous volume is a volume with a random 64-character hex name that Docker creates when a container needs a volume but you did not name one.

The usual source is the VOLUME instruction in a Dockerfile: the official postgres image declares VOLUME /var/lib/postgresql/data, so every docker run postgres without a -v for that path silently creates one. The other source is -v /some/path with no host side.

They accumulate; a CI machine that starts Postgres containers all day can hold thousands of them, each with a 40 MB initialised cluster.

docker rm -v removes a container's anonymous volumes with it, and docker volume prune removes every volume not attached to any container, whether named or anonymous, which is why it asks for confirmation and why --filter label=keep or the -a flag matter.

Since Docker 23 it only removes anonymous ones unless you pass -a. docker volume ls -f dangling=true shows what it would take. For copying data in or out without a mount, docker cp app:/var/log/app.log ./ works on stopped containers too.

The mount suffixes: :ro mounts read-only, so a config directory cannot be modified by a compromised app. :z and :Z only matter on SELinux hosts.

SELinux is a mandatory access control system that labels every file, and a container process can only touch files carrying the container label. :z relabels the host directory as shared among containers, and :Z relabels it as private to this one container.

Using :Z on your home directory relabels all of it, which then breaks the host's own tools, so be careful what path you attach it to.

Land it Name your volumes, prune with a filter, and treat :Z as a chown for SELinux that you never point at a directory you share with the host.

Likely follow-ups
"Why does the VOLUME instruction in a Dockerfile cause trouble, and should you use it?"

It creates an anonymous volume for every run that does not supply a mount, and it has a build-time side effect that surprises people: any RUN after the VOLUME line that writes to that path has its changes discarded, because the path is mounted as an empty volume during each subsequent build step.

So a Dockerfile that declares VOLUME /data and then seeds /data ships an empty directory. It also cannot be removed by a child image.

I do not use it in my own images; the Compose file or the run command declares the mount, where it is visible and intentional. Official images use it as documentation of "this path should be a volume", and I honour that by always naming one.

"How would you clean up thousands of anonymous volumes on a CI host safely?"

First I check nothing running depends on them: docker volume ls -f dangling=true -q | wc -l counts the candidates, and dangling means no container, running or stopped, references them.

Then docker volume prune without -a, which since Docker 23 removes only anonymous dangling volumes and leaves named ones, which is the right default for a CI host. I schedule it nightly with --force and a label filter, --filter label!=keep, so a deliberately kept volume survives.

The root cause is docker run without --rm; adding --rm removes the container and its anonymous volumes together at exit, and Testcontainers' Ryuk sidecar does the same for test runs.

"What goes wrong if you use :Z on a shared directory?"

The :Z option runs a recursive relabel, setting each file's SELinux context to a label private to that one container with a unique category pair, such as container_file_t:s0:c123,c456.

Any other container gets denied, and host processes running under a confined domain, such as the web server or a backup agent, may also lose access. Pointing it at your home directory or at /var/lib relabels everything beneath, and undoing it needs restorecon -R.

:z with the shared label avoids the per-container lockout but still relabels. For system directories the correct approach is to leave the label alone and add a targeted policy, or to use --security-opt label=disable on that one container if the risk is acceptable.

"Can a read-only mount still be modified by the container?"

Not through that mount point; the kernel enforces read-only at the mount, so even root inside gets EROFS on write. Two caveats.

A bind mount with :ro is read-only only at the top: submounts underneath are not automatically read-only unless you add the rro recursive-read-only option, which Docker supports on kernels 5.12 and later through --mount type=bind,readonly,bind-recursive=readonly.

And a container with CAP_SYS_ADMIN can remount, which the default capability set does not include and which is one more reason to drop capabilities.

A tmpfs and a volume also accept ro; I use it on config mounts and on the source volume of a build to prove the build does not modify inputs.

Q98 · Design. "Design the volume and backup strategy for a stateful service running in a container — say a Postgres used by a small internal tool — including how you restore and how you know the backup works."

Reveal answer

Strong answer Requirements: no data loss beyond one day, restore in under an hour, and no dependency on the container that produced the data. Assumptions: one host, data under 50 GB, a Compose deployment.

The storage design is a named external volume pgdata with PGDATA set to a subdirectory, so neither down -v nor a mount-root quirk can touch it. Backups come in two flavours.

Logical backups run nightly from a sidecar container that shares the data network and runs pg_dump -Fc into a dated file on object storage; these are engine-version independent and restore anywhere.

Physical backups are a snapshot of the volume for fast full restore: stop the database or use a filesystem snapshot, then archive the volume through a throwaway container so no host tool needs to know Docker's paths.

backup-volume.sh
#!/usr/bin/env bash
set -euo pipefail
# Archive the named volume "pgdata" into ./backups/pgdata-<date>.tgz
# using a throwaway Alpine container, so nothing on the host touches
# /var/lib/docker directly.
stamp=$(date +%Y%m%d-%H%M)
mkdir -p ./backups
docker run --rm \
  -v pgdata:/data:ro \
  -v "$PWD/backups":/out \
  alpine:3.20 \
  tar czf "/out/pgdata-${stamp}.tgz" -C /data .
echo "wrote backups/pgdata-${stamp}.tgz"

Restore is the mirror: docker volume create pgdata-restore, then the same container with the volume writable and tar xzf. The part people skip is verification: a weekly job restores the latest dump into a fresh postgres:17 container on a scratch volume, runs SELECT count(*) on three key tables, and posts the numbers to the team channel; a backup nobody has restored is a hope. Trade-offs: pg_dump of 50 GB takes minutes and loads the database, so I schedule it at 02:00; the tar snapshot is only consistent if the database is stopped or the filesystem supports atomic snapshots, so on a plain ext4 host I stop the container for the 30 seconds it takes. What I would not do: rely on docker commit, which does not capture volumes at all, or copy /var/lib/docker/volumes by hand, which ties the backup to one host's Docker layout. For anything larger or with a tighter recovery objective, the answer is a managed database, as the next question argues.

Land it External named volume, logical dump nightly, throwaway-container tar for full restores, and a scheduled restore test — the fourth one is the one that makes the first three real.

Likely follow-ups
"The recovery point objective changes from one day to fifteen minutes. What changes?"

A nightly dump cannot meet it, so I add continuous WAL archiving.

Postgres writes every change to the write-ahead log before the data files, and with archive_mode=on and archive_command shipping each 16 MB segment to object storage, plus a weekly base backup, I can restore to any second.

In a container the practical tool is pgBackRest or WAL-G running as a sidecar sharing the data volume, with archive_timeout=300 so a quiet database still ships a segment every five minutes. Restore becomes: base backup, then replay WAL to the chosen time.

This is more moving parts, the restore test becomes mandatory weekly, and at this point I would say out loud that the requirement is now one a managed database meets by default.

"How do you take a consistent snapshot without stopping the database?"

Two safe ways. Logically, pg_dump runs inside a single transaction using a snapshot, so it is always consistent without stopping anything; that is why it is the nightly default.

Physically, either use the database's own backup mode, which is what pg_basebackup does by streaming data files plus the WAL needed to make them consistent, or take an atomic filesystem snapshot such as an LVM, ZFS, or cloud disk snapshot while the database runs.

An atomic snapshot is crash-consistent: Postgres treats it as a crash and recovers from the WAL on start, which is safe as long as the data directory and WAL are on the same snapshot.

A plain tar of a live directory is not atomic and can produce a corrupt copy.

"What would you cut under time pressure and what would you never cut?"

I would cut the physical tar snapshot entirely; for a 50 GB internal tool, restoring from a logical dump in twenty minutes is acceptable, and one backup method well-tested beats two half-done.

I would cut the weekly automated restore verification to a manual restore once, today, with the result recorded, and a ticket for the automation.

I would never cut the external named volume with a subdirectory, because that takes five minutes and prevents the most common data loss.

And I would never cut the nightly dump to a location off the host, because a backup on the same disk as the database is not a backup. The order of value is: off-host copy, external volume, one proven restore, automation.

"How do you handle a major-version Postgres upgrade with this setup?"

Not by changing the image tag, because Postgres 17's data directory is unreadable by 18 and the container simply fails to start.

The safe path for a small database is dump and restore: run pg_dumpall from the old container, stop it, create a fresh volume, start the new major version, restore the dump, and keep the old volume until verified.

For larger databases, pg_upgrade needs both binaries present, which the pgautoupgrade community image or a custom image provides, run against the data volume with --link to avoid copying.

Either way it is a runbook with a rollback, tested in staging on a copy of the volume, and scheduled in a window. Pinning the image by digest is what stops it happening by accident.

Q99 · Design. "Write the policy for running databases in containers at your company. Where is it fine, where is it forbidden, and what conditions apply in between?"

Reveal answer

Strong answer Assumptions: a mid-sized company with cloud accounts, a platform team, and a few dozen services. The policy has three tiers.

Tier one, always allowed: local development and CI. A postgres:17 container in Compose or Testcontainers is the best possible development database, because every engineer gets the exact production version, a fresh state on demand, and no shared-environment drift.

The condition is that the data is disposable by definition. Tier two, allowed with conditions: staging, internal tools, and anything whose loss costs a day of someone's time but no revenue.

Conditions are the ones from the previous question: external named volume on a real filesystem, PGDATA subdirectory, nightly logical dump to object storage, a tested restore, memory limits so the host does not swap, and the container pinned by digest with a documented upgrade procedure, since a major-version Postgres upgrade in a container is a manual pg_upgrade step, not an image tag change.

Tier three, forbidden without a written exception: any production database of record. Not because containers are unsafe, but because the hard parts of a production database are outside the container: replication, failover, point-in-time recovery, storage that survives the host, connection pooling, and patching.

A managed service such as RDS or Cloud SQL, or a Kubernetes operator like CloudNativePG run by a team whose job it is, delivers those; a docker run on one VM does not, and the person who set it up leaves.

The exception path requires a named owner, a tested failover, and a restore drill on the calendar. Trade-offs: managed databases cost more per month and less per outage.

What I would not do is ban containers for data outright; that just pushes teams to run Postgres on a bare VM with even fewer guardrails, and it breaks the local-dev story that makes everything else reproducible.

Land it Containers are the best way to run a database you are allowed to lose and the worst way to run one you are not — the policy is just that sentence with conditions for the middle.

Likely follow-ups
"A team argues that a Kubernetes operator makes containers fine for production databases. Where does that fit your policy?"

It fits as the exception path becoming a supported tier, provided someone owns it. CloudNativePG, Zalando's operator, and the Percona operators do deliver replication, failover, backup to object storage, and point-in-time recovery; they solve the hard parts I said were outside the container.

What they do not solve is who is on call for the operator itself, who upgrades it, and who tests failover every quarter.

So the policy says: an operator-managed database is permitted for production when a platform team owns the operator with a documented service level, storage is a replicated cloud block class, and the quarterly failover and restore drills are on a calendar.

Without that ownership it is a managed service, because the failure mode of an unowned operator is worse than a VM.

"What about a company with no cloud provider — is a managed service still the answer?"

Then the choice is between a well-run database on virtual machines or bare metal, with streaming replication, a failover manager such as Patroni, and tested backups, and the same thing inside containers under an operator.

On-premises, containers under Kubernetes with an operator are often the better choice, because the operator encodes the failover and backup procedures that a small team would otherwise write by hand in shell.

The policy adapts: tier three becomes "production databases run only under the platform team's operator or on the DBA team's VM standard", and a docker run postgres on a single host stays forbidden. The principle survives; only the name of the owning team changes.

"How do you enforce a policy like this rather than just publish it?"

At the points where things get created.

A CI check flags any Compose file or Kubernetes manifest destined for a production environment that contains a known database image, postgres, mysql, mongo, redis with persistence, and fails unless the file carries an exception label with a ticket number.

In Kubernetes an admission policy does the same at deploy time. A nightly inventory job lists every running container across production hosts matching those images and posts the list to the platform channel with owners.

And the cost of following the policy is kept low: a managed database is requestable through a Terraform module in a pull request, which is easier than writing a Compose file. A policy people can follow in ten minutes gets followed.

"Why is a container database in CI the best development database, and is there anything it hides?"

It is the exact production version, created fresh for every test run, so tests never depend on leftover state and schema migrations are exercised from empty on every commit; Testcontainers starts it in a few seconds and tears it down.

What it hides is scale and configuration: a container Postgres with default settings on a laptop has no replication lag, no connection limit pressure, no statement timeout, and a tiny dataset, so queries that scan a million rows in production look instant.

I compensate with a staging environment that has realistic data volume and the production parameter group, and with a test that runs EXPLAIN on the critical queries against a seeded table large enough to show a sequential scan.

Drill · Compose v2

These questions test whether you can run a multi-service stack the way Compose v2 intends in 2026 — healthchecks, ordered startup, hot reload, profiles, and limits — rather than the way a 2018 tutorial did it.

Q100. "What changed between the old docker-compose and today's docker compose? Name the things a 2019-era file does wrong."

Reveal answer

The real test Whether your mental model of Compose is the 2026 plugin and specification or the retired Python tool.

Strong answer The old tool was a separate Python program called docker-compose with a hyphen. Since 2021 Compose is a Go plugin of the Docker CLI, invoked as docker compose with a space, and as of Aug 2026 it is on the 2.4x line.

The file format is now the Compose Specification, one merged schema instead of the old numbered versions. Concretely, a modern file is named compose.yaml, and the version: "3.8" line at the top is obsolete; v2 ignores it and prints a warning, so delete it.

The old file typically has depends_on: [db] as a bare list, which only orders container start and says nothing about readiness; today you write depends_on: db: condition: service_healthy paired with a healthcheck: on the database.

It probably has links:, which are replaced by the project network's DNS, and container_name: everywhere, which breaks --scale and parallel projects.

Resource limits in 2019 lived under deploy.resources and were ignored outside Swarm, or under the v2-format mem_limit; in Compose v2 deploy.resources.limits.cpus and memory are honoured by plain docker compose up, so that is where they go.

New things a modern file uses: profiles: to make optional services opt-in, develop.watch for file sync and rebuild, secrets: mounted at /run/secrets, include: to compose files from other files, and from 2026 pre_start_init_containers for run-once setup steps before the main container.

The commands changed too: docker compose up --build -d --wait builds, detaches, and blocks until every service with a healthcheck is healthy, and docker compose down -v removes volumes.

Compose v1 has been end-of-life since mid-2023, so a CI image still calling docker-compose is running unsupported code.

Land it Drop the version line, spell dependencies with condition: service_healthy, put limits under deploy.resources, and use the space not the hyphen — those four edits modernise most files.

Likely follow-ups
"Why does container_name break --scale, and what do you use instead?"

Because a container name must be unique on the host. With container_name: api, docker compose up --scale api=3 would need three containers all named api and fails at the second.

It also stops two projects from coexisting, since a second checkout of the same repository collides with the first.

Without it, Compose names containers <project>-api-1, -2, and so on, and the service name still resolves in DNS to all replicas, so nothing in the stack needs the fixed name.

The only legitimate use is a container that an external script references by name, and there the better fix is docker compose ps -q api in the script. Same logic applies to fixed host ports, which collide across projects too.

"How exactly do deploy.resources limits behave under plain Compose versus Swarm?"

Under docker compose up, deploy.resources.limits.cpus and memory are translated to the container's cgroup limits, the same as --cpus and --memory, and reservations.memory becomes a soft limit.

Other deploy keys such as replicas, placement, and update_config are Swarm-only and ignored by Compose, with replicas being the exception that Compose honours as a scale. Under docker stack deploy all of them apply, but build and develop are ignored.

So the file is shared but the two runtimes read different subsets. I verify limits took effect with docker inspect --format '{{.HostConfig.Memory}}', because a silently ignored limit is worse than none.

"What does include: solve that extends: did not?"

extends pulls one service definition from another file into the current one, so it is per service and you still list every service yourself.

include pulls in whole Compose files, with their services, networks, and volumes, and each included file is resolved relative to its own directory with its own .env, so a platform team can publish a compose.platform.yaml that brings up the shared observability stack, and a service repository includes it in one line.

Conflicts between included files are errors rather than silent merges, which is safer than -f stacking. As of Aug 2026 include also accepts a remote path, so the shared file can live in a git repository or an OCI registry.

"Is there anything in the old file that still works and is worth keeping?"

Most of it. Service definitions, image, build, environment, volumes, and networks are unchanged; the specification was designed so that a v3 file runs under Compose v2 with warnings rather than errors.

The things I keep are the healthchecks if they exist, the named volumes, and any user-defined networks.

The things I change are mechanical: delete version, convert depends_on lists to the map form with conditions, replace links with nothing, remove container_name, move limits to deploy.resources, and rename to compose.yaml.

docker compose config prints the fully resolved file and warns on deprecated keys, so I run it before and after and diff the two.

Q101 · Scenario. "docker compose up starts the API before Postgres is ready. The API crashes with a connection error, restarts, and works on the second try. The team has a sleep 10 in the entrypoint as a workaround. Fix it properly."

Reveal answer

The real test Whether you know a healthcheck is the right primitive and can write one that means "ready", not "process exists".

Strong answer Diagnosis order:

  1. Symptom: startup race. The database container is "started" the moment its process launches, but Postgres takes several seconds to run recovery and open the socket, and on first boot it initialises a cluster and restarts itself once, which is why sleep 10 is fragile.
  2. Evidence: docker compose ps shows the database with no health column because there is no healthcheck; docker compose logs db shows "database system is ready to accept connections" printed twice on first boot, several seconds after start; the API log shows the refused connection timestamped before the second one.
  3. Cause: depends_on: [db] in list form only orders the start calls. It never waits for readiness because Compose has no idea what readiness means for that image unless you tell it.
  4. Fix: give the database a healthcheck and make the dependency conditional. For Postgres, test: ["CMD-SHELL", "pg_isready -U app -d app"], interval: 5s, timeout: 3s, retries: 10, and start_period: 20s so early failures do not count. Then on the API, depends_on: db: condition: service_healthy. pg_isready checks that the server accepts connections, which is what the API needs. For Redis it is redis-cli ping; for Kafka a kafka-topics.sh --list. Remove the sleep.
  5. Also fix the application: a connection pool such as HikariCP already retries, so set spring.datasource.hikari.initialization-fail-timeout to a positive value like 30000 so the app waits up to 30 seconds for the first connection instead of dying. That covers restarts in production, where nothing orders your containers for you.
  6. Prevention: docker compose up --wait in CI blocks until all healthchecks pass and exits non-zero otherwise, so a broken healthcheck fails the pipeline instead of the next engineer.

Land it Sleep guesses, a healthcheck knows — and the app should tolerate a slow database anyway, because in production nobody runs depends_on for you.

Likely follow-ups
"pg_isready returns healthy but the API still fails on first connect with 'database app does not exist'. Why?"

Because pg_isready checks only that the server accepts connections, and on first boot the official image starts a temporary server, runs the init scripts that create the database and users, then restarts.

During that first temporary phase pg_isready succeeds while the application database does not yet exist.

The fix is a healthcheck that proves the real thing: psql -U app -d app -c 'select 1' as the test, which fails until the database and role exist and the final server is up.

Adding start_period: 20s lets that first phase fail without counting toward retries. The same principle applies elsewhere: check the capability the dependant needs, not merely that a process answers.

"Why fix the application too, if the healthcheck already solves it?"

Because Compose is the only environment that will ever order the start for you. In production the database fails over, a network partition lasts thirty seconds, or the API pod schedules before the database service is reachable, and none of those has a depends_on.

An application that dies on the first failed connection turns every one of those into a crash loop.

Setting Hikari's initialization-fail-timeout to 30 seconds means the pool retries for that long before giving up, and a readiness probe that reports not-ready while the pool is empty keeps traffic away meanwhile. The healthcheck removes the race in development; the retry removes it everywhere.

"How does service_healthy differ from service_started and service_completed_successfully?"

service_started is the old list behaviour: wait until the container is running, which for a database means the process launched. service_healthy waits until the healthcheck has passed, which requires a healthcheck to be defined or Compose errors.

service_completed_successfully waits until the dependency's container has exited with code 0, which is how you run a one-shot migration container before the API: the migration service depends on the database being healthy, and the API depends on the migration completing.

With those three you can express any startup graph without a sleep. Compose also restarts the dependants when a dependency is recreated if you add restart: true on the dependency entry.

"What does the Kafka healthcheck cost and is there something lighter?"

Starting a JVM to run kafka-topics.sh --list every ten seconds costs a second or two of CPU each time and roughly 200 MB of memory transiently, which on a laptop is noticeable.

Lighter checks exist: the apache/kafka image can be probed with a TCP connect to 9092 using bash's /dev/tcp, bash -c 'exec 3<>/dev/tcp/localhost/9092', which proves the listener is up but not that the controller quorum is ready.

A middle ground is kafka-broker-api-versions.sh, which is the same JVM cost.

My compromise is the heavy check with a long interval and start_period: 30s, because a broker that accepts TCP but has not finished quorum election still rejects produces, and that is exactly the false positive the healthcheck exists to prevent.

Q102. "Explain profiles, override files, env_file, and Compose secrets. How do you keep one compose.yaml serving a laptop, CI, and a demo box?"

Reveal answer

Strong answer Four mechanisms, each for one axis of variation. Profiles tag a service as optional: a service with profiles: [tools] does not start unless you run docker compose --profile tools up or set COMPOSE_PROFILES=tools.

That is how a Kafka UI, a mail catcher, or a load generator lives in the file without slowing every start. Override files handle environment shape. Compose automatically merges compose.override.yaml on top of compose.yaml, and you can name others with -f.

The base file holds what is true everywhere: images, networks, volumes, healthchecks. The override, which is git-ignored or per-environment, adds bind mounts and debug ports for laptops, or --scale and resource limits for the demo box.

Merging is by key: lists such as ports are appended, maps such as environment are merged, and a scalar wins.

env_file: .env.local loads key-value pairs into the container environment; note the difference from the top-level .env, which Compose reads for variable substitution in the file itself, so image: app:${TAG:-dev} reads .env, not env_file.

Secrets in Compose are files: a top-level secrets: db_password: file: ./secrets/db_password.txt and a per-service secrets: [db_password] mounts the content at /run/secrets/db_password on a tmpfs, so it never appears in docker inspect or the environment, and the Postgres image reads it via POSTGRES_PASSWORD_FILE.

Compose v2 also supports environment: as a secret source for the value itself.

Putting it together: base file plus a laptop override with watch and mounts, a CI invocation with -f compose.yaml -f compose.ci.yaml --wait, and the demo box with a profile that adds the reverse proxy.

What I would not do is copy the whole file three times, because the copies diverge within a month.

Land it One base file, overrides for shape, profiles for optional services, and secrets as files — each axis of variation has its own mechanism, so no environment needs its own copy.

Likely follow-ups
"Show me the merge rules concretely: what happens to ports and environment in an override?"

For maps such as environment and labels, keys are merged and an override's value replaces the base's for the same key.

For sequences such as ports, expose, and dns, the lists are concatenated, so a base with 8080:8080 plus an override with 9090:8080 publishes both, which surprises people who wanted a replacement.

volumes and devices merge on the container-side path, so an override with the same target replaces the mount. Scalars such as image and command are replaced.

Since Compose 2.24 there is an explicit !override YAML tag to replace a list, and !reset to remove a key inherited from the base. I always run docker compose config to see the result before trusting a merge.

"How does variable substitution interact with env_file — where does ${DB_HOST} get its value?"

From the shell environment first, then from the .env file in the project directory, and never from env_file. Substitution happens when Compose parses the YAML, before any container exists, and at that point it knows only the process environment and .env.

env_file is a per-service instruction that loads variables into the container at run time, so its contents are invisible to the ${...} syntax in the file itself.

The precedence for what a container sees is: environment: beats env_file:, and within environment a bare DB_HOST with no value passes through the host's value. --env-file other.env on the command line changes which file feeds substitution.

"What would a CI-specific override look like?"

Small and mostly subtractive.

It removes the bind mounts and develop.watch by not including the laptop override, sets image: to the freshly built tag with ${IMAGE_TAG} from the pipeline environment, publishes nothing, since tests run on the project network from a test container, and adds deploy.resources.limits to keep runners predictable.

The invocation is docker compose -f compose.yaml -f compose.ci.yaml up --wait --quiet-pull, then docker compose run --rm tests for a service on the test profile, then down -v because CI data is disposable.

--wait fails the job if any healthcheck never passes, which makes a broken dependency a red build instead of a flaky test.

"Are Compose secrets actually secure, or just tidier?"

They are tidier and moderately more secure, and I say both. The file is mounted on a tmpfs inside the container, so it is not in the image, not in docker inspect, and not inherited by child processes.

But the source file sits on the developer's disk in plain text, anyone with socket access can docker exec cat it, and there is no rotation or audit. For a laptop that is fine, since the values are throwaway.

For a demo box they are acceptable if the file has mode 0400 and the box has no other users.

For production they are not the answer; the pattern is the same file path fed by a secrets manager through workload identity, so the application code never changes between environments.

Q103 · Design. "Design a local development environment with Compose for a Spring Boot API plus Postgres, Redis, and Kafka, with hot reload of the Java code and a startup that never races."

Reveal answer

Strong answer Requirements: one command to a working stack, sub-five-second feedback on a code change, no port collisions with other projects, and the same images as production.

Assumptions: Compose v2.4x, JDK 21 image with Spring Boot DevTools, single-node Kafka in KRaft mode so there is no ZooKeeper. The design: four services on the project network, all three stores with healthchecks, and the API depending on all of them with condition: service_healthy.

Hot reload uses develop.watch: a sync action copies compiled classes from build/classes into the container, where DevTools notices the change and restarts the Spring context in about two seconds, and a rebuild action fires only when build.gradle changes.

The IDE keeps compiling on save, so no Java source is mounted at all, which sidesteps the Docker Desktop file-sharing cost.

compose.yaml
services:
  api:
    build: .
    ports: ["127.0.0.1:8080:8080"]
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/app
      SPRING_DATA_REDIS_HOST: cache
      SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092
    depends_on:
      db: { condition: service_healthy }
      cache: { condition: service_healthy }
      kafka: { condition: service_healthy }
    develop:
      watch:
        - action: sync
          path: ./build/classes
          target: /app/classes
        - action: rebuild
          path: build.gradle
    deploy:
      resources:
        limits: { memory: 1g }
  db:
    image: postgres:17
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 5s
      timeout: 3s
      retries: 10
  cache:
    image: redis:7
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 10
  kafka:
    image: apache/kafka:3.9.0
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    healthcheck:
      test: ["CMD-SHELL", "/opt/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list"]
      interval: 10s
      timeout: 5s
      retries: 12
      start_period: 30s
volumes:
  pgdata: {}

You run it with docker compose up --build --watch. Trade-offs: DevTools restarts are slower than JRebel-style class swapping but free and reliable; the Kafka healthcheck is heavy, so it runs every ten seconds with a thirty-second grace period; the API binds 127.0.0.1 only, so a second project on the same laptop uses a different host port through an override file. What I would not do: mount the whole repository and run Gradle inside the container, because Gradle's daemon and caches are far faster on the host and the mount would be the slowest part of the loop; and I would not use network_mode: host to "simplify" ports, since it breaks on Docker Desktop and removes the per-project isolation that lets two stacks coexist.

Land it Compile on the host, sync classes in, healthcheck every dependency, and bind to loopback — that is a dev loop that starts in one command and reloads in two seconds without a single sleep.

Likely follow-ups
"A developer wants to attach the IDE debugger to the API. What changes?"

Two lines in the laptop override. The JVM gets JAVA_TOOL_OPTIONS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005, and the service publishes 127.0.0.1:5005:5005. Binding the debug agent to * inside the container is required, since 127.0.0.1 would be unreachable through the DNAT, and publishing on loopback keeps it host-only.

In the IDE a remote debug configuration attaches to localhost:5005.

With DevTools restarts, the debugger reconnects automatically in IntelliJ. I put it in the override rather than the base so the CI and demo configurations never expose a debug port, and I would never set suspend=y in a Compose file because the healthcheck then fails while the JVM waits.

"A second developer complains that two projects fight over port 8080. Fix it without editing the shared file."

The base file already binds 127.0.0.1:8080:8080, so the developer creates a git-ignored compose.override.yaml, or sets COMPOSE_FILE to include a personal file, with ports: !override ["127.0.0.1:8081:8080"]. The !override tag replaces the list instead of appending, which is what plain merging would do.

Better still, the base uses a variable, "127.0.0.1:${API_PORT:-8080}:8080", and the developer sets API_PORT=8081 in a local .env. Compose also names networks and containers per project directory, so nothing else collides; only host ports are global.

I would set the variable form in the shared file once so nobody needs an override for this.

"What would you cut if you had to ship a first version this afternoon?"

Kafka. It is the heaviest service, the slowest to become healthy, and most features do not need it on day one; I would put it on a profiles: [messaging] profile so it starts only when asked.

I would keep the healthchecks and depends_on conditions for Postgres and Redis, because they are five lines and remove the race. I would keep develop.watch because it is the whole point of the environment.

I would drop the memory limit on the API, since a laptop is not a shared host. And I would ship the API with build: . and no cache tuning; a slow first build is acceptable, a racing startup is not.

"How do you keep this Compose file from drifting away from production?"

By making the image the shared artifact and the configuration the only difference. The API is built from the same Dockerfile that CI uses, so what runs locally is the production image plus a synced classes directory.

The Postgres, Redis, and Kafka image tags come from a single .env file that a bot bumps alongside the production version pins, so a version upgrade in production is a pull request that changes both. Environment variable names are identical to production's, with only values differing.

And the pipeline runs the same Compose file in CI, so if it breaks it breaks visibly. What I avoid is any code path that checks "am I in Compose", because that is the drift made permanent.

Q104 · Design. "Design how a Java service exposes liveness, readiness, and startup signals so that Compose, Docker's own HEALTHCHECK, and Kubernetes can all use them correctly."

Reveal answer

Strong answer Requirements: three distinct questions answered by three distinct endpoints. Liveness asks "should this process be killed and restarted?", readiness asks "should traffic be sent here right now?", and startup asks "has it finished booting yet?".

Mixing them is the classic mistake: if liveness checks the database, a database outage makes every pod restart in a loop.

The design with Spring Boot Actuator: management.endpoint.health.probes.enabled=true exposes /actuator/health/liveness, backed only by the application's own state, and /actuator/health/readiness, which includes the database and any downstream that a request genuinely needs.

I serve them on a separate management port, management.server.port=8081, not published outside the container, so probes never compete with user traffic and are not internet-reachable.

The image gets HEALTHCHECK --interval=10s --timeout=3s --start-period=40s --retries=3 CMD wget -qO- http://127.0.0.1:8081/actuator/health/readiness || exit 1, using wget from a minimal base or a tiny Java or Go health binary on distroless.

Docker only has one health concept, so readiness is the right one to wire, because Compose's service_healthy means "safe to depend on".

In Kubernetes, described in E10, the same two URLs become livenessProbe and readinessProbe, and a startupProbe with failureThreshold: 30 and periodSeconds: 2 covers a 60-second JVM warm-up without loosening the liveness probe.

Readiness also flips to down during graceful shutdown: with server.shutdown=graceful Spring stops accepting requests, reports not-ready, and drains in-flight work for up to spring.lifecycle.timeout-per-shutdown-phase.

Trade-offs: a readiness check that includes the database will take the whole service out of rotation during a database failover, which is usually right for a service that cannot do anything without it, and wrong for one that can serve cached reads; make that choice explicit per service.

What I would not do: return 200 from /health unconditionally, because that turns every probe into a no-op and the orchestrator into a bystander.

Land it Liveness is "am I stuck", readiness is "can I serve", startup is "give me time" — wire readiness to Docker's single healthcheck and keep the database out of liveness or you will restart your way through every incident.

Likely follow-ups
"Why wire readiness to the Docker healthcheck rather than liveness?"

Because of what each consumer does with it. Docker's health state does nothing on its own; it is read by Compose's service_healthy, by Swarm, and by humans running docker ps. All of those want to know "is it safe to send work here", which is readiness.

If I wired liveness, Compose would start the API as soon as the process was alive and before the database connection existed, which is the race I was trying to remove. In Kubernetes the two are separate probes and I wire each to its endpoint.

The one place to be careful is a restart policy driven by health, which Docker does not have but Swarm and some wrappers do; there, a readiness check that fails during a database outage would cause restarts, and a liveness check is correct.

"The readiness check includes the database and a failover took every instance out for two minutes. Was that right?"

It was correct for a service that cannot do anything useful without the database, because the alternative is accepting requests and returning 500s, which also fails the user but additionally hides the cause from the load balancer.

It was wrong if the service could have served cached reads or a degraded mode. The design choice is per dependency: Spring's readiness group can include the datasource health indicator or exclude it via management.endpoint.health.group.readiness.include.

For a service with a degraded mode I would exclude the database from readiness, mark the dependency status in a separate endpoint, and let the circuit breaker in the code handle the outage.

The rule is that readiness should reflect whether a request sent now would succeed.

"How do you keep the probe from lying during a slow startup or a GC pause?"

Slow startup is the startup probe's job: in Kubernetes a startupProbe with a generous failure threshold suspends liveness until the first success, and in Docker the --start-period does the same.

A long GC pause is different: the probe times out, and if liveness has failureThreshold: 3 at ten-second intervals, a single 30-second pause restarts a healthy pod.

I set the liveness timeout to a few seconds but the threshold high enough that only sustained unresponsiveness triggers, and I serve the probes on the management port from a separate thread pool so they do not queue behind user requests.

A probe that shares the request thread pool measures queue depth, not health.

"Distroless has no wget. How does the Docker HEALTHCHECK run?"

The healthcheck command runs inside the container, so it needs a binary the image has. On distroless Java there is no shell and no curl, so the options are: compile a tiny Go static binary that performs the HTTP GET and exit codes accordingly, copied in at /app/healthcheck; use the JVM itself with a small class and the java binary, which costs a JVM start per probe and is too heavy; or omit the Docker HEALTHCHECK and rely on the orchestrator's HTTP probe, which Kubernetes performs from the kubelet with no binary needed. In Compose I want the healthcheck for service_healthy, so the Go binary is what I ship; it is about 2 MB and needs no libc.

Q105. "Compare Docker's restart policies. How does restart: always interact with a crash loop, a daemon restart, and a deliberate docker stop?"

Reveal answer

The real test Whether you know that a restart policy makes a crash invisible and that Docker never restarts on a failed healthcheck.

Strong answer There are four policies, set with --restart or the restart: key in Compose. no is the default; the container stays exited.

on-failure[:N] restarts only when the process exits with a non-zero code, up to N attempts, so a clean exit 0 from a batch job is left alone.

always restarts regardless of exit code, and also brings the container back when the Docker daemon itself restarts, for example after a host reboot.

unless-stopped behaves like always except that a container you stopped by hand with docker stop stays stopped across a daemon restart, which is almost always what an operator wants.

On a crash loop, both always and on-failure use exponential back-off starting at 100 ms and doubling to a cap, and docker ps shows Restarting (1) 12 seconds ago with the exit code in parentheses.

The important nuance is that a restart policy hides bugs: a service that crashes every 40 seconds and restarts looks "up" to anyone who only checks that the container exists, and its healthcheck resets on each restart, so docker compose up --wait can even report it healthy for a moment.

Read the exit code: 137 is SIGKILL, usually the out-of-memory killer, 143 is SIGTERM from a stop, and 1 is the application's own failure.

docker stop sends SIGTERM, waits ten seconds by default or the --stop-timeout you set, then SIGKILL, and a manual stop always wins over the policy until the next daemon restart for always.

A restart policy is also not a healthcheck: Docker never restarts a container just because its healthcheck fails; that behaviour is what Kubernetes liveness probes add.

In a Compose file for development I use unless-stopped for stores and no policy for the application, so a crash stays visible in docker compose ps instead of being papered over.

Land it unless-stopped for things that should survive a reboot, on-failure for jobs, and remember that a restarting container is a crashing container with better makeup — read the exit code.

Likely follow-ups
"What is the back-off cap and how do you see the restart history?"

The delay starts at 100 milliseconds and doubles on each consecutive failure, capped at one minute, and resets to the start once the container stays up for ten seconds.

docker inspect --format '{{.RestartCount}} {{.State.ExitCode}} {{.State.FinishedAt}}' shows how many restarts and the last exit, and docker events --filter container=name --since 1h replays each die and start with timestamps so I can see the loop's rhythm.

docker logs --tail 100 shows the last attempt's output; earlier attempts' logs are in the same file, since the json-file driver appends across restarts. For on-failure:5, after the fifth failure the container stays exited and RestartCount stops at 5.

"How does live-restore interact with restart policies?"

"live-restore": true in daemon.json lets containers keep running while the daemon itself is stopped or upgraded, because the shim processes hold them independently of dockerd. With it, a daemon restart does not stop containers, so always never gets to act.

Without it, a daemon restart stops every container, and on start-up the daemon restarts the ones with always or unless-stopped in the order it finds them, which is not dependency order.

That is why a stack with restart policies can come back with the API up before the database and needs the application-level retry. Live-restore has limits: it does not survive a host reboot, and containers started without it cannot be adopted after the fact.

"How do you make a failed healthcheck actually restart a container without Kubernetes?"

With a small supervisor outside Docker, since the engine will not do it. The common choices are autoheal, a container that watches docker events for health_status: unhealthy and restarts the culprit, or a systemd timer running docker ps --filter health=unhealthy -q | xargs -r docker restart.

Both need the Docker socket, which is root-equivalent, so I run them via a socket proxy that allows only the container list and restart endpoints. Swarm does it natively: an unhealthy task is replaced.

The reason Docker itself does not is philosophical, since the healthcheck was designed as a signal for orchestrators, and the reason to be careful is that restarting on a database outage produces the same loop Kubernetes liveness misuse does.

"Why not restart: always on everything in production on a single host?"

Because it hides failures and fights operators. A service crashing every minute under always shows as running in every check that looks at container existence, and the restart count climbs silently unless someone alerts on it.

It also resurrects containers you stopped deliberately whenever the daemon restarts, which during an incident is the opposite of what you want; unless-stopped exists to fix exactly that.

My rule on a single host is unless-stopped for the stores and long-running services, an alert on RestartCount increasing, and a deploy script that recreates containers rather than relying on restarts to pick up changes. For batch jobs, on-failure:3 and a log of the last failure.

Q106 · Design. "Your team of thirty engineers runs containers on shared build and staging hosts. Design a standard docker run wrapper or policy so that the defaults are safe without slowing anyone down."

Reveal answer

Strong answer Requirements: safe defaults, no host takeover by accident, per-container resource ceilings, and an escape hatch that leaves an audit trail. Assumptions: Linux hosts, Docker Engine 27 or newer, engineers who mostly run Compose.

The design has three layers so that the wrapper is a convenience and not the only line of defence.

Layer one is daemon configuration in /etc/docker/daemon.json, which applies to everything: "userns-remap": "default" so root in a container maps to an unprivileged host uid; "no-new-privileges": true so setuid binaries cannot escalate; "ip": "127.0.0.1" so published ports are host-local unless stated; "default-ulimits" with a sane nofile; and "live-restore": true so daemon upgrades do not kill workloads.

Layer two is a small wrapper script, drun, committed to the platform repository, that expands to docker run --rm --cap-drop=ALL --read-only --tmpfs /tmp --pids-limit 512 --memory 2g --cpus 2 --security-opt seccomp=default.json plus whatever the caller passed, and refuses --privileged, -v /var/run/docker.sock, and bind mounts outside $HOME and the workspace unless DRUN_UNSAFE=reason is set, in which case it logs the reason and the user to syslog.

The same defaults ship as a Compose fragment engineers pull in with include:, so the two paths agree.

Layer three is enforcement that does not depend on the wrapper: the Docker socket is owned by a group that only the CI runner and the wrapper's sudo rule can use, and a nightly job lists containers that violate the policy with docker inspect and posts them.

Trade-offs: user namespaces break a handful of images that need to chown volumes, so the wrapper documents --userns=host as an allowed exception for those; the read-only root filesystem needs --tmpfs for any path the image writes, which surfaces sloppy images early.

What I would not do: block docker entirely and force everything through a ticket, because engineers then install their own Docker in a VM and the policy protects nothing.

Land it Put the safety in daemon.json where nobody can forget it, put the convenience in a wrapper everyone wants to use, and make the exception path louder than the default rather than impossible.

Likely follow-ups
"userns-remap breaks an image that chowns its volume. What is the exact failure and fix?"

With remapping, container root is host uid 100000, and a named volume Docker creates is owned by 100000 too, so a chown to 999 inside the container maps to host 100999 and works.

The failure appears with bind mounts: a host directory owned by the real uid 1000 is seen by the remapped container as owned by an unmapped id, so it is nobody and unwritable, and a chown fails with "Invalid argument" because 999 is outside the container's mapped range.

The fixes are to use a named volume instead of a bind mount, to pre-chown the host directory to the subordinate range, chown 100999 /srv/data, or to run that one container with --userns=host as a documented exception.

The wrapper offers the last as an allowed escape hatch that logs the reason.

"How do you stop people from just using DRUN_UNSAFE for everything?"

By making the escape visible and accountable rather than convenient. Every DRUN_UNSAFE invocation logs the user, the reason string, and the full command to syslog, which ships to the central log store, and a weekly report lists who used it and why.

A reason is mandatory, so it cannot be an empty flag. For the genuinely common needs, such as binding a low port or a specific device, I add first-class flags to the wrapper so people do not reach for the unsafe switch at all.

And the socket permissions mean that even bypassing the wrapper with raw docker is limited to the CI runner and the sudo rule, so the wrapper is a convenience over a floor set elsewhere, not the only guard.

"What would you cut from this design for a five-person startup?"

The wrapper script and the nightly audit.

For five people on trusted machines, the value is in the two things that cost nothing: the daemon.json defaults, especially no-new-privileges, userns-remap, and loopback publishing, which protect every container without anyone changing their commands; and a shared Compose fragment with the hardening keys that new services include.

I would skip the sudo-gated socket and the syslog reporting, because with five trusted people the overhead outweighs the risk. I would keep the digest pinning and the resource limits, since a runaway container hurting a shared build box is the failure a startup actually hits.

The rule scales: put safety in defaults first, add enforcement only when headcount makes trust insufficient.

"How do you roll daemon.json changes across thirty hosts without an outage?"

Through the config-management tool that already owns the hosts, Ansible or similar, applied in waves.

A daemon.json change needs a systemctl reload docker or restart to take effect, and a restart stops containers unless live-restore is on, so I enable live-restore first in its own change, verify it, then apply the rest with reload where possible.

Options such as userns-remap cannot be reloaded and require a restart plus re-pulling images into the remapped storage, so I schedule those in a window and drain the host first.

I apply to a canary host, run the smoke suite, then ten percent, then the rest, and I keep the previous daemon.json so a rollback is one revert and one reload. The audit job confirms the effective config with docker info afterwards.

Drill · Security & hardening

This group tests whether you understand that a container is a Linux process with some doors closed — which doors, who can open them, and what an attacker does with the ones you left ajar.

Q107. "Why is --privileged effectively root on the host, and why is mounting /var/run/docker.sock into a container just as bad?"

Reveal answer

The real test Whether you can name the concrete escape, not just say "it's dangerous".

Strong answer A normal container is root inside its namespaces but with three restraints: a reduced set of capabilities, which are the individual slices of root power such as "bind low ports" or "mount filesystems"; a seccomp filter, which is a list of system calls the process may make; and no access to host devices.

--privileged removes all three. The container gets every capability including CAP_SYS_ADMIN, the seccomp and AppArmor profiles are switched off, and every device in /dev is exposed.

The escape is then mechanical: mount /dev/sda1 /mnt mounts the host's root disk, chroot /mnt and you are editing the host's /etc/shadow or dropping an SSH key.

There are also cgroup-based escapes that need only CAP_SYS_ADMIN and a writable cgroup, which is why that single capability is the one to fear. The Docker socket is the same result by a different route.

The socket is the daemon's API, and the daemon runs as root on the host. Any process that can write to /var/run/docker.sock can say docker run --privileged -v /:/host alpine chroot /host, and there is no authentication on a Unix socket beyond file permissions.

Tools that legitimately need it, such as a CI runner or a log collector, therefore have to be treated as root on the host, and the modern answer is to give them a proxy such as docker-socket-proxy that allows only the API calls they need, or to run the daemon rootless so that even the daemon is not root.

In short, --privileged hands over the host through the kernel, and the socket hands it over through the daemon.

Land it Say "privileged means mount the host disk and chroot into it, and the socket means run a privileged container on demand" — both are root on the host with one extra command.

Likely follow-ups
"A CI runner genuinely needs to build images. How do you give it that without the socket or privileged?"

By moving the build off the daemon.

The runner runs the buildx client with no local daemon and connects over TLS to a remote BuildKit pool on hardened hosts running rootless, so the job never holds host root and the untrusted pull-request code cannot reach a daemon at all.

Alternatively Buildah builds rootless inside the unprivileged runner using user namespaces, with no daemon and no socket. If the runner must talk to a daemon for some legacy step, it gets a socket proxy allowing only the specific endpoints, never the raw socket.

The principle is that build capability and host-root capability are separable, and every 2026 tool lets me keep them apart.

"A logging agent needs the socket to read container metadata. Is that acceptable?"

Only through a filtered proxy. The agent needs read endpoints, GET /containers/json and GET /containers/{id}/json and the events stream, and nothing that starts containers.

docker-socket-proxy is a small container that mounts the real socket and exposes a network endpoint permitting only the endpoints you set to 1, so the agent gets CONTAINERS=1 EVENTS=1 and POST=0, and it is on an internal network with only the agent.

That turns "root on the host" into "can list containers". Even better where available is reading the metadata from the orchestrator's API with a scoped token, or from the container runtime's read-only interface, so the Docker socket is not shared at all.

"Does rootless Docker make the socket safe to mount?"

It makes it much less catastrophic, not safe.

With rootless Docker the daemon runs as your user inside a user namespace, so a container that gains socket access and starts a privileged container is privileged only within that user namespace and maps to your unprivileged uid on the host, not to real root.

It cannot mount the host disk as root or read another user's files. But it can still do anything your user can, including reading your files and using your credentials, and it can start containers that consume your resources.

So mounting the socket in rootless mode is the difference between "compromise the host" and "compromise this user", which is a real improvement but still means I only share it through a proxy with the minimum endpoints.

"Show the exact escape from --privileged so I know you have done it."

Inside a privileged container, fdisk -l lists the host disks because all devices are exposed, then mkdir /m && mount /dev/sda1 /m mounts the host root, and echo 'ssh-ed25519 ...' >> /m/root/.ssh/authorized_keys plants a key, or I chroot /m and edit /etc/shadow directly.

A subtler route needs only CAP_SYS_ADMIN and a writable cgroup: I set the cgroup's release_agent to a script on the host and trigger it by emptying the cgroup, and the kernel runs my script as root on the host.

Both are a handful of commands, which is why --privileged and CAP_SYS_ADMIN are treated as host root rather than as a strong sandbox.

Q108 · Scenario. "Audit logs show a developer ran docker run -v /:/host -it alpine on a shared build host and opened /host/etc/shadow. Treat it as an incident: what happened, what is exposed, and what changes?"

Reveal answer

Strong answer In diagnosis order:

  1. Symptom: a bind mount of the host root into a container running as uid 0. Inside the container the process is root, and a bind mount keeps host file ownership, so root in the container reads and writes every host file as root. This is not an exploit; it is the documented behaviour of bind mounts without user namespaces. The developer needed no sudo, only membership of the docker group, which is why that group is equivalent to root.
  2. Evidence: journalctl -u docker and the daemon's audit events show the run call with its mounts; docker ps -a may still list the container; on the host, ausearch or file access times on /etc/shadow, and the shell history inside the container if it was not --rm, show what was read or changed.
  3. Exposure: password hashes for every local account, any SSH host keys, any cloud credentials in /root or /home, CI secrets on disk, and the ability to have planted a backdoor. Treat the host as compromised regardless of intent, rotate every secret that touched it, and rebuild it from an image rather than cleaning it.
  4. Fix and prevention, three items. First, enable userns-remap in daemon.json: container root becomes host uid 100000-something, and /host/etc/shadow becomes unreadable because the file is owned by real uid 0. Second, remove interactive users from the docker group; give them rootless Docker for personal work and let only the CI runner talk to the system daemon. Third, an admission rule, whether the wrapper from the previous question or an authorization plugin, that rejects bind mounts outside an allow-list.
  5. Process: a blameless write-up. The developer used a documented feature on a host that was configured to allow it; the failing was the configuration.

Land it Membership of the docker group is root, and -v /:/host is just the shortest proof — user namespaces and taking people out of that group are the fixes, not a stern email.

Likely follow-ups
"The container was run with --rm, so it is gone. What evidence survives?"

Plenty, because the container was the least of it. The host's audit log, if auditd was watching /etc/shadow, records the read with the process and timestamp; ausearch -f /etc/shadow -ts recent pulls it.

The Docker daemon logs the run API call with its mounts in journalctl -u docker, so the command line and the -v /:/host are recoverable even after --rm. File access times on the host, stat /etc/shadow, show when it was read unless noatime is set.

Shell history is gone with the container, but the developer's own shell history on the host shows the docker run they typed. And the image they used is still in the local store or the registry pull log. I treat the mounted files as read and act on that.

"How do you decide whether to rebuild the host or clean it?"

By what the intruder could have written, not what they say they did.

With root-in-container on a bind-mounted host root, they could have added a user, planted a cron job, replaced a binary, or dropped an SSH key, and proving the absence of all of those is harder than rebuilding.

So my default is to rebuild the host from a known-good image and restore data from backups, treating anything the container could reach as compromised.

I would clean rather than rebuild only if the audit log positively shows the access was read-only and nothing was written, which on a shared build host I rarely trust. Rotating every credential the host held is required either way, because reads cannot be undone.

"The developer says it was accidental and they just fat-fingered a path. Does that change the response?"

It changes the write-up, not the containment. Intent does not un-read a password hash, so the credential rotation and the host rebuild proceed regardless, and the incident is handled blameless because the failing was a host configured to permit it, not a person.

What intent changes is the follow-up: an accidental case tells me the guardrails are missing, so the fixes, userns-remap, removing users from the docker group, and a bind-mount allow-list, are the real remediation.

A deliberate case adds an access-review and possibly HR steps in parallel, but the technical response is identical, because a system that depends on everyone being careful is the actual vulnerability.

"What single control would have prevented this specific command?"

userns-remap on the daemon, because it maps container root to an unprivileged host uid, so /host/etc/shadow mounted in would be owned by real uid 0 and unreadable by the container's remapped root, and the read would fail with permission denied.

It is one line in daemon.json and a daemon restart. Removing interactive users from the docker group prevents the command from being runnable at all, which is stronger but affects everyone's workflow. A bind-mount allow-list in an authorization plugin blocks -v /:/host specifically.

If I could pick one for immediate effect with least disruption, it is userns-remap; for the durable fix, it is that plus taking people out of the docker group and giving them rootless.

Q109 · Scenario. "A hardened image runs as uid 1000 and the app now fails with Permission denied binding port 80. The team's proposal is to go back to root. What are the alternatives and which do you pick?"

Reveal answer

Strong answer Diagnosis order:

  1. Symptom: bind: permission denied on a port below 1024. On Linux, ports 1 to 1023 are privileged and by default only a process with the CAP_NET_BIND_SERVICE capability may bind them. The app lost that when it stopped being root.
  2. Evidence: docker exec app id confirms uid 1000; docker inspect app --format '{{.HostConfig.CapAdd}}' shows no capabilities added; docker exec app cat /proc/sys/net/ipv4/ip_unprivileged_port_start tells you where the privileged range starts inside this container.
  3. Options, best first. Option one: do not bind 80 at all. Have the app listen on 8080 as an unprivileged user and publish with -p 80:8080; the DNAT rule does the translation and no privilege is needed anywhere. This is the right answer for almost every service and the reason this incident usually should not exist. Option two: the sysctl. Docker Engine 20.10 and later already set net.ipv4.ip_unprivileged_port_start=0 inside new containers, so on a current engine uid 1000 can bind 80 out of the box; if the daemon is old or the value was overridden, --sysctl net.ipv4.ip_unprivileged_port_start=0 restores it with zero capabilities. Option three: --cap-drop=ALL --cap-add=NET_BIND_SERVICE, which grants exactly the one slice of root needed. Note that for a plain binary the capability must also be permitted for a non-root process, which works with Docker's ambient capability handling but may need setcap on the binary in older setups. Option four, going back to root, is the one I reject: it hands the app every capability in the default set and makes any code-execution bug a container-root bug.
  4. Fix: I pick option one, and if the port really must be 80 inside for a legacy reason, option two.
  5. Prevention: the base image template documents "listen above 1024, publish whatever you like", so the question never comes up.

Land it Low ports are a host convention, not an application need — listen on 8080 and publish 80, and if you must, add one capability rather than all of them.

Likely follow-ups
"Option two sets ip_unprivileged_port_start=0. Does that weaken security?"

Barely, and only inside that container's namespace. The privileged-port convention exists so that on a multi-user host an ordinary user cannot run a fake service on port 80 and impersonate the system's web server.

Inside a container the network namespace is already the isolation boundary, there are no other users to protect, and the port maps to whatever you publish anyway. Docker Engine 20.10 and later set the sysctl to 0 in new containers for exactly this reason.

So allowing an unprivileged process to bind 80 inside its own namespace grants no capability that matters. The thing I would not do is lower the value on the host itself, which would let any host user bind low ports and is a real change.

"You picked option one, listen on 8080 and publish 80. What if it sits behind a load balancer that only forwards to 80?"

Then the load balancer's target port is configuration, not a law, and I point it at 8080.

Cloud load balancers, Kubernetes Services, and reverse proxies all let you set the target port independently of the listener port, so the balancer listens on 443 to the world and forwards to 8080 on the container. The container never needs a low port.

If it is a legacy hardware balancer hard-wired to 80, I publish the container's 8080 on the host's 80 with -p 80:8080, and the host's 80 is bound by the daemon, which runs as root, so no application privilege is involved.

The application binding a high port is the invariant; everything downstream is a mapping.

"The binary is a compiled Go server, not a shell. Does NET_BIND_SERVICE alone work?"

With Docker's ambient capability handling, yes: --cap-add=NET_BIND_SERVICE adds the capability to the container's ambient set, and a non-root process inherits it, so the Go server binds 80 without being root and without file capabilities. In some older or more locked-down setups the capability must also be present in the binary's permitted set, set at build with setcap 'cap_net_bind_service=+ep' /app/server, because a non-root process only gains a capability it is permitted to hold. Since this is fiddly and easy to get wrong on an upgrade, I still prefer listening high and publishing low, and reach for the capability only when a legacy protocol genuinely requires the process to see port 80 itself.

"Going back to root is rejected — but what if the team insists for expedience?"

I would show the cost concretely: as root the container holds the full default capability set, so a remote code execution in the app is immediately container-root with the ability to write anywhere the filesystem allows, install tools, and probe the host, whereas as uid 1000 with dropped capabilities the same bug is contained.

Then I offer the one-line alternatives that cost nothing, the sysctl or listening high, so expedience is satisfied without the regression.

If they still insist, I make it a written exception with an owner and an expiry and an image-scan gate that flags the missing USER, so the decision is visible and revisited rather than silent.

The goal is to make the safe path the easy path, which here it genuinely is.

Q110 · Scenario. "A penetration test report says: 'All containers run as root, several have CAP_SYS_ADMIN, and one mounts the Docker socket.' Prioritise the findings and describe the remediation for each."

Reveal answer

The real test Whether you rank by "host root today" versus "host root after the next bug", not by how scary the words sound.

Strong answer In order of severity:

  1. Evidence first: docker ps -q | xargs docker inspect --format '{{.Name}} user={{.Config.User}} caps={{.HostConfig.CapAdd}} priv={{.HostConfig.Privileged}} binds={{.HostConfig.Binds}}' gives the whole picture in one command, and I would run it before agreeing with the report.
  2. Highest: the Docker socket mount. That container is root on the host today, as Q107 explains. Remediation: identify why it needs the socket, replace with a filtered proxy such as docker-socket-proxy exposing only the endpoints used, for example GET /containers for a monitoring agent, and put the container on a network with nothing else. If it is a CI runner, move it to a dedicated host or to rootless mode.
  3. Second: CAP_SYS_ADMIN. This capability is the catch-all that covers mounting, namespace tricks, and several known cgroup escapes, and it is not in Docker's default set, so someone added it. Usually the reason is a FUSE mount or a tool that wanted to change a sysctl. Remediation: find the real need and grant the narrow thing instead, for example --device /dev/fuse with the SYS_ADMIN only on the one sidecar that mounts, or set the sysctl with --sysctl at start. Then --cap-drop=ALL and add back only what remains.
  4. Third: running as root. On its own, root inside a container with the default capabilities and seccomp profile is contained, but it makes every other misconfiguration exploitable and lets a compromised app write anywhere the image is writable. Remediation is a USER 10001:10001 line in each Dockerfile after fixing file ownership with COPY --chown, plus userns-remap at the daemon so even the stragglers are not host root. Java and Node apps need no changes for this beyond writable paths, which --tmpfs supplies.
  5. Prevention: an image-scanning gate that fails the build when USER is missing, and a runtime policy that rejects CapAdd and socket binds without an approved exception label.

Land it Socket first, SYS_ADMIN second, root third — because the first two are host root today and the third is the thing that makes tomorrow's bug into host root.

Likely follow-ups
"You replaced the socket mount with a proxy but the tool now fails. How do you find the missing endpoint?"

By reading the tool's requests. I set the proxy to log denied calls, or run it with everything denied and watch which endpoint returns 403 first, then enable exactly that one.

Most agents need GET /containers/json, GET /containers/{id}/json, and the events stream, and nothing more; a metrics agent may also need GET /containers/{id}/stats. I enable them one at a time until the tool works, then stop, so the final allow-list is the minimum.

If the tool needs a POST endpoint such as exec, that is a red flag I investigate rather than grant, because exec through the proxy is close to the socket access I was removing.

The audit is the log of which endpoints I turned on and why.

"CAP_SYS_ADMIN was added for a FUSE mount. What is the narrow replacement?"

The FUSE case needs the /dev/fuse device and the ability to mount, not the whole of SYS_ADMIN on the main container.

I move the mount into a dedicated sidecar with --device /dev/fuse and only that sidecar gets the narrow capability, while the application container mounts the resulting filesystem through a shared mount namespace or a shared volume and holds no extra capability.

On newer kernels, unprivileged FUSE mounts inside a user namespace remove the need for SYS_ADMIN entirely. If the mount is optional, I question whether it is needed at all.

The general move is: find the one operation that wanted the capability, isolate it, and grant the smallest thing that enables it, then --cap-drop=ALL everywhere else.

"How do you prioritise these three across forty services without stopping everything?"

By exposure and by blast radius. The socket mount is one container and host-root today, so I fix that first and it is a contained change to one service.

SYS_ADMIN is a few services and also close to host-root, so it is second, handled case by case since each has a reason.

Root-with-default-capabilities is every service but individually contained, so it is a fleet-wide campaign done through the base-image template and a scanning gate rather than a rush.

I would deploy an admission or nightly-audit rule immediately that blocks new occurrences of the first two, freezing the problem, then burn down the existing list by severity. That way the worst is fixed in a day and the long tail does not regrow.

"After remediation, how do you prove to the pen-test firm it is fixed?"

With the same one-line inventory they would run, captured as evidence: docker ps -q | xargs docker inspect --format '{{.Name}} user={{.Config.User}} caps={{.HostConfig.CapAdd}} priv={{.HostConfig.Privileged}} binds={{.HostConfig.Binds}}' across every host, showing no privileged containers, no socket binds, non-root users, and empty CapAdd except the documented exceptions.

I add the admission policy configuration and a screenshot of it rejecting a bad manifest, the nightly audit job and its last clean run, and the exception register with owners and expiries. Then I invite a re-test of the specific findings.

Proof is the current state plus the control that keeps it that way, because a one-time fix without enforcement drifts back within a quarter.

Q111. "Explain the default seccomp profile, AppArmor, no-new-privileges, and user namespaces. Which layer catches which kind of attack?"

Reveal answer

The real test Whether you can say what each fence is made of and name the attack it stops, because they are not interchangeable.

Strong answer These are four independent fences, and a senior answer says what each one is made of. Seccomp is a kernel feature that filters system calls, the requests a process makes to the kernel.

Docker's default profile allows roughly 300 of the 350-plus calls and blocks the rest, including mount, reboot, kexec_load, and ptrace of other processes.

It catches kernel-exploit attempts that need an obscure syscall, and you tighten it further with --security-opt seccomp=profile.json generated from a trace of what the app actually calls.

AppArmor, and on Red Hat systems SELinux, is mandatory access control: a policy that says which files, paths, and capabilities a process may touch, enforced regardless of file permissions. Docker's default docker-default AppArmor profile denies writes to /proc/sys, /sys, and similar host-facing paths.

It catches a process that has root inside the container from reaching for host interfaces through the filesystem.

no-new-privileges, set with --security-opt no-new-privileges, is a single process flag that stops execve from ever granting more privilege, so setuid binaries like sudo or ping and file capabilities stop working. It catches privilege escalation inside the container after an initial foothold.

User namespaces, enabled by userns-remap or by rootless Docker, map container uid 0 to an unprivileged host uid, so even a full container escape lands as a nobody-user on the host. It catches the case where every other fence has failed.

The layering matters because each has gaps: seccomp does nothing about file access, AppArmor does nothing about a bad syscall, and only user namespaces change what "root" means.

Together with --cap-drop=ALL and a read-only root, they are the stack that Kubernetes surfaces as a Pod Security Standard.

Land it Seccomp filters what you may ask the kernel, AppArmor filters what you may touch, no-new-privileges freezes how much you are, and user namespaces decide what root means — name the fence when you name the attack.

Likely follow-ups
"How would you build a tightened seccomp profile for one service safely?"

By recording what it actually calls, then denying the rest with a soft failure first.

I run the service under a tracer, either strace -f -qcf to list syscalls or the newer approach of running with the audit action so seccomp logs rather than kills, using a profile whose default action is SCMP_ACT_LOG.

I exercise it through its full test suite and a soak in staging, collect the union of syscalls, and generate a profile allowing exactly those, which tools like Docker's own tracing or oci-seccomp-bpf-hook produce.

Then I set the default action to SCMP_ACT_ERRNO and deploy to staging with monitoring for denied calls before production.

The risk is a rare code path that calls something the trace missed, which is why I start in log mode and keep it there for a full business cycle.

"Which single one of these four would you enable first if you had none?"

The default seccomp and AppArmor profiles are already on unless someone disabled them, so the real question is what to add.

I would add --cap-drop=ALL with a small add-back, paired with no-new-privileges, because together they close the most common escalation paths for the least effort and break almost nothing.

User namespaces via userns-remap is the highest-value single change for a shared host because it redefines what container root means, but it has the most compatibility fallout, so I stage it.

Seccomp tightening beyond the default gives the least marginal benefit for the most maintenance, so it comes last. The order is: keep the defaults, drop capabilities and no-new-privileges, then user namespaces, then custom seccomp only where it earns its keep.

"Where do these four map onto Kubernetes Pod Security Standards?"

The Restricted standard bundles them. runAsNonRoot: true and a numeric runAsUser correspond to the non-root and, with node configuration, the user-namespace intent, and Kubernetes 1.30-plus adds real user namespaces per pod with hostUsers: false. allowPrivilegeEscalation: false is no-new-privileges.

seccompProfile.type: RuntimeDefault is the default seccomp profile, and Restricted requires it explicitly. capabilities.drop: ["ALL"] is --cap-drop=ALL. AppArmor is set through the appArmorProfile field.

So the Docker flags I harden with by hand are the same controls the cluster enforces declaratively, which is why getting them right in the Compose and run world carries straight over to E10.

"An attacker has code execution as the app user with all four enabled. What can they still do?"

They can do whatever the application itself can, which is the point of least privilege rather than a promise of nothing.

They can read the files the app reads, including any mounted secrets and the app's own data, reach every network endpoint the app's network policy allows, and consume the container's CPU and memory up to its limits.

What they cannot easily do is escalate to container root, since no-new-privileges blocks setuid; make dangerous syscalls, since seccomp blocks them; write host-facing paths, since AppArmor and read-only root block them; or become host root, since user namespaces remap them.

So the residual risk is data the app could reach and lateral movement the network permits, which is why secrets scoping and network segmentation sit alongside these four rather than being replaced by them.

Q112 · Scenario. "A test container ran a script with a bug that forked endlessly. The whole host became unresponsive and had to be power-cycled. Why could a container take down the host, and what stops it next time?"

Reveal answer

The real test Whether you separate namespaces, which hide, from cgroups, which limit — the bomb exploits the gap between them.

Strong answer Diagnosis order:

  1. Symptom: a fork bomb, a process that creates copies of itself until the kernel has no process slots or memory left. Namespaces isolate what a container can see, but they do not limit how much it can consume; that is the job of cgroups, the kernel's resource accounting groups, and Docker applies no pids, memory, or CPU limit unless you ask.
  2. Evidence after reboot: journalctl -b -1 from the previous boot shows fork: retry: Resource temporarily unavailable messages and the OOM killer thrashing; docker inspect of the container shows PidsLimit: 0 and Memory: 0, meaning unlimited. The host's kernel.pid_max is typically 4,194,304 on 64-bit and each process costs kernel memory, so a bomb exhausts memory before it exhausts pids.
  3. Fix: --pids-limit 256 on the run, or pids_limit: 256 in Compose, caps the number of processes in the container's cgroup; the bomb then fails inside the container with the same fork error while the host stays healthy. Pair it with --memory 1g, which makes the OOM killer target the container rather than the host, and --cpus 2 so a spin loop does not starve the daemon. For a JVM, also set -XX:MaxRAMPercentage so the heap respects the cgroup limit, which the JDK reads automatically since version 10.
  4. Set defaults for everyone: "default-ulimits": {"nproc": {"Name": "nproc", "Hard": 4096, "Soft": 4096}} in daemon.json gives a per-user process ceiling, though note nproc is per uid across all containers, which is one more reason to run each service as its own uid. A daemon-wide pids default is not available, so the wrapper or Compose fragment from Q106 carries it.
  5. Prevention: the host itself gets systemd slices reserving CPU and memory for docker.service and sshd, so even a runaway leaves enough for an operator to log in and kill it, and monitoring alerts on container pid counts above 80 percent of the limit.

Land it Isolation is namespaces, containment is cgroups, and Docker only does the first for free — a pids limit is one flag and it is the difference between a failed test and a power cycle.

Likely follow-ups
"nproc as a ulimit is per-uid across containers. Why is that a trap and what is the fix?"

Because the nproc rlimit counts every process owned by that uid on the whole host, not per container.

If three containers all run as uid 1000 and the daemon set nproc=4096, they share one 4096 budget, so a fork bomb in one starves the other two, and raising the limit for one raises it for all.

The fix is twofold: use --pids-limit, which is a cgroup control scoped to the single container regardless of uid, as the real defence, and run each service as its own distinct uid so an rlimit, if used, is not shared.

The pids cgroup limit is the correct tool; the nproc ulimit is a blunt legacy instrument that surprises people precisely because of the cross-container sharing.

"You set --pids-limit 256 and a legitimate service that spawns worker processes now fails. What next?"

Then 256 was too low for that workload, and I size the limit from its real peak.

I measure with cat /sys/fs/cgroup/pids.current under load, or the cAdvisor series container_processes, over a busy period including startup, and set the limit to the observed peak plus generous headroom, often two to three times, because thread-heavy runtimes count threads as pids too.

A JVM with a large thread pool or a Python app using a process pool can legitimately need a few thousand.

The point of the limit is to stop unbounded growth, not to sit just above normal, so I choose a ceiling well above the peak but well below the host's pid_max, and I alert at 80 percent of it so a slow leak is visible before it hits.

"How do you make sure a runaway container never makes the host unreachable, even with limits set?"

By reserving resources for the system outside Docker's reach.

On a systemd host, docker.service runs in its own slice, and I put a limit on that slice, system.slice and a dedicated docker.slice, reserving CPU and memory for sshd, the kernel, and the monitoring agent through MemoryMin and CPUWeight on the system slice.

Then even if every container hits its limit at once, the operator can still log in and act. I also set --oom-score-adj so the kernel prefers killing containers over system daemons, and I keep swap small or off so the machine fails fast rather than thrashing.

The layered rule is: per-container limits stop one container hurting others, and slice reservations stop all containers together hurting the host.

"Fork bomb aside, what other resource exhaustion should the defaults cover?"

Four beyond pids. Memory, with --memory so the OOM killer targets the container not the host. CPU, with --cpus so a spin loop cannot starve the daemon, though for latency services I use shares instead of a hard cap.

Open files, with a sane nofile ulimit so a descriptor leak does not exhaust the host's global limit.

And disk, which Docker does not limit by default: log growth via the log driver's max-size, writable-layer growth via --storage-opt size on supported drivers or by mounting scratch space as a sized tmpfs, and volume growth via filesystem quotas.

The daemon defaults plus the wrapper carry all of these, so a new container is bounded on every axis without the author thinking about it.

Q113 · Design. "Define a container hardening baseline every service at your company must meet, and show the run configuration that expresses it."

Reveal answer

Strong answer Requirements: an attacker who gets code execution inside a service should gain nothing beyond that service's own data, and the baseline must work for Java, Node, and Go apps without per-team negotiation.

Assumptions: images are built by a shared pipeline and run by Compose or Kubernetes. The baseline has seven rules. One, non-root: USER 10001 in the Dockerfile with a numeric uid so the orchestrator can verify it. Two, drop all capabilities and add none by default.

Three, read-only root filesystem with an explicit tmpfs for every path the app writes. Four, no-new-privileges. Five, the default seccomp and AppArmor profiles left on, never unconfined. Six, resource ceilings on memory, CPU, and pids.

Seven, images pulled by digest, and no latest tags in any deployable file. In Compose it looks like this.

compose.hardened.yaml
services:
  api:
    image: registry.example.com/api@sha256:3f1c9e2a6b0d4c8e7a1b2c3d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5a6b7
    user: "10001:10001"
    read_only: true
    tmpfs:
      - /tmp:size=64m
      - /app/work:size=128m
    cap_drop: [ALL]
    security_opt:
      - no-new-privileges:true
    pids_limit: 256
    deploy:
      resources:
        limits:
          cpus: "2"
          memory: 1g
    ports: ["127.0.0.1:8080:8080"]
    healthcheck:
      test: ["CMD", "/app/healthcheck"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 40s

The equivalent docker run flags are --user 10001:10001 --read-only --tmpfs /tmp --cap-drop=ALL --security-opt no-new-privileges --pids-limit 256 --memory 1g --cpus 2. Trade-offs: read-only root breaks images that write to their own directory, which is a defect in the image and the pipeline reports it; some Java agents want to write to /tmp, which the tmpfs covers; a digest pin means an image bump is a visible diff, which is the intent. Exceptions, such as a sidecar that needs NET_ADMIN, are declared with a label naming the ticket, and a nightly check lists every running container that lacks the label and fails the baseline. What I would not do: mandate a custom seccomp profile per service on day one, because the maintenance cost is high and the default profile already blocks the dangerous calls; nor would I make userns-remap a per-service rule, since it belongs at the daemon.

Land it Non-root, no capabilities, read-only, no-new-privileges, default profiles, limits, and digests — seven lines that turn a code-execution bug into a contained one, and a nightly check that they stayed there.

Likely follow-ups
"read_only: true breaks a Java service that writes to /tmp for heap dumps and JIT. How do you handle it cleanly?"

By enumerating exactly what the app writes and giving each a sized tmpfs, keeping the root read-only. Java wants /tmp for the attach socket, heap dumps, and sometimes JIT scratch, so --tmpfs /tmp:size=256m, and I point heap dumps there with -XX:HeapDumpPath=/tmp.

If the app writes logs to a file, that path gets its own tmpfs or, better, the app logs to stdout. Any genuine persistent write goes to a named volume, not the root.

The read-only root then surfaces every sloppy write as a startup error in staging, which is the point: it documents the app's real write set. I capture the final tmpfs list in the service's Compose fragment so it is reproducible.

"How do you enforce the digest-pinning rule when developers want to bump versions easily?"

By automating the bump so pinning is not friction.

Dependencies and base images are pinned by digest in the Dockerfile and Compose file, and Renovate or Dependabot watches the upstream tag and opens a pull request updating the digest whenever it moves, with the changelog in the description.

The developer reviews a diff instead of typing a tag, and CI runs the tests on the new digest before merge. A lint rule, Hadolint's DL3007 for latest and a custom check for un-digested references, fails any manual edit that reintroduces a floating tag.

So the rule is enforced by a gate and made painless by a bot, which is the only way a pinning policy survives contact with a team that ships daily.

"What would you cut from these seven rules if a team pushed back hard on effort?"

I would not cut any of the seven, because each is a line or two, but I would sequence them so early wins come free. Non-root USER, cap_drop: ALL, no-new-privileges, and the resource limits are trivial and I would require them from day one.

Read-only root is the one with real integration cost because it exposes write paths, so I would allow a grace period where it is a warning not a failure, giving teams a sprint to add their tmpfs mounts.

Digest pinning I would enable with the bot in place so it is not manual. Keeping the default seccomp and AppArmor profiles costs nothing since it just means not passing unconfined.

So the cut is not a rule but a timeline: hard-enforce the free five now, phase in read-only, automate pinning.

"How does a nightly audit actually check read-only root and dropped caps on running containers?"

By inspecting the live runtime config, not the files.

For each container, docker inspect --format '{{.Name}} ro={{.HostConfig.ReadonlyRootfs}} caps_drop={{.HostConfig.CapDrop}} caps_add={{.HostConfig.CapAdd}} nnp={{index .HostConfig.SecurityOpt}} user={{.Config.User}}' reports the effective settings the daemon applied, which is what matters since a Compose file can say one thing and a manual docker run another.

The job flags any container where ReadonlyRootfs is false, CapDrop lacks ALL, no-new-privileges is absent, or the user is empty or 0, unless the container carries an exception label naming a ticket. In Kubernetes the equivalent queries the pod's securityContext.

The output is a list of violators posted to the platform channel, and repeated offenders become a blocking policy at admission.

Q114 · Design. "Design secrets handling for containerised services, covering local development, CI builds, and production, and explain why environment variables are the wrong default."

Reveal answer

Strong answer Requirements: secrets never land in an image layer, a log, or docker inspect; rotation without a rebuild; and a development story that does not train people to paste credentials into files they commit. First, why not environment variables.

An environment variable is visible to every process in the container through /proc/<pid>/environ, it is printed by docker inspect to anyone with socket access, it is inherited by child processes such as a shell you exec, and crash reporters and Spring's /actuator/env happily dump it.

The design by stage. In development, Compose file-based secrets: a git-ignored secrets/ directory, a top-level secrets: block pointing at those files, and the service reads /run/secrets/db_password, a tmpfs mount that never touches the image.

The values are throwaway, such as app/app, and a make bootstrap generates them. In CI builds, BuildKit secret mounts: RUN --mount=type=secret,id=maven_token,target=/root/.m2/settings.xml mvn package makes the file exist only during that one RUN step and leaves no trace in any layer.

The pipeline passes it with docker build --secret id=maven_token,src=$HOME/.m2/settings.xml. Never ARG a secret; build arguments are recorded in image history. In production, an external manager is the source of truth: Vault, AWS Secrets Manager, or the cloud provider's equivalent.

The container authenticates with a short-lived workload identity, not a stored key, and either an init step writes the secrets to a tmpfs at start or the app fetches them at boot through a client library with caching and a rotation hook.

Kubernetes' own Secret objects, described in E10, mount as files the same way. Trade-off: file-based secrets need the app to read files, which Spring Boot does through spring.config.import=configtree:/run/secrets/ with no code change.

What I would not do: bake a dev secret into the image "because it is only dev", because images get promoted; or put production secrets in a .env file on the host, which is an environment variable with extra steps.

Land it Files on tmpfs in development, BuildKit secret mounts in CI, a manager plus workload identity in production — and environment variables only for things you would be happy to see in a stack trace.

Likely follow-ups
"Walk me through a BuildKit secret mount versus an ARG — why is ARG so dangerous?"

A build argument is recorded in the image's history: docker history --no-trunc and the config JSON show every ARG value and the command that used it, so a token passed as --build-arg NPM_TOKEN=... is baked into a layer forever and travels to anyone who can pull the image.

A BuildKit secret mount, RUN --mount=type=secret,id=npm,target=/root/.npmrc npm ci, makes the file exist only in the tmpfs of that single RUN step; it is never written to a layer, never in history, and gone when the step ends. The build passes it with --secret id=npm,src=$HOME/.npmrc.

So the rule is: anything sensitive at build time uses a secret mount, and ARG is only for non-secret configuration such as a version number.

"How does the production app get a secret from Vault without a stored token — what is the bootstrap?"

Through an identity the platform vouches for, so there is no first secret to protect.

On Kubernetes the pod has a projected service account token, a short-lived JWT the API server signs, and Vault's Kubernetes auth method verifies it against the API server and returns a Vault token scoped to that service account's policies.

On a cloud VM the equivalent is the instance's IAM role: the app calls the metadata endpoint for temporary credentials and uses them against Secrets Manager.

In both cases the machine's identity, not a stored password, is the root of trust, and the credential it receives is short-lived and rotated automatically.

The Vault Agent or the CSI Secrets Store driver writes the fetched secret to a tmpfs file the app reads, so the app code is unchanged from the Compose file-secret pattern.

"A secret leaked into a Git-committed .env last year. What is the response?"

Rotate first, scrub second, prevent third. The moment it is found, rotate the credential, because it is in the repository history and on every clone and CI cache, so it must be assumed public; scrubbing does not un-leak it.

Then remove it from history with git filter-repo and force-push, invalidate caches, and rotate anything that shared the secret. Investigate access: who could have cloned the repo, and whether the credential shows use from unexpected sources in its provider's audit log.

Prevent recurrence with a pre-commit and CI secret scanner, gitleaks or trufflehog, that blocks the pattern, and move the real secret to the manager so .env holds only throwaway development values. The order matters: a scrub without rotation is theatre.

"When is an environment variable actually acceptable for a secret?"

When the value is low-value and the exposure paths do not matter, or when the platform makes the variable itself a managed secret. A throwaway development password, a feature flag, or a public API base URL are fine as environment variables.

In production the honest exception is a platform where the environment variable is injected from a secrets manager at start and the platform prevents it appearing in inspect output, as some serverless runtimes do; even then it is still readable via /proc/self/environ and inherited by child processes, so I prefer a file.

My test is the one from the land-it line: if I would be unhappy to see the value in a stack trace or a crash report, it does not go in an environment variable.

Q115 · Design. "Design a rollout of rootless Docker to two hundred developer laptops and shared Linux workstations. What breaks, what is the migration path, and what do you tell the security team it does and does not buy?"

Reveal answer

Strong answer Requirements: remove "member of docker group equals root" from every Linux machine, keep the daily workflow unchanged for most people, and have a documented exception path. Assumptions: Ubuntu and Fedora laptops, kernel 5.11 or newer so overlay2 works unprivileged, Docker Engine 27 or newer.

What rootless Docker is: the daemon itself runs as the user, inside a user namespace, with networking supplied by a user-space helper such as slirp4netns or pasta, so neither the daemon nor any container ever holds host root. The rollout has four phases.

Phase one, pilot: the platform team installs it with dockerd-rootless-setuptool.sh install on ten volunteer machines, sets DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock, and collects breakage.

Phase two, fix the known breakages in shared tooling: ports below 1024 need net.ipv4.ip_unprivileged_port_start=0 on the host or a switch to high ports; --network host shows the rootless network namespace rather than the real host; bind-mounted files owned by other users are unreadable because uid mapping only covers the user's own subordinate range from /etc/subuid; a few images that chown volumes to a fixed uid fail and need --userns=keep-id-style handling; and the user-space network stack is slower, which pasta largely fixes.

Phase three, default-on through the laptop management tool, with the system daemon disabled and the docker group emptied. Phase four, exceptions: machines that must run the system daemon, such as ones doing kernel-module or GPU work, get it with userns-remap and an owner recorded.

What it buys the security team: a container escape or a socket mount lands as the developer's own uid, not root, and a malicious image cannot modify the host system.

What it does not buy: it does not protect the developer's own files, which are the valuable thing on a laptop, so pulling by digest and banning latest tags are still required.

What I would not do: flip the switch for everyone on the same day, because the first blocked developer will install the system daemon from a blog post and you will be worse off than before.

Land it Rootless turns "docker group is root" into "docker is you", which is a real win for the host and no win for your home directory — roll it out in phases and keep provenance rules alongside it.

Likely follow-ups
"A developer's build needs a service on port 443 inside a rootless container. What breaks and how do you fix it?"

In rootless mode the daemon cannot bind privileged ports on the host by default, because the daemon itself is unprivileged, so publishing -p 443:443 fails. Three fixes, in order of preference.

Lower the host's threshold once with sysctl net.ipv4.ip_unprivileged_port_start=443, applied through config management, which lets the rootless daemon bind 443 and above. Or grant the rootlesskit binary the capability with setcap cap_net_bind_service=ep $(which rootlesskit).

Or publish a high port such as 8443 and put a host-level reverse proxy or an ssh tunnel in front.

For most developers the answer is simply to use a high port locally, since nothing on a laptop requires 443 specifically; the sysctl is the fix when a tool hard-codes it.

"What exactly do you tell the security team rootless does not protect?"

The developer's own files and identity. Rootless removes host root as an outcome of a container escape, so a malicious image or a socket-mounting container lands as the developer's uid, not root, and cannot modify system files or other users.

But it runs as the developer, so it can already read everything in their home directory, use their SSH keys and cloud credentials, and reach anything their network access allows, which on a laptop is the valuable target.

So rootless is a strong control for the shared host and for protecting the machine from the container, and no control at all for protecting the user's data from a malicious image. That is why provenance, digest pinning, and banning latest stay mandatory alongside it.

"How do you handle the machines that genuinely need the system daemon?"

By treating them as a small, named exception rather than leaving the door open everywhere.

Machines doing kernel-module work, GPU workloads that need device access the rootless stack cannot give, or nested virtualization keep the system daemon, configured with userns-remap and no-new-privileges so it is hardened even though it is rootful, and each is recorded with an owner and a reason in an inventory.

They are separated on the network from general developer machines, and access to them is limited. Everywhere else the system daemon is disabled and the docker group emptied.

The goal is that the rootful surface is a handful of documented machines an attacker cannot assume exists, not the default state of two hundred laptops.

"What would you cut if the rollout had to finish in a month instead of a quarter?"

I would cut the breadth of the pilot and the per-team hand-holding, not the phasing.

A month means: one week piloting on twenty machines across the two main Linux distributions to catch the real breakages, then default-on through the management tool for the clearly-compatible majority, with a documented opt-out to the exception process for anyone genuinely blocked.

I would keep the exception path and the empty-docker-group end state because those are the whole point.

What I would not cut is the phased ordering itself, because the failure mode of a big-bang flip is that the first blocked developer reinstalls the system daemon from a blog post, leaving the fleet less safe than before and harder to reason about. Speed comes from a narrower pilot, not from skipping the waves.

10 · DrillProduction Scenarios & Design — Q116–Q150

The last thirty-five questions are the ones a hiring manager asks after the Dockerfile trivia is done: how images get built, scanned, signed, stored, promoted, and rolled back across a fleet of forty services, and what you do at 09:00 when every deploy fails with a registry error.

Most of these have no single right answer, so the interviewer is listening for requirements first, then a design, then the trade-offs you name unprompted.

Scenario answers go in diagnosis order — symptom, evidence, ranked causes, fix, prevention — and design answers always end with what you would not do.

Version claims are as of Aug 2026: Docker Engine 29.x current with 28.x still supported, containerd 2.x, Trivy 0.6x, cosign 2.x with 3.x rolling out. Say each answer out loud before you reveal it.

Drill · Registries & the supply chain

These questions test whether you treat the registry as production infrastructure with availability, capacity, and trust properties — not as a bucket you push to.

Q116 · Scenario. "Every weekday at 09:00 about a third of our deploys fail with toomanyrequests: You have reached your pull rate limit. By 09:40 it clears. Walk me through it."

Reveal answer

The real test Whether you know the rate limit is per source identity, why it clusters at 09:00, and that the durable fix is removing Docker Hub from the pull path entirely.

Strong answer I would diagnose in this order:

  1. Confirm the symptom is Docker Hub's pull limit and not our own registry. The error string toomanyrequests with HTTP 429 is Docker Hub's. As of Aug 2026 anonymous pulls are limited per source IP address per six hours, and free authenticated accounts get a higher but still small budget; only paid team or business accounts get generous limits.
  2. Collect evidence: the remaining budget from the ratelimit-remaining header on a manifest request with curl, and which images are being pulled at 09:00. The 09:00 clustering almost always means scheduled jobs, autoscaling scale-up, or a morning burst of CI runs all pulling from behind one NAT gateway. A NAT gateway means hundreds of nodes share one public IP, so they share one anonymous budget.
  3. Ranked causes: anonymous pulls through a shared NAT, then imagePullPolicy: Always on latest tags forcing a manifest check on every pod start, then base images referenced as bare python:3.12 in CI which resolve to Docker Hub.
  4. Immediate fix: authenticate the pulls with a paid organisation account so the budget is per account instead of per IP, and set pull policy to IfNotPresent with digest-pinned tags.
  5. Durable fix: stand up a pull-through cache (a registry that fetches from Docker Hub once and serves every later pull locally), for example the registry:2 mirror mode, Harbor's proxy cache project, or ECR's pull-through cache rule, and rewrite all references to point at it.
  6. Prevention: a CI policy check that rejects any image reference not under your internal registry hostname, plus an alert on 429 responses in node and CI logs.

Land it Paying for an account buys you the morning back; the pull-through cache buys you independence from a third party's outage and pricing forever.

Likely follow-ups
"You added a paid account and it still throttles occasionally. What did you miss?"

Probably that not every pull authenticates.

A paid organisation budget applies only when the client logs in, and several pull paths do not: a base image referenced as bare python:3.12 in a Dockerfile that a build runner pulls before login, a Kubernetes node whose kubelet has no image-pull secret for Docker Hub, and a sidecar or init container from a third-party chart pointing straight at docker.io.

I would grep the fleet's manifests and Dockerfiles for docker.io and bare official names, confirm with the ratelimit-remaining header which identity each pull uses, and route everything through the internal pull-through cache so Docker Hub is contacted once per image regardless of who pulls.

The durable fix is that no node ever talks to Docker Hub directly.

"Why does it cluster at exactly 09:00 and clear by 09:40?"

Because the limit is a rolling six-hour budget per source IP, and 09:00 is when the day's demand spikes through one shared exit.

Scheduled CI runs kick off as people arrive, autoscaling scales up for the morning traffic, and nightly-to-morning cron jobs land, all pulling within a few minutes through the same NAT gateway that shares one public IP and therefore one anonymous budget.

The budget drains, pulls get 429, and by 09:40 enough of the six-hour window has rolled forward, or the burst has passed, that headroom returns.

The clustering is the signature of many machines behind one IP hitting a per-IP limit simultaneously, which is exactly what a cache or authentication per account dissolves.

"What does the pull-through cache cost and how do you keep it available?"

It costs a little storage and one more service to run, and its availability must match the fleet's because a dead cache with no fallback stops pulls.

I run it as a highly available service, two replicas behind a load balancer with shared or replicated storage, one per region so a regional outage is contained, and I configure containerd's mirror so it falls back to the next mirror or the upstream if the primary cache is down.

Storage grows with the number of distinct images, bounded by a retention policy that expires untagged blobs.

The cache also becomes a chokepoint I must monitor, so I alert on its error rate and latency with the same severity as the applications that depend on it, exactly as with the internal registry.

"How would you prevent any team from adding a new docker.io reference in future?"

A CI policy check that fails any Dockerfile, Compose file, or Kubernetes manifest whose image references are not under the internal registry hostname, run in the shared pipeline template so every repository inherits it.

The check allow-lists registry.internal/ and the cache's hostname and rejects docker.io, bare official names, and other public registries, with a message pointing at the mirrored equivalent.

At deploy time an admission policy enforces the same rule for anything that slipped through, so a manifest pulling from Docker Hub is rejected before scheduling. And Renovate keeps the mirrored base images current so nobody is tempted to reach upstream for a newer tag.

Enforcement at both the build gate and the admission gate is what keeps the rule from eroding.

Q117. "How does registry authentication actually flow for a CI runner and for a production node — and why should those two identities be different?"

Reveal answer

Strong answer A registry uses the Docker Registry HTTP API, and authentication is a token dance.

The client requests a manifest, the registry answers 401 with a WWW-Authenticate header naming a token service and a scope such as repository:team/api:pull, the client presents credentials to that token service, and it receives a short-lived bearer token that it sends on every following request.

docker login only stores the long-lived credential in ~/.docker/config.json, or hands it to a credential helper so it is never written in plain text.

On a CI runner the right credential is a short-lived one obtained through workload identity: GitHub Actions or GitLab exchange an OpenID Connect token — a signed statement of "this job in this repo on this branch" — for cloud credentials that map to a push-scoped role on ECR, Google Artifact Registry, or Azure Container Registry.

Nothing static is stored. On a production node the runtime, containerd 2.x in most fleets, needs pull-only access, and it gets that from the node's instance identity through a credential provider plugin rather than from a secret copied onto disk.

The two identities must differ because a compromised node should not be able to push a poisoned image, and a compromised CI job should not be able to read every production image. Least privilege at the registry is the cheapest supply-chain control you have.

Land it The senior answer names the token exchange and workload identity; the junior answer is a shared robot password in a CI variable that nobody has rotated since 2023.

Likely follow-ups
"Walk me through the OIDC exchange for a GitHub Actions job pushing to ECR."

The workflow requests an OIDC token from GitHub with id-token: write permission; GitHub mints a short-lived JWT whose claims include the repository, the workflow, and the branch or tag.

The job calls AWS STS AssumeRoleWithWebIdentity, presenting that JWT. AWS has an IAM OIDC identity provider registered for token.actions.githubusercontent.com and a role whose trust policy allows that provider only when the token's sub claim matches, say, repo:acme-org/api:ref:refs/heads/main.

STS validates the JWT signature against GitHub's published keys, checks the condition, and returns temporary AWS credentials valid for the session. The job uses those to authenticate to ECR and push.

Nothing static is stored, and the trust is scoped to one repository and branch, so a fork or another repo cannot assume the role.

"How does a production node get pull credentials without a secret on disk?"

Through the node's own cloud identity and a credential provider. On AWS the node's instance profile grants ECR read, and containerd's ECR credential helper calls the metadata endpoint for temporary credentials at pull time, so nothing is written to disk and the credentials rotate automatically.

On GKE and AKS the equivalent workload or node identity does the same for Artifact Registry and ACR. In Kubernetes the kubelet credential provider plugin performs this per pull.

The node therefore has read-only access scoped to what it must run, and there is no long-lived registry password anywhere on it, which means a compromised node yields no reusable credential and cannot push.

"Why must the CI identity and the node identity be different, concretely?"

Because their compromises have opposite blast radii and combining them multiplies both. The CI identity can push, so if a node held it, a single compromised node could poison an image every other node then pulls, turning one host into fleet-wide code execution.

The node identity can pull every image, so if CI held it, a malicious pull-request build could exfiltrate every production image.

Splitting them means a compromised node can only read what it already runs and cannot alter anything, and a compromised CI job can push but cannot read unrelated production images or reach nodes.

Least privilege at the registry, push for build and pull for run, scoped to the right repositories, is the cheapest supply-chain control and it directly bounds these two very different incidents.

"What if the registry is a plain self-hosted one with no cloud identity available?"

Then I use robot accounts with narrow scopes and short-lived tokens rather than a shared password.

Harbor and GitLab's registry support robot accounts scoped to a project with push or pull only, and I issue a separate robot per pipeline and per environment, storing its token in the CI secret store and rotating it on a schedule.

Nodes get a pull-only robot delivered by config management, not baked into images. Where the registry supports it, I put an OIDC-aware token service in front so CI can still exchange its pipeline identity for a scoped token.

The principle is unchanged even without cloud identity: distinct identities for build and run, least privilege per repository, and the shortest-lived credential the setup allows.

Q118 · Design. "Design a registry topology for a company running clusters in three regions, with pull-through caches and a retention policy."

Reveal answer

The real test Whether you separate the single source of truth from the many read paths, and whether you have a story for storage growth.

Strong answer Assumptions: about forty services, roughly 200 image pushes a day, three regions with a few hundred nodes each, and a requirement that a regional outage of the registry must not stop deploys or pod restarts elsewhere.

The design has one authoritative registry, the place CI pushes to and the only place with write access, and one read-only mirror per region.

On AWS that is a primary ECR repository with cross-region replication rules; with Harbor it is a primary instance plus replication policies pushing to a Harbor per region.

Every node and cluster is configured to pull from its regional mirror, with containerd's hosts.toml mirror configuration falling back to the primary if the mirror is down.

Third-party images never come straight from Docker Hub: each regional registry has a pull-through cache rule for docker.io, ghcr.io, and quay.io, so an upstream image is fetched once per region and cached.

Retention runs in the primary and replicates as deletions: keep every digest referenced by a running workload (checked by a nightly job against the clusters), keep the last 30 tagged images per service, keep anything tagged as a release for 18 months for audit, and expire untagged manifests after 7 days.

Trade-offs: replication lag of a minute or two means a deploy must wait for the digest to exist in its region.

I would not run one global registry with nodes pulling across regions, because cross-region egress costs real money, and I would not let developers push straight to regional mirrors, because two sources of truth make signing and audit meaningless.

Land it One write path, many read paths, and a retention rule that starts from "what is still running" rather than from an arbitrary count.

Likely follow-ups
"Replication lag means a deploy races the digest into a region. How do you handle it?"

By making the deploy wait for the digest to exist locally rather than assuming it.

The deploy pipeline, after pushing to the primary, polls each regional mirror with crane digest or a HEAD on the manifest until the target digest resolves there, with a timeout, before it triggers the regional rollout. That turns a race into a deterministic gate.

For pull-through of third-party images the same applies. If the registry supports synchronous or on-demand replication, I trigger a pull of the specific digest to warm the mirror.

The alternative, nodes falling back to the primary across regions when the mirror lacks the image, works but costs cross-region egress and latency, so I use it as a safety net rather than the normal path.

"How does the retention rule know what is still running so it does not delete a live digest?"

A nightly job queries every cluster and host for the digests currently in use, from Kubernetes it is the imageIDs on running pods, from Docker hosts the docker ps --no-trunc images, deduplicates them into an allow-list, and the garbage collection excludes anything on that list regardless of age or tag count.

This matters because digest-pinned deployments reference images by an untagged digest, and a naive "keep the last 30 tags" rule would delete a running untagged image and break the next pod restart.

So retention starts from "what is live", then adds "the last N tags per service" and "releases for 18 months", and only then expires the remainder. The live set is the floor that overrides every other rule.

"What changes if the three regions span different cloud providers?"

The topology holds but the mechanics fragment.

Cross-provider replication cannot use a single provider's built-in feature, so I either run one registry product, Harbor, on all three with its own replication policies pushing between them, or use an external tool such as skopeo sync or regctl on a schedule to copy digests provider to provider.

Authentication becomes per-provider, so nodes in each cloud use that cloud's identity to reach the local registry, and the CI push identity must reach the authoritative one wherever it lives.

Egress cost and latency between providers make the per-region mirror even more important, and I would keep the single source of truth in the provider where CI runs to minimise the push path.

The invariant, one write path and many read paths with a live-set retention rule, does not change.

"Would you ever accept a single global registry to keep it simple?"

For a small footprint, yes, with eyes open.

If the whole estate is in one region or one cloud and pulls are modest, a single highly available registry plus a pull-through cache in each cluster is simpler and avoids replication entirely, and I would take that over premature multi-region complexity.

The point where it stops working is when a regional outage of that registry must not stop deploys or restarts elsewhere, or when cross-region pull egress becomes a real bill, or when latency on cold pulls hurts scale-up.

At that point the read replicas earn their keep. So I size the topology to the actual availability requirement and cost, and treat "one registry, caches everywhere" as the correct default until a specific requirement forces replication.

Q119 · Scenario. "Our private registry has been down for two hours. Running containers are fine, so nobody panicked. Then one node rebooted and now six services are degraded. What is happening and what do you do?"

Reveal answer

Strong answer I would diagnose in this order:

  1. The symptom is consistent with the registry being a hard dependency for scheduling, not for running. A running container never talks to the registry. A rebooted node loses nothing in its image store if the disk survived, but the workloads that were on it get rescheduled elsewhere, and any node that does not already have that digest cached must pull. With the registry down, those pulls fail with ImagePullBackOff.
  2. Evidence to collect: docker images --digests or crictl images on the healthy nodes to see which digests are already present, and the events on the failing workloads. Also check whether the pull policy is Always, because that forces a manifest fetch even when the image is present locally, and that fetch fails during the outage.
  3. Ranked causes: rescheduling onto nodes without the cached image, pull policy Always defeating the local cache, and a mirror pointing at the same dead backend as the primary.
  4. Fix now: pin the affected workloads to nodes that already hold the images, or copy the images across with docker save on a healthy node and docker load on the target, then switch the pull policy to IfNotPresent. In parallel, fail the registry over to its replica or to the regional mirror.
  5. Prevention: pull-through mirrors per region as in the topology design, pull policy IfNotPresent with digest references so the local cache is trusted, a warm-cache job that pre-pulls the current release onto every node, and an alert on the registry with the same severity as the applications it feeds.

Land it The registry is invisible until the first restart, so its availability target must equal the highest target of anything that pulls from it.

Likely follow-ups
"You switched pull policy to IfNotPresent but a security patch now does not roll out. How do you reconcile that?"

By pinning to digests rather than to a mutable tag, which makes IfNotPresent safe. With IfNotPresent and a moving tag such as :1.4, a node that already has some image for that tag never re-pulls, so a rebuilt :1.4 is missed.

With a digest reference, a patch is a new digest, so the deployment manifest changes, the node does not have that digest, and it pulls it once.

So the reconciliation is: deployments reference @sha256:..., a patch changes the manifest through the normal Git-driven deploy, and IfNotPresent still trusts the cache because a digest is immutable.

Always is only needed when you insist on mutable tags, and it is the mutable tag that is the real problem.

"How do you warm caches so a reboot during a registry outage is survivable?"

A pre-pull job that runs on every node and pulls the current release's digests before they are needed, driven by a DaemonSet in Kubernetes or a config-management task on plain hosts, so every node holds the running set locally.

Then a reschedule or reboot finds the image already present and needs no registry. I refresh it on each promotion so the warm set tracks what is deployed.

For the third-party and base images, the per-region pull-through cache means even a cold node reaches a local copy rather than the upstream. Together they make the registry a dependency for new images only, not for restarts, which is the property the outage exposed was missing.

"During the outage, is docker save and load a good idea or a last resort?"

A last resort that works. On a healthy node docker save image@digest | ssh target docker load, or via a file, copies the exact image to a node that lacks it, bypassing the registry entirely, which is enough to restore the six degraded services now.

It is a last resort because it is manual, does not scale past a handful of nodes, and loses the digest-addressability if done carelessly, so I verify the digest after load.

I reach for it only to stop the bleeding while I fail the registry over to its replica or mirror, which is the real fix.

In parallel I would raise the registry's availability target, because the whole incident is a registry treated as less critical than the services that pull from it.

"What is the correct availability target for the registry, and why?"

At least as high as the highest target of anything that pulls from it, because it is a hidden hard dependency for scheduling and restarts even though running containers do not touch it.

If the most critical service promises three-and-a-half nines, the registry cannot promise less, or a registry outage caps that service's availability the moment a node restarts.

Practically that means the registry is highly available within a region, replicated across regions so a regional outage is survivable, backed by durable storage, and monitored and paged like a tier-one service.

The mistake in the scenario was treating it as infrastructure that "nobody uses" because running containers were fine, when in fact its outage was one reboot away from an incident.

Q120. "We deleted 2,000 old tags and the registry's disk usage did not change. Why, and what actually reclaims space?"

Reveal answer

Strong answer A registry stores three kinds of objects: blobs, which are the compressed layer files and config files addressed by their SHA-256 digest; manifests, which are small JSON documents listing which blobs make up one image; and tags, which are just names pointing at a manifest.

Deleting a tag removes only the pointer. The manifest and every blob it references stay on disk, and because layers are shared across images, one blob may be referenced by hundreds of manifests.

Space is only reclaimed by garbage collection, a separate pass that walks every manifest still reachable from any tag, marks the blobs they reference, and deletes everything unmarked.

In the open-source registry that is registry garbage-collect /etc/docker/registry/config.yml, and you must run it with --delete-untagged to also drop manifests that no tag points at, otherwise digest-referenced images survive by design.

Harbor runs the same idea as a scheduled job, and ECR and Google Artifact Registry do it behind lifecycle policies. Two cautions matter in production.

Classic garbage collection needs the registry in read-only mode or a push during the pass can reference a blob that is about to be deleted, so schedule it at a quiet hour.

And digest-pinned deployments keep manifests untagged on purpose, so your policy must whitelist any digest a cluster still runs before the pass.

Land it Tags are labels, blobs are the bytes; you free bytes only by proving no reachable manifest still needs them.

Likely follow-ups
"Why does garbage collection need read-only mode, and what happens if you skip it?"

Because classic garbage collection is a mark-and-sweep in two phases with a gap between them. It first walks all manifests and marks every referenced blob, then deletes the unmarked blobs.

If a push arrives between mark and sweep that references a blob the mark phase saw as unreferenced, for example a layer shared with a new image, the sweep deletes a blob the new manifest now needs, corrupting that image.

Read-only mode closes the window by refusing pushes during the pass. Skipping it risks exactly that race, which surfaces later as a pull failing with a missing blob.

Newer registry versions and hosted services reduce the window with reference counting, but for the open-source registry the documented safe path is read-only during collection, scheduled at a quiet hour.

"You have digest-pinned deployments. How does that interact with --delete-untagged?"

Dangerously if you run it blindly. --delete-untagged removes manifests that no tag points at, and a digest-pinned deployment references an image precisely by its untagged digest, so a promotion flow that retags and lets the old tag expire leaves the running image as an untagged manifest.

Running --delete-untagged then deletes the image a cluster is still pinned to, and the next pod restart fails.

So before collection I build the allow-list of digests currently running, and either the retention tool excludes them or I keep a hidden tag on each live digest so it is never untagged.

The rule is the same as retention generally: the live set overrides the tidy-up, and digest pinning makes that override mandatory rather than optional.

"Two thousand tags freed nothing. How much would you actually expect to reclaim, and how do you predict it?"

Often far less than the tag count suggests, because layers are shared. If those 2,000 tags were nightly builds of a few services, they share most base and dependency layers, so the unique reclaimable bytes are just the top application layers that no surviving manifest references.

I predict it with a dry run: registry garbage-collect --dry-run lists what would be deleted without deleting, and Harbor and cloud registries show reclaimable size before you run the job.

I would run the dry run, read the byte estimate, and set expectations accordingly, because promising a big reclaim from a tag delete and then freeing two percent is a credibility loss.

The real space is freed only when the last manifest referencing a blob is gone.

"How would you keep this from recurring, so disk does not creep back?"

A retention policy that runs automatically rather than a manual cleanup after a scare.

The policy keeps the live set, the last N tags per service, and releases for the audit window, and expires untagged manifests after a few days and everything else beyond its rule, with garbage collection scheduled weekly in read-only mode or through the hosted service's lifecycle rules.

I alert on registry storage crossing a threshold so growth is visible before it is urgent. And I make the build side tidy: immutable git-SHA tags rather than thousands of mutable ones, and no unbounded nightly tag accumulation.

Automation plus a storage alert turns disk management into a background process instead of a recurring incident.

Q121 · Scenario. "A release engineer signed an image with cosign, then retagged it from api:1.4.0-rc1 to api:1.4.0 for production. Admission now rejects it with 'no matching signatures'. Nothing was rebuilt. What went wrong?"

Reveal answer

The real test Whether you know signatures attach to digests, not tags, and that some retag paths silently produce a new digest.

Strong answer I would diagnose in this order:

  1. Establish what the signature covers. cosign signs the manifest digest, the SHA-256 of the image manifest, and stores the signature as a separate artifact in the registry under a tag derived from that digest. A tag is never part of what is signed.
  2. Evidence: crane digest registry/team/api:1.4.0-rc1 and the same for :1.4.0. If they differ, that is the whole story. Then cosign tree registry/team/api@sha256:… to list what signatures and attestations exist for each digest, and the admission controller's log for the exact identity and issuer it expected.
  3. Ranked causes: the retag was done with docker pull, docker tag, docker push, and the push from a different Docker version or a single-platform pull of a multi-arch image re-created the manifest with a different digest. Second, the retag went to a different repository and the signature was not copied with it. Third, the policy pins the signer identity to a branch or workflow name that the release job does not match, so the signature exists but is not trusted.
  4. Fix: retag server-side with crane tag or cosign copy, which add a tag to the existing manifest without moving bytes, so the digest and its signatures are untouched. If the repository changed, run cosign copy to carry the signatures over.
  5. Prevention: promotion by digest only, with crane tag in the pipeline and no local Docker daemon in the loop, plus verification as a pipeline step right after the retag so the failure surfaces before admission does. Cross-reference E10 for the admission policy side.

Land it Pull-tag-push is a rebuild in disguise; server-side retagging keeps the digest and therefore keeps the trust.

Likely follow-ups
"The digests match but admission still rejects it. Now what?"

Then the signature exists on the right digest but the policy does not trust it, so the problem is identity matching, not digests.

I read the admission controller's log for the exact expected --certificate-identity and --certificate-oidc-issuer and compare them with what the signature actually carries via cosign verify run by hand with the same flags, or cosign tree to list the signatures.

Common causes: the signing job ran on a different branch or workflow than the policy pins, so the certificate's identity regexp does not match; the signature was made keyed while the policy expects keyless or vice versa; or the Rekor or Fulcio roots the verifier trusts differ from the ones used to sign.

The fix is to align the policy's expected identity with the release job's real identity, or to re-sign from a job that matches.

"How do you retag safely so digests and signatures are preserved?"

Server-side, without a local Docker daemon. crane tag registry/team/api@sha256:... 1.4.0 adds a new tag pointing at the exact existing manifest, moving no bytes and changing no digest, so the signature that covers that digest still applies.

If the promotion crosses repositories, cosign copy registry/team/api:1.4.0-rc1 registry/team/api-prod:1.4.0 copies the manifest and its associated signatures and attestations together.

What I never do is docker pull, docker tag, docker push, because a pull of a multi-arch image on a single-platform daemon, or a re-push under a different Docker version, re-creates the manifest with a new digest and orphans the signature.

The whole promotion flow is digest-based and daemonless for exactly this reason.

"How do you keep pull-tag-push out of the release pipeline entirely?"

By removing the Docker daemon from the promotion step and gating on verification. The pipeline promotes with crane or cosign copy only, and there is no docker in that job's environment, so the tempting three-command retag is not even available.

Immediately after the retag, a pipeline step runs cosign verify against the new reference with the production policy's exact identity flags, so if the digest or signature is wrong the pipeline fails there, before admission ever sees it.

And the deployment manifests reference the image by digest, not by the 1.4.0 tag, so even a mistaken tag move cannot change what runs. Verification as a pipeline step is the control that surfaces the failure at the cheapest possible place.

"What if the release engineer insists a local retag is simpler?"

I would show them the failure they just caused: a local pull-tag-push re-created the manifest, changed the digest, and orphaned the signature, which is precisely why admission rejected a byte-identical release and cost an incident.

Then I would show that the server-side alternative is actually simpler, one crane tag command, no daemon, no pull of gigabytes, and it finishes in a second. Simplicity that breaks trust is not simplicity.

If they still want a local workflow for convenience, it can produce a candidate, but promotion to production goes through the digest-based pipeline with verification, because the whole point of signing is defeated by a step that quietly rebuilds the manifest.

Q122. "What are the realistic supply-chain attacks on a container image, and which controls actually stop each one?"

Reveal answer

Strong answer I group the attacks by where in the chain they land. First, typosquatting: an attacker publishes pyhton:3.12 or nginx-alpine on a public registry and waits for a typo or a copied snippet.

The control is an allow-list of registries and namespaces enforced in CI and at admission, so a reference outside registry.internal/ is rejected before it is ever pulled.

Second, mutable tags: FROM ubuntu:latest or node:22 can point at different bytes tomorrow, and if the upstream account is compromised, the next build ingests the attacker's layer.

The control is digest pinning with automated bump pull requests, so every change to the base is a reviewed diff. Third, a compromised or impersonated registry: DNS or a proxy serving modified layers.

The control is signature verification against a trusted identity, so bytes from the wrong signer fail regardless of where they came from. Fourth, a poisoned build: a dependency pulled at build time from a package mirror, or a CI runner that has been tampered with.

The control is provenance, a signed record of which builder ran which source commit, plus SBOM diffing to notice a package that should not be there. Fifth, the insider path: a developer with push rights to the production repository.

The control is separating build identities from promote identities and requiring the promotion step to verify the CI signature. Every control here is cheap compared with the incident it prevents, and none of them requires Kubernetes to start.

Land it Name the attack, then the control, then where it is enforced; a list of tools without that mapping is not an answer.

Likely follow-ups
"Which of these controls would you implement first for the most risk reduction?"

The registry and namespace allow-list, enforced at both the build gate and admission, because it kills typosquatting and unauthorised registries outright and is a few lines of policy.

Digest pinning with a bump bot is a close second, since it removes the mutable-tag attack that a compromised upstream account exploits, and it also gives reproducibility for free.

Signature verification at admission is third because it needs the signing pipeline in place first, and provenance and SBOM diffing follow once the attestations are being produced.

So the order is: control what you pull from, control that it cannot change under you, then prove who built it and what is inside. Each step assumes the previous, and the first two block the most common real attacks for the least effort.

"How does SBOM diffing actually catch a poisoned build?"

By comparing the inventory of the new image against the last known-good one and flagging anything that appeared without a corresponding source change.

If a build-time dependency was swapped for a malicious version, or an extra package was injected by a tampered runner, the new SBOM contains a component the diff did not expect, a new library, a changed version, or a package the manifest and lock file do not explain.

The pipeline generates the SBOM at build time, diffs it against the previous release's attested SBOM, and requires a human to acknowledge unexpected additions.

It is not foolproof, since a sophisticated attacker could match the inventory, but it catches the common case of an added or altered component, which pure signature checking would happily sign.

"The insider path is a developer with push rights. How do the technical controls actually stop that?"

By separating who can build from who can promote, and making promotion require a machine-verifiable claim only CI can produce. Developers do not have push rights to the production repository; only the CI identity does, and it pushes with a keyless signature bound to its workflow.

Promotion verifies that CI signature, so an image a person pushed by hand lacks the expected identity and fails admission. Branch protection and required reviews mean the source that CI builds was seen by someone other than the author.

So the insider would need to compromise the CI workflow itself, review included, not merely hold push rights, which raises the bar from one person to a reviewed change on a protected branch. The controls turn a single trusted human into a multi-party, logged process.

"What attack does none of this stop, and what do you do about it?"

A vulnerability in the application's own reviewed source, and a compromised upstream that is signed and provenanced by its legitimate but breached maintainer.

Signing proves who built it, not that what they built is safe, and provenance proves where it came from, not that the source was benign. Against the first I rely on code review, dependency scanning, and runtime controls that limit what a compromised app can reach.

Against the second I add SBOM-based vulnerability monitoring so a newly disclosed issue in a trusted component is found fast, and defence in depth at runtime, least privilege, network egress control, so even a trusted-but-malicious image is contained.

The supply-chain controls raise the cost of tampering; they do not replace review and runtime containment.

Q123 · Design. "Design a delivery process for a customer site that is fully air-gapped: no internet, no access to our registry, quarterly on-site visits."

Reveal answer

Strong answer Requirements: the customer runs about fifteen of our images plus a handful of third-party ones, updates arrive on approved media, the site must be able to verify what it received, and they need to roll back without our help. The design is a bundle.

On our side a pipeline job resolves every image in a release to its digest, pulls all platforms the customer runs, and writes a single tarball.

I prefer crane pull --format=oci or skopeo copy into an OCI layout directory over docker save, because the OCI layout preserves multi-arch manifests, signatures, and SBOM attestations, whereas docker save flattens to one platform and drops everything that is not a layer.

The bundle also carries the compose or Helm files, the SBOMs, the cosign public key or the Sigstore trust root, and a checksum file signed with our release key.

On site, the engineer loads the bundle into the customer's local registry with skopeo copy from the OCI directory, and verifies every digest and signature offline with cosign verify --offline using the bundled Rekor entries.

Rollback is simply the previous bundle's digests, kept in the local registry. Trade-offs: bundles are large, so we strip debug variants and build from a shared base to maximise layer reuse.

What I would not do is ship docker save tarballs built on a laptop, because they cannot be verified and they are not reproducible, and I would not allow the customer registry to be configured with any upstream mirror, because a "temporary" internet path defeats the whole compliance claim.

Land it The air gap is a trust boundary, so the bundle must carry its own proof — digests, signatures, SBOMs — not just bytes.

Likely follow-ups
"Why OCI layout over docker save, concretely?"

Because docker save flattens to a single platform and drops everything that is not an image layer.

A saved tarball loses the multi-arch manifest list, so if the customer runs both amd64 and arm64 you would need two saves and manual handling, and it discards the cosign signatures and the SBOM and provenance attestations, which are stored as separate referrer artifacts in the registry, not inside the image.

An OCI layout directory produced by crane pull --format=oci or skopeo copy preserves the manifest list and copies the referring artifacts, so the whole verifiable bundle travels together.

Since the entire point at an air-gapped site is that they can verify what they received offline, keeping the signatures and SBOMs attached is not optional, and docker save would throw exactly those away.

"How does the customer verify signatures with no internet access to Rekor?"

With offline verification against bundled trust material. cosign supports --offline verification when the signature bundle includes the Rekor inclusion proof and the signed entry timestamp, which the pipeline captures at signing time and I include in the bundle.

I also ship the Fulcio root and Rekor public key, or the full Sigstore trust root as a TUF bundle, so the customer's cosign can validate the certificate chain and the transparency-log proof without reaching the public Sigstore services.

For a fully air-gapped customer that must sign their own approvals, I would instead use a keyed cosign flow with a public key I ship, which needs no Rekor at all.

Either way the verification material is part of the bundle, because the air gap means nothing can be fetched at verify time.

"The customer needs to roll back on their own between visits. How?"

By keeping previous bundles and referencing images by digest.

Each quarterly bundle is self-contained and loaded into the customer's local registry with skopeo copy, and the previous bundle's digests remain in that registry, so rollback is re-pointing the customer's Compose or Helm manifests at the prior digest, which is already present locally.

I ship a rollback runbook and a script that flips to the last-known-good digest and restarts, tested before delivery. Because everything is digest-addressed and immutable, rollback needs no rebuild and no contact with us.

I keep at least the last two or three bundles' images under the local retention policy so the customer always has a version to fall back to without waiting for the next on-site visit.

"What would you cut if the first air-gapped delivery had to ship next week?"

I would cut multi-region niceties and automation, not verifiability. The first bundle can be produced by a manual pipeline run rather than a polished self-service job, and I can ship a single combined tarball with a hand-written load script instead of a slick installer.

What I would not cut is the OCI layout preserving signatures and SBOMs, the offline verification material, the signed checksum of the bundle, and the rollback runbook, because those are the trust and safety properties that justify an air-gapped delivery in the first place.

A rough but verifiable bundle beats a polished but unverifiable one. The automation and the layer-reuse optimisation to shrink bundle size are follow-ups for the second delivery once the process is proven.

Q124 · Scenario. "A production Docker host pages with the root filesystem at 100 percent. du shows 180 GB under /var/lib/docker. Containers are starting to fail writes. What is your sequence?"

Reveal answer

The real test Whether you can free space without killing healthy workloads, and whether you know which of the four usual culprits to check first.

Strong answer I would diagnose in this order:

  1. Get the breakdown before touching anything: docker system df -v reports images, containers, local volumes, and build cache with reclaimable amounts, and du -sh /var/lib/docker/* confirms whether the bytes are in overlay2, containers, volumes, or buildkit.
  2. Ranked causes on a long-lived host: container log files under containers/<id>/<id>-json.log with no max-size configured, which routinely reach tens of gigabytes; dangling images from months of deploys with no prune; anonymous volumes left behind by deleted containers; and writable-layer growth from an application that writes temp files inside the container instead of to a volume. On a CI host, BuildKit cache is the usual winner.
  3. Safe reclaim first: docker image prune -a --filter "until=168h" removes images not used by any container and older than a week, docker builder prune clears build cache, and docker volume ls -f dangling=true lists orphan volumes to review before deleting. Truncate an oversized log with truncate -s 0 rather than rm, because the daemon holds the file open and deleting it does not free the space.
  4. Then fix the cause: set "log-driver": "local" or json-file with "max-size": "50m" and "max-file": "5" in /etc/docker/daemon.json, which needs a daemon restart and applies only to new containers, so schedule recreation.
  5. Prevention: put /var/lib/docker on its own volume so a full image store cannot take down the operating system, alert at 80 percent, and run a nightly prune with a retention window on every host.

Land it Free the safe categories first, then remove the reason the disk filled, and never let Docker share a filesystem with the host's root.

Likely follow-ups
"You truncated the logs but df still shows the disk full. Why?"

Most likely because the daemon still holds the old file open, or the space is elsewhere.

If you deleted a log with rm instead of truncating it, the directory entry is gone but the daemon keeps the inode open, so the blocks are not freed until the process closes the file, which for a running container means never; lsof +L1 shows deleted-but-open files, and the fix is truncate -s 0 on the live file rather than rm.

If the logs really are truncated and the disk is still full, the bytes are in another category, overlay2 layers, volumes, or build cache, so I go back to docker system df -v and du -sh /var/lib/docker/* to find where.

A container writing to its writable layer keeps growing regardless of logs.

"How do you tell whether the growth is logs, images, volumes, or a runaway writable layer?"

docker system df -v splits it into images, containers, local volumes, and build cache with reclaimable amounts, which usually names the winner immediately.

To confirm and localise, du -sh /var/lib/docker/* shows which subtree holds the bytes: containers/ for logs, overlay2/ for image and writable-layer data, volumes/ for volume data, buildkit/ for cache.

For a runaway writable layer specifically, docker ps -s shows each container's writable size in the SIZE column, and the one with a multi-gigabyte "virtual" delta is the culprit.

That distinguishes an app writing temp files into the container, which needs a volume or tmpfs, from an oversized log, which needs a log rotation setting.

"What is the safest first thing to delete, and what do you never delete during an incident?"

Safest first is build cache, docker builder prune, which never affects running containers, and dangling images older than a week, docker image prune -a --filter until=168h, which removes only images no container uses. Truncating oversized logs is safe and immediate.

What I never do during the incident is docker system prune -a --volumes, because --volumes can delete a database's data and -a removes images that stopped-but-wanted containers need, and I never delete a volume without checking it is truly dangling.

I also do not restart the daemon to clear things until I have freed enough to act, because a restart under a full disk can leave containers unable to start. Reclaim the safe categories first, verify headroom, then address the cause.

"How do you make sure a full /var/lib/docker never takes down the OS again?"

By separating Docker's storage from the root filesystem and bounding what grows.

I put /var/lib/docker on its own dedicated volume or partition, so even if it fills to 100 percent the operating system's root, and therefore sshd and the ability to log in and fix it, is unaffected.

I set the log driver's max-size and max-file in daemon.json so container logs rotate and cannot grow unbounded, run a nightly prune with a retention window on every host, and alert at 80 percent of the Docker volume so it is addressed before it pages.

Together those turn a disk-full outage into a routine alert: growth is capped, cleanup is automatic, and the worst case is a full Docker volume rather than a wedged host.

Drill · Scanning, SBOMs, signing & vulnerability response

These questions test whether you can turn a wall of scanner output into a process that engineers actually follow, and whether you understand what a signature or an SBOM proves — and what it does not.

Q125 · Scenario. "Trivy reports about 340 CVEs on every one of our images. The team has stopped reading the reports. Security wants the pipeline to block on any critical finding starting Monday. What do you do?"

Reveal answer

The real test Whether you can cut the noise to a number humans act on, without either ignoring real risk or blocking every deploy on Monday.

Strong answer I would diagnose in this order:

  1. Understand where the 340 come from. Run trivy image --format json on three representative images and split the findings by layer. In my experience 80 to 90 percent sit in the base image's operating-system packages, many with no fix available, and a further chunk are in packages the application never loads. That is noise the app team cannot fix by editing their code.
  2. Collect the evidence that matters: how many findings have a fixed version available (--ignore-unfixed drops the rest), how many are critical or high (--severity CRITICAL,HIGH), and how many are reachable, which Trivy 0.6x and Docker Scout approximate by checking whether the vulnerable package is actually in the dependency tree the app uses.
  3. Ranked causes: a fat base such as ubuntu or full eclipse-temurin instead of a slim or distroless base, base images that have not been rebuilt in months, and application dependencies pinned years ago.
  4. Fix in two moves. First, move the fleet to a maintained golden base rebuilt weekly, which usually removes two thirds of the findings in one pull request. Second, gate on a rule people can defend: block on critical and high findings that have a fix available; warn on everything else. Use a .trivyignore.yaml for accepted exceptions, each with an owner, a reason, and an expired_at date so nothing is ignored forever.
  5. Prevention: make the gate green on Monday by running it in report-only mode for a week first, fixing the top offenders, and only then flipping --exit-code 1. Track a single number per service, open fixable critical and high findings, on a dashboard, and give it a 7-day service level for highs.

Land it A gate that blocks on 340 findings gets bypassed; a gate that blocks on 4 fixable ones gets fixed.

Likely follow-ups
"Security wants zero criticals, not zero fixable criticals. How do you handle an unfixable one?"

By making the exception explicit, time-bound, and owned rather than pretending it is fixed.

An unfixable critical, one with no upstream patch yet, goes in a .trivyignore.yaml entry with the CVE id, a reason, the owner, and an expired_at date a few weeks out, so it is suppressed for the gate but resurfaces automatically when the date passes or when a fix appears.

Alongside I assess reachability and mitigations: if the vulnerable code path is not used or is behind a control, I record that; if it is exploitable, I add a compensating control such as a network restriction and escalate.

I present security with the list of accepted exceptions and their expiries, so "zero criticals" becomes "zero unmanaged criticals", which is the achievable and honest version of their goal.

"How do you avoid the gate blocking every deploy on Monday morning?"

By running it in report-only mode for a week first and fixing the top offenders before it can block.

During that week the scan runs on every build, writes its findings, and fails nothing, so I see the real blocking set, which is usually a handful of fixable criticals concentrated in a couple of base images.

I fix those, typically by moving the fleet to a freshly rebuilt golden base that clears most of them in one change, then flip --exit-code 1 on the Monday with the exception file already populated for the genuinely unfixable ones.

So the gate goes live already green. Turning on a hard block cold, against 340 findings, guarantees every pipeline goes red and the gate gets disabled by lunchtime; the report-only soak is what makes it stick.

"Why do most of the 340 not matter, and how do you prove that to skeptical engineers?"

Because most sit in base-image operating-system packages the application never invokes, and many have no fix available, so they are neither the app team's to fix nor exploitable in context.

I prove it by splitting the scan: --ignore-unfixed drops everything with no patch, --severity CRITICAL,HIGH drops the low-severity noise, and Trivy's or Docker Scout's reachability analysis flags whether the vulnerable package is actually in the dependency graph the app loads.

Running those filters typically collapses 340 to a single-digit number of fixable, severe, reachable findings, and showing that reduction on a real image is more convincing than any argument.

Then the team acts on the four that matter instead of ignoring all 340, which is the behaviour the wall of noise created.

"What would you cut to ship the gate this week versus doing it properly?"

To ship this week I would cut reachability analysis and the per-service dashboard, and gate simply on fixable critical and high with the report-only soak and the exception file, which is the core that changes behaviour.

Reachability is valuable but adds tooling and tuning I do not need to start blocking on the genuinely fixable severe findings.

The dashboard and the runtime rescan loop are the "properly" version I would add over the following weeks so findings are tracked over time and routed to owners with service levels.

What I would not cut even for speed is the golden-base move, because without it the fixable-critical count stays high and the gate is painful; fixing the base is what makes the first Monday survivable.

Q126 · Design. "Design a vulnerability management process for container images across forty services and three teams."

Reveal answer

Strong answer Requirements: every deployed image is scanned continuously, not just at build time; findings are routed to a named owner; and the organisation has agreed service levels of 48 hours for critical, 7 days for high, and a monthly batch for the rest.

The design has three loops. The build loop runs Trivy or Grype in CI on every image, blocks on fixable critical and high, and uploads the scan result as an attestation on the image.

The runtime loop is a scheduled job, Harbor's built-in scanner or a Trivy Operator in the clusters, that rescans every digest currently running once a day against the fresh vulnerability database and writes results to one store.

The response loop reads that store, groups findings by base image versus application layer, and opens tickets automatically: base-image findings go to the platform team as one ticket, because rebuilding the golden base fixes all forty services, and application-layer findings go to the owning team with the fix version in the ticket title.

Exceptions are declared in code, a .trivyignore.yaml with expiry, and reviewed monthly. Trade-offs: a daily rescan of a few hundred digests costs little compute but produces churn when a database update reclassifies severity, so I report on fix-available findings only.

I would not scan on a single tool and trust its severity blindly, because Trivy and Grype disagree on around 10 to 20 percent of findings; I use one as the gate and the other as a periodic cross-check.

And I would not let teams silence findings in the pipeline configuration, because exceptions without expiry become permanent.

Land it Scan what runs, not just what you built; route base findings to the platform and app findings to the owner; and expire every exception.

Likely follow-ups
"Trivy and Grype disagree on a critical finding. Which do you believe?"

Neither blindly; I reconcile. The disagreement usually comes from different vulnerability databases and different severity sources, one taking the NVD score and the other the vendor's, or one detecting a package the other misses because of how it reads the metadata.

I look at the finding itself: the CVE, the fixed version, and whether the vulnerable package is actually present and reachable in the image, which I can confirm from the SBOM. I treat the union of both tools' findings as the candidate set for safety, use one as the enforcing gate for consistency, and run the other as a periodic cross-check so systematic gaps are visible.

When they disagree on severity specifically, I take the higher for triage and record which source it came from, because acting on the more cautious classification is cheaper than missing a real critical.

"How do you route a base-image finding differently from an app finding automatically?"

By the layer the finding sits in. The scanner reports which layer introduced each vulnerable package, and the base image's layers are known because the platform team built them, so a finding in a base layer is tagged base and one above it is tagged application.

The response loop groups by that tag: base findings become a single ticket to the platform team, because rebuilding the golden base fixes all forty consumers at once, and application findings go to the owning team with the fixed version in the ticket title.

I map image to owning team from a service catalogue. This is the key efficiency, because otherwise the same base CVE opens forty near-identical tickets across three teams and everyone assumes someone else owns it.

"Why scan what runs and not just what you build?"

Because vulnerabilities are discovered after build time, so an image that was clean when built accumulates findings as new CVEs are disclosed against packages it already contains.

Build-time scanning catches what is known that day; a running image three months old may have a dozen new criticals that no build ever saw.

The runtime loop rescans every currently-deployed digest daily against the fresh database, so the question "what severe, fixable issues are in production right now" has a current answer rather than a stale build-time one. It also catches images deployed outside the pipeline.

Build scanning gates new risk in; runtime scanning finds risk that appeared in what is already running, and you need both because neither sees the other's window.

"Exceptions without expiry become permanent. How do you enforce expiry in practice?"

By making the exception file the only place to suppress a finding and requiring an expired_at field the tooling honours.

Suppressions live in a version-controlled .trivyignore.yaml with the CVE, owner, reason, and expiry, and the scanner ignores an entry only until its date, after which the finding reappears and can block again.

A scheduled job lists entries expiring within the week and pings their owners, and a monthly review walks the whole file.

Crucially, teams cannot silence a finding by editing pipeline configuration or passing a flag, because the gate rejects out-of-band suppression, so every exception is in the reviewed file with a clock on it.

That combination, one suppression mechanism, mandatory expiry, and automated resurfacing, is what stops "temporary" exceptions living for years.

Q127. "What is an SBOM, how do you generate one for a container image, and what is the difference between SPDX and CycloneDX?"

Reveal answer

Strong answer A software bill of materials, SBOM, is a machine-readable inventory of every component inside an artifact: operating-system packages, language libraries with versions, and ideally the files they came from.

Its purpose is to answer "do we ship package X at version Y" without rescanning anything. For an image there are two ways to produce one.

Syft, the open-source tool behind Grype, walks the image layers and detects packages from dpkg or apk databases, Maven and npm manifests, Python metadata, and Go build info.

Alternatively BuildKit can generate it at build time with docker buildx build --sbom=true, which runs a Syft-based scanner inside the build and attaches the result to the image as an attestation, a signed document stored next to the manifest.

Build-time generation is better because it can see build stages and source paths that vanish from the final image. The two formats are both open standards.

SPDX is the older Linux Foundation and ISO standard, centred on licence compliance and file-level inventory; CycloneDX comes from OWASP, is security-centred, and has richer fields for vulnerabilities, services, and dependency graphs.

Most tools emit either, most consumers accept either, and regulators in the United States and the European Union accept both. Pick one house format, CycloneDX in most engineering organisations, and convert when a customer asks.

sbom.sh
docker buildx build --sbom=true --provenance=true \
  --tag registry.internal/team/api:git-3f9a2c1 --push .
docker buildx imagetools inspect registry.internal/team/api:git-3f9a2c1 \
  --format '{{ json .SBOM }}' > api-sbom.json
syft registry.internal/team/api:git-3f9a2c1 -o cyclonedx-json > api-cdx.json
grype sbom:api-cdx.json --fail-on high

Land it An SBOM is the inventory that makes the next zero day a query instead of a rescan, and attaching it at build time is the only way it stays attached to the exact digest.

Likely follow-ups
"Why is a build-time SBOM better than scanning the final image later?"

Because the build sees things the final image has erased.

A multi-stage build compiles in one stage and copies artifacts to a slim final stage, so scanning the final image cannot see the build-stage toolchain, the source paths, or dependencies that were vendored and then stripped, and it can misattribute a library whose metadata was removed.

The build-time scanner runs inside the build with full visibility of each stage, so it records the real provenance of every component and the source files they came from.

It also attaches the SBOM to the image as a signed attestation at that moment, bound to the exact digest, so it cannot drift or be lost.

Scanning later is a fallback that works but produces a less complete inventory and one that is not cryptographically tied to the image.

"When would you choose SPDX over CycloneDX or vice versa?"

I default to CycloneDX because it is security-centred, with first-class fields for vulnerabilities, dependency relationships, and services, which is what an engineering organisation uses an SBOM for day to day.

I choose SPDX when the driver is licence compliance or a customer or regulator that standardised on it, since SPDX is the older ISO standard and is strong on file-level inventory and licence expressions.

In practice most tools emit either and most consumers accept either, and converters exist, so I pick one house format, generate everything in it, and convert on demand when a specific customer asks for the other.

The format matters far less than generating the SBOM at build time and keeping it attached; arguing formats is a distraction from that.

"How do you keep the SBOM attached to the exact image through promotion?"

By attaching it as an attestation on the digest and promoting by digest only.

docker buildx build --sbom=true or cosign attest --type cyclonedx stores the SBOM as a referrer artifact tied to the manifest digest, not to a tag, so it travels with the image as long as the digest is preserved.

Promotion uses crane tag or cosign copy, which keep the digest and copy the referring attestations, so the production image carries the same SBOM the build produced. A pull-tag-push would change the digest and orphan the attestation, so it is banned.

Verification at deploy time checks the SBOM attestation exists for the running digest, which both confirms it is attached and gives the audit trail. Digest-addressability is what makes "attached forever" true.

"An auditor asks for the SBOM of an image from a year ago. Can you produce it?"

If it was attached at build time and the registry retention kept the digest, yes: I fetch the attestation for that digest with cosign download attestation or docker buildx imagetools inspect, and it is the exact inventory as built.

That is the whole reason for build-time attachment and for a retention policy that keeps released digests for the audit window, eighteen months or more.

If the image predates the SBOM practice, I can regenerate one by running Syft against the archived digest, which still exists in the registry, though it will be the later-scan quality, less complete for multi-stage builds, and I would flag it as regenerated rather than original.

The lesson I would draw for the auditor is that build-time attestation plus digest retention is what makes historical SBOMs reliable.

Q128 · Scenario. "It is Tuesday. Compliance needs an SBOM for every image currently deployed in production by Friday, and none of our pipelines produce one. How do you deliver?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Reframe the symptom: the need is an inventory for what runs today, not a pipeline change. Those are separable, and only the first has a Friday deadline.
  2. Collect the list of deployed digests, not tags. Across Kubernetes clusters that is kubectl get pods -A -o jsonpath pulling status.containerStatuses[*].imageID; on plain Docker hosts it is docker ps --no-trunc --format '{{.Image}}' with docker inspect for the repo digest. Deduplicate; forty services usually collapse to fifty or sixty unique digests including sidecars.
  3. Generate SBOMs from the registry, not from nodes: a loop over the digests running syft registry.internal/team/api@sha256:… -o cyclonedx-json takes seconds per image and does not need the source. Attach each result to its digest with cosign attest --type cyclonedx, so it lives beside the image and can be verified later, and also export the files to a bucket for the compliance team.
  4. Ranked risks: images with no matching manifest in the registry because someone deployed from a laptop, third-party images with obscure packaging that Syft cannot fully read, and base images so old the package database is incomplete. Flag those explicitly in the deliverable rather than hiding them.
  5. Fix the pipeline in the same week, because the question will return: add --sbom=true --provenance=true to every buildx call, which is a one-line change in a shared pipeline template.
  6. Prevention: an admission policy in E10 that requires an SBOM attestation, so an image without one cannot reach production again.

Land it Generate from the registry for Friday, attach at build time for forever, and be honest in the report about the images you could not fully read.

Likely follow-ups
"Why generate from deployed digests rather than from the source repositories?"

Because the deadline is about what runs, and the source repositories may not correspond to what runs.

A repository's current main branch might be ahead of production, a service might be deployed from an old commit, and something might be running that was built from a branch or a laptop.

Generating from the actual deployed digests, collected from the clusters and hosts, guarantees the SBOM matches the bytes in production, which is what compliance is asking about.

It is also faster: Syft against a registry digest takes seconds and needs no checkout, build, or per-repo tooling, so fifty or sixty unique digests are done in an hour.

Source-based generation would require building every service, which is slower and produces an inventory of a build that may not be the deployed one.

"You find an image running that has no manifest in the registry. What do you do?"

Flag it loudly in the deliverable and chase its origin, because it is both a compliance gap and a security one.

An image running with no registry manifest was almost certainly built and loaded outside the pipeline, from a laptop with docker save and load or a direct build on the node, which means it was never scanned, signed, or provenanced.

I generate an SBOM by scanning the running image directly, syft against the container or its local image, so the compliance list is complete, and I mark it as out-of-band with the node and owner.

Then the follow-up is an admission policy that refuses to run any image not present in the internal registry with an attestation, so this cannot recur, which is the real fix behind the immediate scramble.

"How do you fix the pipeline so Friday's scramble never repeats?"

One line in the shared build template: add --sbom=true --provenance=true to every buildx call, so from then on every image carries an attested SBOM tied to its digest at build time.

Because the pipeline is a reusable template the forty services inherit, that single change covers the fleet without forty pull requests.

Then an admission policy requires an SBOM attestation for anything deployed to production, so an image without one cannot reach production and the "none of our pipelines produce one" state becomes impossible.

The Friday deliverable was a one-off inventory; the durable fix is generate-at-build plus enforce-at-deploy, which turns the next compliance request into a query against attestations rather than a scramble.

"Compliance also wants it signed and tamper-evident. How does that change the delivery?"

I attach each generated SBOM to its digest as a signed attestation with cosign attest --type cyclonedx rather than only exporting loose JSON files, so each inventory is cryptographically bound to the exact image and signed by an identity, and anyone can verify later with cosign verify-attestation that it was not altered.

For the Friday deliverable I also export the files to a bucket for the compliance team's convenience, but the authoritative copy is the attestation in the registry.

That satisfies tamper-evidence because a changed SBOM would fail signature verification, and it satisfies "for the running image" because the attestation is on the digest that is deployed. It is only a small addition to the digest-scanning loop, the attest step after each syft run.

Q129 · Scenario. "A Log4Shell-class zero day drops at 14:00. Leadership wants to know within the hour which of our forty services are affected and which are already patched. How do you answer?"

Reveal answer

The real test Whether you have an inventory to query, and whether you distinguish "contains the library" from "is exploitable".

Strong answer I would diagnose in this order:

  1. Pin down the symptom precisely: the affected package name, the vulnerable version range, and the fixed version, from the vendor advisory rather than from social media. For Log4Shell that was log4j-core from 2.0 to 2.14.1 with a fix in 2.15 and then 2.17.
  2. Query the inventory rather than scanning. If SBOMs are attached to images, one query across the SBOM store, or grype sbom: against each stored file with the new database, gives the list of digests containing the package in minutes. Cross that with the list of running digests from the clusters, and you have "deployed and affected". Without SBOMs, the fallback is trivy image over every running digest in parallel, which for sixty digests takes twenty to thirty minutes on a couple of runners.
  3. Ranked traps: shaded or repackaged jars where the package is renamed and only a class-path search finds it; images that include the library in a build stage but not the final stage, which is a false positive; and vendor images where the fix arrives only when the vendor rebuilds.
  4. Fix: for services we build, bump the dependency, rebuild through the normal pipeline, and promote by digest with a fast-tracked review; for vendor images, apply the documented mitigation such as an environment variable or a removed class, and track the vendor fix. Order the rollout by exposure: internet-facing services first.
  5. Prevention: the reason the answer took one hour instead of one day is the SBOM inventory, so if we did not have it, that becomes the follow-up action, along with a rehearsed runbook for exactly this question.

Land it The hour is spent querying an inventory you built earlier; if you are scanning at 14:05, you are already late.

Likely follow-ups
"You have the list of images containing the library. How do you separate 'contains' from 'exploitable'?"

By checking whether the vulnerable code path is reachable and reachable from untrusted input, not just present.

For Log4Shell specifically, an image containing log4j-core in the vulnerable range is a candidate, but exploitability depended on JNDI lookups being enabled and on attacker-controlled strings reaching the logger, so a service that never logs external input, or runs with the mitigation flag, is far lower risk.

I use reachability analysis from the scanner where available, then confirm by asking whether the service is internet-facing and whether user input flows to logging. I order remediation by that exposure: internet-facing and exploitable first, internal and not-reachable last.

Reporting "forty contain it" without that split panics leadership; "six are exploitable and internet-facing" is the answer they can act on.

"What are the false positives and false negatives you specifically watch for?"

False positives: a library present only in a build stage but not the final image, which a final-image scan correctly ignores but a source scan flags; and a vendored copy the scanner double-counts. False negatives are the dangerous ones: a shaded or repackaged jar where the vulnerable classes are relocated under a different package name, so a name-based scan misses them entirely, which for Log4Shell meant a class-path or class-file search for the actual JndiLookup class rather than the package name; and statically linked or bundled dependencies in a single binary that the package scanner cannot see. So I supplement the SBOM query with a content search for the vulnerable class or symbol in the suspect images, because the repackaged case is exactly where a purely metadata-driven inventory lies.

"Without an SBOM inventory, how long does this actually take and what do you do?"

Without an inventory it is twenty to thirty minutes of parallel scanning rather than minutes of querying, which for a one-hour deadline is survivable once but not a plan.

I collect the running digests from the clusters, then run trivy image against all sixty in parallel across a couple of runners filtered to the specific CVE, and cross the hits with the internet-facing list. Meanwhile I do the content search for the repackaged case.

It works, but it is slower, noisier, and it is the exact situation the SBOM store exists to prevent, so the incident's follow-up action is to attach SBOMs at build time and stand up the store, so the next zero day is a query.

Being honest that "we were scanning at 14:05" is the gap, not the method, matters.

"For vendor images you cannot rebuild, what is the play?"

Apply the documented mitigation now and track the vendor fix in parallel.

For a library flaw in a vendor image, the mitigation is usually a configuration change I can apply without rebuilding, an environment variable disabling the vulnerable feature, a JVM flag, or removing the offending class from the jar at deploy time via an init step, exactly what teams did for Log4Shell with log4j2.formatMsgNoLookups and class removal.

I also constrain it at runtime, egress network policy so even a successful exploit cannot call out, which for Log4Shell's JNDI callback was itself a strong mitigation. Then I open a ticket against the vendor for a patched image and hold them to it.

So the play is: mitigate by config, contain by network, and chase the real fix, rather than waiting helplessly for the vendor.

Q130 · Design. "Design supply-chain security for container images at a regulated organisation: SBOM, signing, provenance, and enforcement at deploy time."

Reveal answer

Strong answer Requirements: auditors must be able to prove for any running image who built it, from which commit, with which base and dependencies, and that nothing changed between build and deploy. The design layers four things onto the pipeline from the build-pipeline design.

Every buildx call runs with --sbom=true --provenance=mode=max, so the image carries an SBOM attestation and a SLSA provenance attestation, which is a signed record of the builder identity, source repository, commit, and build parameters.

The pipeline then signs the digest with cosign in keyless mode: the CI job authenticates to Sigstore's Fulcio with its OpenID Connect identity, receives a short-lived certificate bound to that identity, signs, and the signature is recorded in the Rekor transparency log.

There is no private key to leak or rotate.

At deploy time an admission controller, Kyverno or Sigstore's policy controller as covered in E10, verifies three things before a pod is admitted: a valid signature from the CI identity for the exact digest, a provenance attestation whose source repository is in our organisation, and an SBOM attestation present.

Trade-offs: keyless signing depends on the Sigstore services being reachable at build time and on Rekor at verify time, so I cache verification results and allow a short grace window during outages.

What I would not do is sign with a long-lived key stored in CI secrets, because that key becomes the single thing an attacker needs, and I would not enforce in audit mode forever, because a control that only logs is not a control.

Land it Provenance says where the image came from, the signature says nobody touched it since, the SBOM says what is inside, and admission is where those claims finally cost an attacker something.

Likely follow-ups
"Keyless signing depends on Sigstore being reachable. What happens during a Sigstore outage?"

Two different impacts at two times.

At build and sign time, if Fulcio or Rekor is unreachable, signing fails, so builds cannot be signed and, with a strict admission policy, cannot deploy; I mitigate by caching and by allowing a documented break-glass path where an on-call approver can promote a build with a recorded exception.

At verify time, admission needs to check the signature and the Rekor proof, so I cache verification results per digest so an already-verified image keeps deploying during an outage, and I use the offline verification bundle, the signed entry timestamp and inclusion proof captured at signing, so verification does not require live Rekor.

For a regulated org I would also consider running a private Sigstore stack, self-hosted Fulcio and Rekor, so availability is under our control rather than a public service's.

"Why is provenance mode=max worth the extra build cost?"

Because it records the full build context an auditor and an incident responder actually need: the builder identity, the source repository and exact commit, the build parameters, and the materials, the base images and dependencies consumed, whereas the default mode records only a minimal subset.

For a regulated organisation the requirement is to prove for any running image who built it, from which commit, with which base, and mode=max is what makes that provable rather than partially inferred.

The extra cost is some build time and attestation size, which is small against the value of being able to answer an audit or trace a supply-chain incident to its source.

I would accept the cost fleet-wide because the whole design exists to make those claims verifiable, and a partial provenance undercuts that.

"An auditor asks you to prove a specific running pod's full chain. Walk me through it."

Start from the running digest: kubectl get pod -o jsonpath for its imageID gives the exact sha256. Then cosign verify against that digest with the production identity flags proves a valid signature from the CI workflow, so nobody tampered with it since build.

cosign verify-attestation --type slsaprovenance returns the provenance, showing the builder, the source repo, and the commit, which I cross-check against the Git history and the reviewed pull request. cosign verify-attestation --type cyclonedx returns the SBOM, listing every component and version.

Together those answer who built it, from which commit and base, what is inside, and that it is unchanged, each backed by a signature recorded in the transparency log.

The admission policy that let it run enforced exactly these checks, so the pod running is itself evidence the chain held.

"Audit-mode admission is not a control. How do you move to enforcing without an outage?"

By running in audit mode long enough to fix the violations it surfaces, then enforcing in stages.

Audit mode logs what would be rejected without blocking, so I collect the list of images that lack signatures, provenance, or SBOMs, and drive it to zero by fixing the pipelines and re-signing the stragglers.

Then I enforce namespace by namespace, starting with the least critical, watching for unexpected rejections, with a documented break-glass exception for emergencies. I keep the cached verification and offline bundle so a Sigstore hiccup does not become a deploy outage.

Only when a namespace has run clean in audit for a full cycle does it flip to enforce. That way enforcement never rejects a legitimate deploy by surprise, because everything it would reject was already fixed while it was only logging.

Q131. "Explain keyless signing with cosign. What does verification actually check, and what does a valid signature not prove?"

Reveal answer

The real test Whether you can explain the trust chain without a key, and whether you know the limits of what a signature asserts.

Strong answer Traditional signing needs a long-lived private key, and the hard part is protecting and rotating it. Keyless signing replaces the key with an identity.

The signer, usually a CI job, obtains an OpenID Connect token, a signed statement from the CI provider saying which repository and workflow is running.

cosign sends that token to Fulcio, Sigstore's certificate authority, which issues a certificate valid for about ten minutes that binds a freshly generated key pair to that identity.

cosign signs the image digest with the ephemeral private key, then uploads the signature and certificate to the registry beside the image and records the whole event in Rekor, an append-only transparency log. The private key is then discarded.

Verification with cosign verify checks that the signature matches the digest, that the certificate chains to Fulcio's root, that the certificate's identity matches the expected value, which you must pass as --certificate-identity and --certificate-oidc-issuer, and that a Rekor entry proves the signature was made while the certificate was valid.

What it does not prove: that the source code was reviewed, that the build was free of malicious dependencies, or that the image is safe to run. It proves only that a specific identity produced this exact digest.

That is why provenance and SBOM attestations sit beside it. As of Aug 2026 cosign 2.x is the widely deployed line and 3.x moves the default to the newer bundle format, so verification commands should pin the version they expect.

sign-and-verify.sh
cosign sign --yes registry.internal/team/api@sha256:9f1c2e7a4b3d5c6e8f0a1b2c3d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5a6
cosign verify \
  --certificate-identity-regexp '^https://github.com/acme-org/api/\.github/workflows/build\.yml@refs/heads/main$' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  registry.internal/team/api@sha256:9f1c2e7a4b3d5c6e8f0a1b2c3d4e5f60718293a4b5c6d7e8f9a0b1c2d3e4f5a6

Land it A signature is a claim about who, bound to a digest; if you forget to pin the expected identity at verify time, any Sigstore user's signature passes.

Likely follow-ups
"You forgot to pin the identity at verify time. What actually happens?"

Verification passes for any signature made by any Sigstore user, which is effectively no verification at all.

Keyless signing binds the signature to an identity in a Fulcio certificate, but cosign verify only checks that identity if you pass --certificate-identity and --certificate-oidc-issuer; without them it confirms the signature chains to Fulcio and has a Rekor entry, which any signature from anyone satisfies.

So an attacker who can push an image to your registry could sign it with their own GitHub Actions workflow and your unpinned verify would accept it.

The fix is to always pin the expected identity, ideally as a regexp matching your organisation's repository and workflow and the correct issuer, and to test the policy by trying to verify an image signed by a different identity and confirming it fails.

"What exactly does a valid signature prove and not prove, in one breath?"

It proves that a specific identity, a particular CI workflow in a particular repository, produced this exact image digest, and that the signing happened while that identity's certificate was valid, recorded immutably in the transparency log.

It does not prove the source code was reviewed, that the dependencies were safe, that the build was free of a compromised runner, or that the image is safe to run at all.

It is a claim about who and which bytes, nothing about quality or safety. That is precisely why provenance sits beside it to say where it came from and the SBOM to say what is inside, and why runtime controls still contain a signed-but-malicious image. Treating a signature as a safety certificate is the common misunderstanding.

"When would you use keyed signing instead of keyless?"

When I cannot depend on Sigstore's public services at verify time or at all, or when policy requires a self-contained trust root.

An air-gapped customer cannot reach Fulcio or Rekor, so I sign with a key whose public half I ship, and they verify offline against it with no transparency log needed.

A regulated environment that forbids external dependencies might mandate keyed signing with keys in an HSM, or a self-hosted Sigstore.

The cost of keyed signing is the hard part keyless was invented to remove: protecting and rotating the private key, which becomes the single thing an attacker needs.

So my default is keyless with pinned identities for the internal fleet, and keyed signing only where offline verification or a controlled trust root is a hard requirement.

"cosign 2.x versus 3.x — why does the version matter for verification?"

Because the default bundle and format changed, and a verifier and signer on mismatched major versions can fail to agree on how the signature and its proofs are stored.

As of Aug 2026, 2.x is the widely deployed line and 3.x is rolling out with the newer bundle format as the default, so a signature produced by 3.x may not verify with an old 2.x client unless flags align, and vice versa.

The practical rule is to pin the cosign version in both the signing pipeline and the admission verifier so they match, and to plan the upgrade as a coordinated change rather than letting signer and verifier drift.

Version-pinning the tooling is part of the same discipline as digest-pinning the images: reproducible, coordinated, and not left to whatever is newest that day.

Q132 · Design. "Design a container hardening baseline and the way you would enforce it in CI, without becoming the team everyone routes around."

Reveal answer

Strong answer Requirements: a short, written baseline that fits on one page, automated checks that fail fast with a message telling the developer what to change, and an exception path with an expiry.

The baseline itself: images run as a non-root user declared with USER; base images come only from the internal golden set and are pinned by digest; no latest anywhere; no secrets in build arguments or layers; a HEALTHCHECK or an equivalent probe; no package managers left in the final stage; read-only root filesystem and dropped capabilities at runtime; and a size budget per language, for example under 300 MB for a Java service on a JRE base.

Enforcement has three layers. Hadolint lints the Dockerfile in the pull request for the static rules such as DL3007 for latest tags and DL3002 for last user root, and it supports inline ignores that I require to carry a ticket reference.

Conftest runs Open Policy Agent rules against the built image's config JSON from docker buildx imagetools inspect or against the compose and Kubernetes manifests, checking the runtime settings that a Dockerfile cannot express. Trivy's misconfiguration scanner covers the overlap.

All three run in a shared pipeline template so teams inherit them without copying YAML. The trade-off is friction: a rule that blocks without a fix hint gets bypassed, so each rule's failure message includes the remediation and a link.

What I would not do is enforce with a manual security review before each release, because that scales with headcount and not with services, and I would not enforce only at admission, because a failure discovered at deploy time is the most expensive place to learn about a missing USER line.

.hadolint.yaml
failure-threshold: warning
trustedRegistries:
  - registry.internal
override:
  error:
    - DL3002
    - DL3007
    - DL3026
ignored:
  - DL3008

Land it The baseline is ten rules on one page, enforced by three tools in a template, each failure saying how to fix it — that is what makes it a guardrail instead of a gate.

Likely follow-ups
"How do you keep a failure message from being useless, concretely?"

By making every rule output the remediation, not just the violation.

A Hadolint failure for DL3007 should not say "latest tag" and stop; the pipeline wraps it to print "Pin the base image by digest: replace FROM node:latest with FROM node:22@sha256:..., see the golden-base list at this link".

A Conftest policy failure prints the exact field and the required value: "container.securityContext.runAsNonRoot must be true; add it to the deployment". Each message names what to change, where, and links the one-page baseline.

I test the messages by having someone unfamiliar with the rule read a failure and fix it without asking me.

A gate that says only "policy violation: rule 14" is the gate people route around, so the message quality is not cosmetic, it is what determines whether the control survives.

"Hadolint checks the Dockerfile but not runtime settings. How do you cover those in CI?"

With Conftest running Open Policy Agent rules against the runtime configuration, not the Dockerfile.

For the built image I feed docker buildx imagetools inspect --format '{{json .}}' or the image config JSON into Conftest to check things like the effective User, and for deployment I run the Compose or Kubernetes manifests through it to check read_only, cap_drop, no-new-privileges, resource limits, and the registry allow-list, since those live in the manifest, not the Dockerfile.

Trivy's misconfiguration scanner covers much of the same ground as a cross-check.

So Hadolint owns the static Dockerfile rules, Conftest owns the runtime and manifest rules, and they run together in the shared template, giving coverage that a Dockerfile linter alone cannot because the Dockerfile cannot express runtime settings.

"How do you roll a new rule out without breaking forty pipelines overnight?"

Warn first, enforce later, and version the template. A new rule ships in the shared pipeline template at warning severity, so it reports on every build without failing any, and I watch how many services would break.

I fix or exempt the violators, communicate the enforce date, and only then raise the rule to error.

Because the template is versioned and consumed by reference, services adopt the change when they pick up the new template version, which I can stage across teams rather than flipping everyone at once. Genuinely blocked services get a time-bound exception with a ticket.

This is the same warn-then-enforce discipline as the scanning gate, and it is what keeps the security team from being the team everyone routes around, because nobody wakes up to a red pipeline they had no warning about.

"What would you cut to keep the baseline to one page?"

Anything that is not a rule with a clear pass or fail and a real risk behind it.

I keep the high-value, checkable rules: non-root user, digest-pinned golden base, no latest, no build-arg secrets, a health probe, no package manager in the final stage, read-only root with dropped capabilities, and a size budget.

I cut aspirational guidance, best-practice essays, and rules I cannot automate a check for, because an unenforced rule on the page is noise that dilutes the enforced ones. I also cut anything the default runtime profiles already handle, since restating them adds length without adding control.

The test is: can a tool check it and can a developer fix it from the message. If not, it does not belong on the one page that engineers are expected to actually meet.

Q133 · Design. "Design the golden path for a new service on your developer platform: templates, Dockerfile, pipeline, policy. What is opinionated and what is left open?"

Reveal answer

Strong answer Requirements: a developer should get from an empty repository to a scanned, signed image running in a development environment in under thirty minutes without reading a wiki, and the platform team should be able to change the build and security rules for all services in one place.

The design is a template repository per language, Java on a Temurin JRE base, Go on distroless, Python on a slim base, each containing a multi-stage Dockerfile with the build stage, the runtime stage, a non-root user, a health endpoint, and a .dockerignore.

The pipeline is a reusable workflow the service repository calls with three parameters: the pipeline builds with BuildKit, tags with the git SHA, generates SBOM and provenance, scans with Trivy, signs with cosign, and pushes to the team's repository in the internal registry.

Policy runs in the same workflow: Hadolint on the Dockerfile, Conftest on the manifests, and the registry allow-list. Opinionated and fixed: base images, tagging scheme, signing, scanning thresholds, the registry.

Left open: the language build tool, application configuration, and the choice to leave the golden path entirely if a team accepts owning the pipeline and passing the same policies. Trade-off: templates drift, so I version them and a monthly job opens update pull requests.

What I would not do is ship a platform CLI that hides the Dockerfile, because when the abstraction breaks at 02:00 the on-call engineer needs a file they can read, and I would not make the path mandatory, because a golden path that people cannot leave is a cage and gets resisted.

Land it Fix the parts that carry risk — bases, signing, scanning, registry — and leave the parts that carry product judgment to the team.

Likely follow-ups
"A team wants to leave the golden path. What is the deal you offer?"

They can leave, but they own what they take on, and they still meet the same outcomes.

The golden path is opinionated but not a cage: a team with a real need, an unusual language, a special build, may run their own pipeline, provided it still produces a scanned, signed, SBOM-attested image from an approved base and passes the same admission policies.

What they give up is the platform team maintaining it for them; what they keep is the freedom to do it their way.

I make the deal explicit so leaving is a considered choice, not a silent fork, and I keep the path attractive enough that few want to leave.

A golden path people cannot leave gets resented and worked around; one they may leave but rarely do is a sign it is actually good.

"What do you deliberately leave open, and why not standardise everything?"

I leave open the parts that carry product judgment rather than risk: the language build tool and its configuration, the application's own structure, the choice of framework, and the runtime configuration values.

Standardising those buys nothing for security or reliability and costs teams the ability to make sensible product decisions, which breeds resentment and workarounds.

I fix the parts that carry cross-cutting risk: the base images, the tagging and signing, the scanning thresholds, and the registry, because a mistake there affects the whole fleet and the platform team can fix it in one place.

The principle is to be opinionated exactly where a wrong choice is expensive and shared, and permissive where a choice is local and reversible, so the path constrains risk without constraining judgment.

"Why not a platform CLI that hides the Dockerfile entirely?"

Because when the abstraction breaks, and it will, at 02:00, the on-call engineer needs a file they can read and reason about, and a hidden Dockerfile generated by a CLI leaves them debugging a black box under pressure.

Buildpacks and hide-the-Dockerfile platforms are attractive for the happy path, but the failure modes, a native dependency that will not build, a base that needs a tweak, a size problem, are exactly when the generated layer becomes an obstacle.

So I ship a real, readable, multi-stage Dockerfile in the template that teams own and can edit, with the opinionated parts pinned.

The template gives the productivity of a generated file with the debuggability of a real one, which is the trade I want, since the whole point of the golden path is speed without giving up the ability to fix things.

"How do you keep the templates from drifting away from the services that used them?"

By versioning the templates and pushing updates as reviewable pull requests rather than expecting teams to notice.

Each template repository is versioned, and a monthly job, driven by Renovate or a custom bot, opens a pull request in every service that was scaffolded from it, bringing the Dockerfile, pipeline reference, and policy config up to the current version, with the changelog in the description.

Teams review and merge on their own schedule, and CI runs their tests on the update so a breaking change is caught. Services that have diverged intentionally show a conflict, which surfaces the drift for a conversation.

So drift becomes a visible, managed stream of small pull requests instead of forty snapshots that silently rot, which is the same bump-bot pattern used for base images applied to the scaffolding itself.

Drill · Build pipelines, base images, promotion & multi-arch

These questions test whether you can make forty services build fast, build the same way every time, and reach production as the exact bytes that were tested — on every CPU architecture you run.

Q134 · Design. "Design the image build pipeline for forty services. Assume a monorepo, but tell me what changes if it is forty repositories."

Reveal answer

The real test Whether you build once and reuse, whether the cache design is explicit, and whether you know the monorepo's hard problem is change detection.

Strong answer Requirements: a merge to main produces a scanned, signed image per changed service in under ten minutes, builds are reproducible from the git SHA, and every artifact is traceable to a commit.

Design for the monorepo: a single docker-bake.hcl declares one target per service with its context, Dockerfile, and shared settings, so docker buildx bake builds any subset in parallel inside one BuildKit session with shared cache.

Change detection runs first: a script diffs the merge against the previous main build and lists the services whose directories or shared libraries changed, and only those targets are built. Every image is tagged git-<sha>.

Cache is a registry cache with --cache-to type=registry,mode=max and --cache-from on the same reference, so any runner, cold or warm, starts from the last build's layers. BuildKit runs as a remote builder, so CI jobs never need a privileged Docker daemon.

After the build, SBOM and provenance attestations are attached, Trivy gates, cosign signs, and the digests are written to a release manifest that the deploy pipeline consumes.

With forty repositories the mechanics are the same but the bake file becomes a shared reusable workflow, change detection becomes trivial because every push is one service, and the cost moves to keeping forty pipelines on the same template version.

Trade-off: registry cache adds 10 to 30 seconds of push time per build, in exchange for cold-runner builds dropping from minutes to seconds.

What I would not do is docker-in-docker with --privileged runners, or build once per environment, because both destroy the traceability that the rest of the design depends on.

Land it Bake for parallelism, registry cache for cold runners, change detection for the monorepo, and one git SHA on every image so you can always answer "what is this".

Likely follow-ups
"How does change detection actually decide which services to build in the monorepo?"

By diffing the merge against the last successful main build and mapping changed paths to services, including shared dependencies.

The script runs git diff --name-only between the current commit and the last built commit, then maps each path to the service that owns it via the directory layout, and crucially expands shared libraries to their consumers, so a change to a common module rebuilds every service that depends on it, which a naive per-directory rule would miss.

It builds only that set of bake targets. I store the last-built commit as metadata so the comparison is reliable across runners.

The hard part of the monorepo is exactly this dependency-aware detection, because building everything on every merge is slow and building only the touched directory misses shared-code changes, and both failure modes are worse than getting the graph right.

"Why registry cache and not a local layer cache on the runner?"

Because every job runs on a fresh runner with an empty local store, so a local cache is cold every time and buys nothing.

A registry cache, --cache-to type=registry,mode=max and --cache-from against the same reference, stores the layers in the registry, so any runner, however fresh, pulls the previous build's layers and starts warm. mode=max caches intermediate stage layers too, not just the final image, which matters for multi-stage builds.

The cost is 10 to 30 seconds of push per build to store the cache, and the payoff is cold-runner builds dropping from minutes to seconds.

On persistent runners a local cache would also work, but a fleet of ephemeral runners is common and the registry cache is what makes it fast, so I design for the ephemeral case and treat any local cache as a bonus.

"What changes concretely if it is forty repositories instead of a monorepo?"

Change detection becomes trivial because every push is inherently one service, so the dependency-diffing machinery disappears, but the cost moves to consistency across forty pipelines.

The bake file per service becomes a shared reusable workflow that all forty repositories call with a few parameters, and the effort is keeping them on the same template version, which I handle with the bump-bot pattern opening update pull requests.

Shared libraries become versioned packages consumed through the package manager rather than source in the same tree, so a shared-code change is a package release plus dependency bumps rather than an automatic multi-service rebuild. Cross-service atomic changes get harder, since they span repositories.

The build mechanics, bake, registry cache, attestations, scan, sign, are identical; only change detection gets simpler and cross-cutting consistency gets harder.

"How do you keep traceability from image back to commit across all this?"

Every image is tagged with the git SHA it was built from, git-<sha>, and carries a provenance attestation recording the source repository, commit, and build parameters, so the chain from any running digest back to its exact commit is machine-verifiable, not inferred.

The release manifest the deploy pipeline consumes lists digest against SHA, and the deployment references the image by digest with the SHA in an annotation for humans.

Because I build once per commit and promote by digest with no rebuild, the digest in production is the same one that was tested, so traceability is not broken by a re-tag or a re-build.

That single-build-per-commit rule, plus the SHA tag and the provenance, is what lets me answer "what is this image and where did it come from" for anything in the fleet, which is the property the whole pipeline exists to guarantee.

Q135 · Scenario. "Our CI image builds take 25 minutes. Developers say 'it's just Docker being slow'. Every job runs on a fresh runner. Where do you look?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Measure before guessing. Run one build with --progress=plain and read the per-step timings, then check the runner's network with a single docker pull of the base image timed by hand. A fresh runner has an empty layer store and an empty build cache, so on every job Docker downloads the base image, re-runs every dependency install, and re-compiles from scratch.
  2. Evidence to collect: size of the base image, whether the Dockerfile copies the whole source before installing dependencies, which forces a dependency reinstall on every commit, whether .dockerignore exists, because sending a 2 GB context with node_modules or target costs minutes on its own, and whether any cache flags are present at all.
  3. Ranked causes: no external cache, so every layer rebuilds; poor layer order, so even a cached build invalidates at the source copy; a fat base pulled cold from Docker Hub across the internet; and heavy build tools such as a full Maven dependency resolution with no mounted cache.
  4. Fix, in order of payoff: add --cache-from and --cache-to type=registry,mode=max against the internal registry, which alone usually turns 25 minutes into 3; reorder the Dockerfile so dependency manifests are copied and installed before the source; add RUN --mount=type=cache,target=/root/.m2 so package downloads persist across builds; point the base image at the pull-through cache in the same region; and write a .dockerignore.
  5. Prevention: a build-time budget in the pipeline that alerts when a service crosses five minutes, and a remote BuildKit builder shared by all jobs so the cache is warm without any per-job download at all.

Land it Docker is not slow; a cold cache is slow, and the fix is to give the cache a home that outlives the runner.

Likely follow-ups
"You added registry cache and it is still slow. Where do you look next?"

At whether the cache is actually hit, then at layer order.

I read --progress=plain output for CACHED lines; if the dependency-install step is not cached, the cache key is being invalidated, usually because the source is copied before dependencies are installed, so any code change busts the dependency layer.

The fix is to copy only the dependency manifests, install, then copy the source.

If layers are cached but the build is still slow, I look at the non-cacheable work: a fat base pulled cold, a huge build context because .dockerignore is missing, or a test suite running inside the build.

I also check the cache backend's own latency, since a slow or cross-region registry makes --cache-from itself slow. Measuring each step's timing tells me which of these it is rather than guessing.

"How does layer order specifically cause a slow build even with caching?"

Because Docker's cache is invalidated from the first changed instruction downward, so a poorly ordered Dockerfile busts the expensive layers on every trivial change. If COPY . . comes before RUN npm ci or RUN mvn dependency:go-offline, then any source edit changes the copied layer and every layer after it, including the expensive dependency install, so the cache is useless for the step that matters.

Ordering it correctly, copy package.json and the lock file, run the install, then copy the source, means a source-only change reuses the cached dependency layer and only re-runs the cheap steps.

So even with a warm registry cache, wrong order means the cache never covers the slow part. Reordering is often the single biggest win, turning a full reinstall on every commit into a cache hit.

"What does RUN --mount=type=cache add beyond layer caching?"

It persists a package manager's download and build cache across builds independently of the layer cache, so even when a layer must rebuild, the tool does not re-download everything.

RUN --mount=type=cache,target=/root/.m2 mvn package keeps the Maven repository between builds, so a changed dependency downloads only the delta rather than re-resolving the whole tree, and the same for ~/.cache/pip, ~/.npm, or Go's module cache.

It differs from layer caching because it survives even a cache-busting change to the layer, and it is not baked into the image, so it does not bloat the result. The mount is a BuildKit feature, shared across concurrent builds on the same builder.

It is the second-biggest speedup after fixing layer order, because it attacks the download time that layer caching alone does not when a layer legitimately rebuilds.

"How do you keep builds fast permanently rather than fixing it once?"

By putting a build-time budget in the pipeline and a warm shared builder behind it.

The pipeline records each service's build time and alerts when one crosses a threshold, say five minutes, so a regression, someone reorders the Dockerfile badly or adds a fat dependency, is caught as it happens rather than rediscovered as a complaint months later.

A remote BuildKit builder shared across jobs keeps the cache warm without any per-job download, so cold runners are no longer cold. Combined with the registry cache, the mount caches, and correct layer order in the template, new services inherit fast builds by default.

So the durable fix is a budget that makes slowness visible plus shared infrastructure that keeps the cache warm, rather than a one-time cleanup that erodes as the Dockerfile changes.

Q136. "Why is docker-in-docker with --privileged a problem in CI, and what do you use instead in 2026?"

Reveal answer

Strong answer Docker-in-docker means running a full Docker daemon inside the CI job's container so the job can run docker build.

The daemon needs to mount filesystems, create network namespaces, and manage cgroups, and the only way to grant all of that is the --privileged flag, which removes almost every kernel boundary between the container and the host.

A CI job running untrusted pull-request code with that flag can read the host's disks, other jobs' secrets, and the runner's cloud credentials. It is a root shell on the build fleet, offered to anyone who can open a pull request.

The alternatives as of Aug 2026 are all daemonless or remote.

The cleanest is a remote BuildKit builder: the CI job runs the buildx client with no daemon at all and talks over TLS to a BuildKit pool that runs on hardened hosts with rootless mode, and the cache lives there.

Buildah from the Podman family builds images without any daemon and can run rootless inside an unprivileged container using user namespaces. Kaniko was the popular Kubernetes-native option for years but was archived by Google in 2025, so I would not start anything new on it.

Docker Engine 29.x also supports rootless mode for the daemon itself, which is a decent option on dedicated build virtual machines where you still want the familiar docker interface.

Mounting the host's Docker socket into the job is sometimes suggested as a lighter alternative, but socket access is root-equivalent on the host, so it is the same risk with a different spelling.

Land it Any design where pull-request code can reach a Docker daemon is a design where pull-request code is root on your build fleet; move the daemon out and talk to it as a client.

Likely follow-ups
"Remote BuildKit needs the runner to trust the builder. How do you secure that connection and the shared cache?"

With mutual TLS and per-tenant cache isolation. The buildx client connects to the BuildKit pool over TLS with client certificates, so only authorised runners reach it, and the builder runs rootless on hardened hosts so a malicious build cannot escalate on the builder itself.

The shared registry cache is a real risk, because a poisoned cache layer could be reused by another build, so I scope cache references per repository or per trust boundary rather than one global cache, and I do not let untrusted pull-request builds write to the cache that trusted main builds read.

Pull-request builds get their own throwaway cache namespace. So the connection is authenticated and encrypted, the builder is unprivileged, and the cache is partitioned so one tenant cannot poison another's layers, which is the property docker-in-docker never gave.

"Kaniko was archived. What do you actually recommend in 2026 and why?"

A remote BuildKit builder as the default, Buildah where a fully daemonless in-runner build is required, and rootless Docker Engine on dedicated build VMs where teams want the familiar interface.

As of Aug 2026 Kaniko was archived by Google in 2025, so I would not start anything new on it and would migrate existing users, most easily to BuildKit since the Dockerfile is unchanged.

Remote BuildKit is my first choice because it keeps the daemon off the runner entirely and gives the best cache story; Buildah suits a Podman-based shop or a strict no-daemon-anywhere policy, building rootless inside an unprivileged container via user namespaces.

All three share the property that pull-request code never reaches a privileged daemon, which is the whole point, and none require the --privileged flag that made docker-in-docker a root shell on the build fleet.

"Someone proposes mounting the host Docker socket as a lighter alternative. Your response?"

It is the same risk with a different spelling, not a lighter alternative.

Access to the host's Docker socket is root-equivalent on the host, because anyone who can talk to it can start a privileged container mounting the host root, so a pull-request build with socket access can read every secret and credential on the runner and escalate to the host exactly as docker-in-docker with --privileged can.

It looks lighter because there is no nested daemon, but the security boundary is identical, gone. So I reject it for untrusted builds and point at the daemonless options.

If some step genuinely needs to talk to a daemon, it gets a socket proxy allowing only the specific read endpoints it needs, never the raw socket, and never for code from an untrusted pull request.

"What is the actual attack if a pull request can reach a privileged Docker daemon?"

The pull request author controls the build steps, so they add a step that uses the privileged access to escape the container: mount the runner host's disk and read its filesystem, including other jobs' checked-out code, cached credentials, and cloud tokens; or start a privileged container and chroot into the host.

From there they exfiltrate the runner's cloud credentials, which often have registry push or deploy rights, or plant a backdoor that poisons later builds on the same host.

Because CI runners frequently hold powerful credentials and run many teams' jobs, one malicious pull request becomes code execution on the build fleet and a foothold into whatever those credentials reach.

That is why the rule is absolute: untrusted, externally-authored build code must never reach a privileged daemon, and the daemonless builders enforce that by construction.

Q137 · Scenario. "Security asks us to prove that a production image matches its commit. We rebuild the same commit on a clean runner and get a different digest. What is going on and can we fix it?"

Reveal answer

The real test Whether you know the ordinary sources of nondeterminism in image builds and how far reproducibility can practically be pushed.

Strong answer I would diagnose in this order:

  1. Split the symptom. An image digest is the hash of the manifest, which contains the hashes of the config and of every layer. If any byte in any layer differs, the digest differs. So the question is which layer changed. Compare the two with diffoci, and use docker history to see which step's layer digest diverges.
  2. Ranked causes: timestamps, because files written during the build carry the build time and the image config carries a created field; unpinned dependencies, because apt-get install curl or pip install requests resolves to whatever is newest today; the base image referenced by tag instead of digest; build tools that embed random ordering or build paths, such as jar files with entry timestamps or Go binaries with embedded paths; and a loose .dockerignore letting local files into the context.
  3. Fix each in turn: pin the base by digest; pin operating-system packages to exact versions and language dependencies through lock files; set SOURCE_DATE_EPOCH to the commit time, which BuildKit uses since 0.13 to normalise file timestamps and the config timestamp when you also pass --output rewrite-timestamp=true; make the application build reproducible, which for Maven means the project.build.outputTimestamp property and for Go means -trimpath; and tighten .dockerignore.
  4. Decide how far to go. Full bit-for-bit reproducibility is achievable for Go and Java services, and fragile for Python and Node. Security usually accepts a signed provenance attestation, proving which builder built which commit, in place of a rebuild.
  5. Prevention: a weekly job that rebuilds one random service from its commit and compares digests, so drift is caught before an audit asks.

Land it Reproducibility is pinning plus timestamp control plus a reproducible application build, and provenance is the cheaper proof most auditors actually want.

Likely follow-ups
"Walk me through finding which layer diverged between the two builds."

docker history --no-trunc on both images lists each layer with its size and the instruction that created it, and comparing the two shows the first layer whose digest differs, which points at the instruction responsible.

For a byte-level view I use diffoci or container-diff, which compare two images and report exactly which files differ in content, timestamp, or permissions, so I can see whether it is a rebuilt dependency, a changed timestamp, or an embedded path.

Once I know the file, the cause is usually obvious: a jar with entry timestamps, a config with the build time, a package resolved to a newer version.

So the method is history to find the diverging layer, then a file-level diff to find the diverging bytes, then map those bytes to one of the known nondeterminism sources.

"How far is full bit-for-bit reproducibility actually worth pursuing?"

Far for Go and Java, which are cheap to make reproducible and where it is achievable, and only as far as provenance for Python and Node, where it is fragile and expensive.

Timestamps and embedded paths are the main obstacles, and SOURCE_DATE_EPOCH, -trimpath, and Maven's output-timestamp property handle the compiled languages well. For interpreted stacks with sprawling native dependencies, chasing the last few nondeterministic bytes costs more effort than it returns.

The pragmatic stance I take with security is that a signed provenance attestation, proving which builder built which commit with which inputs, satisfies the real requirement, which is "prove this image came from this commit", and is cheaper and more robust than a rebuild-and-compare.

So I make the easy languages fully reproducible and rely on provenance as the universal proof.

"What does SOURCE_DATE_EPOCH actually fix and what does it miss?"

It fixes timestamps that would otherwise embed the wall-clock build time: BuildKit since 0.13 uses it to normalise file modification times in layers and the image config's created field, and with --output rewrite-timestamp=true it rewrites layer timestamps to that epoch.

Set to the commit time, two builds of the same commit get identical timestamps.

What it misses is nondeterminism the application build introduces: a jar that records its own entry timestamps unless told not to, a Go binary embedding build paths unless -trimpath is set, unpinned dependencies that resolve differently, and file ordering that some tools randomise.

So SOURCE_DATE_EPOCH is necessary but not sufficient; it handles the Docker layer and config timestamps, and I still need reproducible application builds and pinned dependencies to close the rest. It is one of several controls, not the whole answer.

"Security accepts provenance instead of a rebuild. What exactly does provenance give them here?"

A signed, tamper-evident record that this image digest was produced by a specific builder from a specific source commit with specific inputs, recorded in the transparency log, which answers the underlying question, does this image match its commit, without needing a bit-identical rebuild.

The rebuild was only ever a way to prove that link, and it is fragile because of the nondeterminism sources above, so a rebuild that differs does not actually mean tampering, just an embedded timestamp.

Provenance proves the link directly and cannot be forged without compromising the builder identity. So instead of "rebuild and hope the bytes match", security verifies the provenance attestation against the expected builder and source, which is stronger evidence of origin and far cheaper.

I still pin dependencies and control timestamps for the reproducibility benefits, but provenance is what satisfies the audit.

Q138 · Design. "Design a base-image strategy with patching service levels: critical CVEs fixed in 48 hours, high in 7 days, across forty services and three languages."

Reveal answer

Strong answer Requirements: every service builds from a base the platform team owns, a base fix reaches every service without forty manual pull requests, and there is a paper trail for exceptions.

The design has a golden base per language: Temurin JRE for Java, distroless static for Go, slim Debian for Python.

Each golden base is itself built by a pipeline from an upstream image pinned by digest, and is rebuilt on a weekly schedule and on demand when an advisory lands.

Each rebuild is scanned, signed, and published under a moving tag such as java21:stable plus an immutable digest.

Services reference the base by digest in their Dockerfile, and Renovate or Dependabot opens a pull request in every consumer repository the moment a new digest is published, so the bump is a reviewed diff, not a surprise.

For the 48-hour critical level, the platform team triggers a base rebuild, the bump pull requests are auto-merged where the service's tests pass, and the deploy pipeline promotes them; the runtime scanner confirms the running digest set has moved.

Exceptions live in a file with an owner and an expiry. Trade-offs: auto-merging base bumps needs trustworthy test suites, so auto-merge starts with well-tested services.

What I would not do is let each team pick its own base from Docker Hub, because then a single advisory becomes forty investigations, and I would not rebuild only when a scanner complains, because the scanner lags the advisory by hours to days.

Land it One owned base per language, rebuilt on a clock and on advisories, pinned by digest and bumped by a bot — that is how 48 hours becomes achievable rather than aspirational.

Likely follow-ups
"Auto-merging base bumps needs trustworthy tests. How do you decide which services qualify?"

By a measured confidence bar, not a vote.

A service qualifies for auto-merge of base bumps when it has a test suite that exercises its real dependencies, a green history on recent bumps, and a fast rollback, so a bad base is caught by tests or reverted quickly.

I start auto-merge with the services that already have strong integration tests and a track record, and I keep the rest on manual review of the bump pull request until their tests earn the trust.

Coverage of the paths that a base change could break, the TLS stack, the C library, the runtime, matters more than a raw coverage number.

So the bar is objective and per-service, and it grows as suites improve, rather than auto-merging everything and discovering the weak suites in production during a 48-hour critical scramble.

"A critical CVE lands. Walk me through hitting the 48-hour target concretely."

The platform team triggers a rebuild of the affected golden base from the patched upstream digest, which is scanned, signed, and published under its moving tag plus a new immutable digest within an hour or two.

The bump bot immediately opens pull requests in every consuming service pointing at the new base digest. For qualified services those auto-merge on green tests and the deploy pipeline promotes them; for the rest, owners get a flagged high-priority pull request to review fast.

The runtime scanner confirms the running digest set has moved off the vulnerable base. Because one base rebuild fans out to all forty services through the bot, the human work is reviewing a diff, not editing forty Dockerfiles, which is what makes 48 hours realistic. The paper trail is the pull requests and the scanner's before-and-after.

"What breaks this design and how do you detect it?"

Three things. A service that forked its base or pinned an old digest and stopped taking bump pull requests silently falls behind, which I detect with a check that flags any service whose base digest is not the current golden one.

A base rebuild that itself fails, upstream changed something, stalls the whole fan-out, so I alert on the golden-base pipeline and keep the last-good base to roll back to.

And auto-merge on a weak suite lets a broken base reach production, which the runtime scanner and the service's own health checks should catch, with a fast rollback ready.

So detection is a drift check on base digests, an alert on the base pipeline, and runtime verification that the fleet actually moved, because the design's promise is only real if I can see when a service is not keeping up.

"Why not let each team pick its own base and patch independently?"

Because it turns one advisory into forty independent investigations and makes the 48-hour target impossible.

With forty different bases, a critical CVE in a shared component means every team must separately discover it, find a patched base, and rebuild, with no fan-out and no single owner, so response time is set by the slowest team and coverage is a guess.

A single owned golden base per language means the platform team patches once and the bot propagates to all consumers, so response is fast and provably complete.

It also concentrates the security expertise in the team that maintains the base rather than spreading it thin across forty. The cost is less freedom in base choice, which is exactly the risk-carrying decision I want to standardise, while leaving the application-level choices open. Centralising the base is what makes the service levels achievable.

Q139 · Scenario. "A service that has not changed in three months failed its nightly build and then crashed on the next deploy. The Dockerfile starts with FROM python:3.12. What happened?"

Reveal answer

Strong answer I would diagnose in this order:

  1. Recognise the symptom pattern: nothing in the repository changed, yet the output changed, so an input outside the repository moved. With a bare tag as the base, that input is the base image, and with unpinned package installs it is also every package.
  2. Evidence: compare the digest the last good build used, from its provenance attestation or from docker buildx imagetools inspect python:3.12 at the time recorded in the pipeline log, against the current one. Read the upstream changelog; the python:3.12 tag moves to a new patch release and, more disruptively, to a new Debian base release, which can change the C library, OpenSSL, and default tools. Then check the build log for the first failing step and the crash log for the first missing symbol or library.
  3. Ranked causes: the Debian major bump under the same Python tag breaking a compiled dependency; a Python patch release altering a deprecated behaviour the code relied on; a pip install without a lock file pulling a new major version of a library; and an apt-get install pulling a package that no longer exists in the new distribution.
  4. Fix: pin the base to the digest of the last known-good image, rebuild, and deploy the result to restore service; then upgrade deliberately in a separate change with the lock file updated and tests run.
  5. Prevention: digest-pinned bases with automated bump pull requests so every upstream change is a visible diff; lock files for all dependencies; and a rule that a nightly rebuild failure with no diff is treated as an upstream change to investigate, not as a flake to rerun.

Land it A tag is a promise the upstream never made; a digest is bytes, and only bytes are reproducible.

Likely follow-ups
"How do you find exactly what changed in the base under the same tag?"

By comparing the digest the last good build used against the current one and reading the upstream changelog for what moved between them.

From the last successful pipeline log or its provenance I have the base digest it resolved python:3.12 to; docker buildx imagetools inspect python:3.12 gives the current digest, and if they differ the tag moved.

Then I look at the two images' details, the Debian release, the Python patch version, the OpenSSL and glibc versions, either from the upstream release notes or by diffing the package lists of the two images with a container-diff tool.

That tells me whether it was a Debian major bump changing the C library, a Python patch altering behaviour, or a package that vanished. Knowing the specific change points straight at the fix and confirms the diagnosis that an external input moved.

"The immediate fix is pin to the last-good digest. What is the proper follow-up?"

Upgrade deliberately in a separate, reviewed change rather than absorbing the surprise. Pinning to the last-known-good digest and redeploying restores service now, and it is a stopgap, not the destination, because the service still needs the newer base eventually for its own security patches.

The follow-up is a controlled bump: update to the new base in a pull request, update the lock files, run the full test suite, fix whatever the Debian or Python change broke, and deploy through the normal flow.

That way the upgrade is intentional, tested, and attributable, instead of arriving unannounced through a moving tag. And I make it a bot-driven diff going forward so every future base change is a reviewed pull request rather than a nightly-build surprise, which is the real prevention.

"A nightly build with no code change suddenly fails. Flake or signal?"

Signal, and I treat it as an upstream change to investigate, not a flake to rerun.

If nothing in the repository changed and the build now fails or the image now behaves differently, an input outside the repository moved, and with a bare base tag and unpinned installs there are two such inputs: the base image and the packages.

Rerunning just gets the same moved input; the correct response is to diff the resolved base digest and the installed package versions against the last good build and find what changed.

Making "no-diff nightly failure equals upstream change" an explicit rule stops the team from burning time rerunning and instead points them at the base and dependency pins. It is also an argument for digest pinning, because with pinned bytes a no-code-change build cannot spontaneously change.

"How do you prevent a whole class of these across forty services?"

Pin every base by digest and every dependency by lock file, and make upstream changes arrive as reviewed pull requests.

With digest-pinned bases a moving upstream tag cannot silently change what a service builds from, so a nightly build of an unchanged commit produces the same bytes; the base only changes when the bump bot opens a pull request, which runs the tests and shows the diff.

Lock files do the same for language dependencies. Across the fleet this is enforced by a lint that rejects un-digested bases and by the golden-base strategy, so the forty services share owned, pinned bases that the platform patches deliberately.

The result is that the scenario, a three-month-stable service breaking because python:3.12 moved, becomes impossible, because nothing floats, and every upstream change is a visible, tested diff rather than a surprise at deploy time.

Q140 · Design. "Design the promotion flow from development to production so that the image tested in staging is byte-for-byte the image that runs in production."

Reveal answer

The real test Whether you promote by digest with no rebuild, and whether environment-specific configuration stays outside the image.

Strong answer Requirements: one build per commit, the same digest in every environment, a record of who approved each promotion, and rollback to any earlier digest in minutes. The design separates the artifact from its configuration.

The build pipeline produces one image per service per commit, tagged git-<sha>, signed and attested, in a build repository of the internal registry.

Everything that differs between environments, database hosts, feature flags, log levels, is injected at run time through environment variables, mounted configuration files, or a configuration service, and never baked in.

Promotion is a metadata operation: a deploy pipeline takes the digest from the release manifest, verifies its signature, runs the staging tests against it, and on approval adds a tag such as prod-2026-08-28 with crane tag, which never moves bytes and never changes the digest.

The deployment manifests reference the image by digest, image: registry.internal/team/api@sha256:…, so a tag change cannot alter what runs, and the approval is recorded as a cosign attestation naming the approver and the environment.

Rollback is re-pointing the manifest at the previous digest, which is still in the registry under the retention rule. Trade-offs: digests are unreadable in a manifest, so the pipeline writes the git SHA and tag into an annotation beside it.

What I would not do is build once per environment with environment-specific build arguments, because then staging never tested production's bytes, and I would not use a prod tag that gets moved with pull-tag-push from a laptop, because that both changes the digest and bypasses the approval record.

promote.sh
IMAGE=registry.internal/team/api
DIGEST=$(crane digest "$IMAGE:git-3f9a2c1")
cosign verify --certificate-identity-regexp '^https://github.com/acme-org/' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com "$IMAGE@$DIGEST"
crane tag "$IMAGE@$DIGEST" "prod-$(date +%F)"
echo "$IMAGE@$DIGEST" > release-prod.txt

Land it Build once, promote by digest, configure at run time, and let the tag be a label for humans rather than an instruction for machines.

Likely follow-ups
"Configuration is injected at runtime. How do you keep secrets and config out of the image without a config-per-environment build?"

The image contains only code and sensible defaults, and everything that differs by environment comes in at start.

Non-secret configuration, database hosts, feature flags, log levels, arrives as environment variables or a mounted config file from a config service, keyed by an ENVIRONMENT variable the platform sets.

Secrets arrive as files on tmpfs from the secrets manager via workload identity, read by the app the same way in every environment.

Because none of this is baked in, the same digest runs in staging and production with different inputs, so there is no per-environment build and staging genuinely tested production's bytes.

Spring Boot reads external config trees and environment variables without code changes, so the application is identical. The invariant is: build the artifact once, inject the difference at runtime, never at build time.

"How does crane tag differ from re-pushing, and why does it matter for byte-identity?"

crane tag adds a new tag to an existing manifest in the registry server-side, moving no bytes and changing no digest, so the promoted image is literally the same object that was tested, and its signatures and attestations remain valid.

Re-pushing, the pull-tag-push pattern, pulls the image to a local daemon and pushes it again, which can re-create the manifest with a different digest, a single-platform pull of a multi-arch image or a different Docker version being enough to change the bytes, and that new digest was never tested and orphans the signature.

So byte-identity between staging and production depends on the promotion being a metadata operation, not a rebuild, which is exactly what crane tag guarantees and what a local retag breaks.

Referencing by digest in the manifest makes it airtight, since even a tag cannot change the running bytes.

"Rollback needs the previous digest. How do you guarantee it is still there?"

By a retention policy that keeps at least the last several production digests per service regardless of age, and by referencing images by digest so the running one is always concretely identified.

The registry retention starts from the live set, every digest a cluster currently runs is protected, then keeps the last N production digests and any release-tagged image for the audit window, so last week's image cannot be garbage-collected out from under a rollback.

Rollback is then re-pointing the deployment manifest at the previous digest, which is still present and already cached on the nodes, so it completes in minutes with no rebuild.

If retention deleted the prior digest, rollback would require a rebuild that produces an untested image, defeating the purpose, so protecting recent production digests is a hard rule, not a nice-to-have.

"What would you cut if you had to ship this promotion flow in a day?"

I would cut the signed approval attestation and the cosign verification step, and keep the two things that deliver byte-identity: build once per commit with a git-SHA tag, and promote by digest with crane tag rather than rebuilding.

That alone guarantees staging and production run the same bytes, which is the question. I would keep runtime configuration injection so there is no per-environment build.

What I would defer is the approval recorded as an attestation and the automated signature check at promotion, replacing them for a day with a manual approval logged in the pipeline.

Those add auditability and tamper-evidence, which matter, but they are not what makes the image byte-identical. So the one-day version is build-once, promote-by-digest, configure-at-runtime, with the signing and approval trail added right after.

Q141 · Scenario. "Infrastructure added arm64 nodes to save cost. Twelve services now crash-loop with exec /app/server: exec format error. Walk me through the diagnosis and the fix."

Reveal answer

Strong answer I would diagnose in this order:

  1. Read the symptom literally. exec format error is the kernel refusing to run a binary compiled for a different CPU architecture. An amd64-only image was scheduled onto an arm64 node, the layers pulled fine, and the first process failed at exec.
  2. Evidence: docker buildx imagetools inspect registry.internal/team/api:git-3f9a2c1 shows whether the image is a single-platform manifest or a manifest list with both linux/amd64 and linux/arm64 entries.
  3. Ranked causes: the service pipelines build with a plain docker build on amd64 runners and never produced arm64 images; the base image is multi-arch but a build stage downloads an amd64 binary by hard-coded URL; a Java service ships a native library compiled for amd64 in its jar; and the scheduler has no architecture constraint, so it treats all nodes as equal.
  4. Fix in two steps. Immediately, add a node selector or affinity on kubernetes.io/arch: amd64 to the twelve services, or in plain Docker pin them to the amd64 hosts, so they stop crashing. Then rebuild them with docker buildx build --platform linux/amd64,linux/arm64, which either cross-compiles with QEMU emulation, slow but simple, or uses native arm64 builders in the buildx builder group, fast and the right choice for compiled languages. Fix the hard-coded amd64 downloads with TARGETARCH build arguments.
  5. Prevention: an admission rule that rejects a single-platform image on a mixed cluster, a pipeline check that fails when the manifest list lacks a required platform, and a rollout order where arm64 nodes are tainted until a service has proven itself there. See E10 for the scheduling side.

Land it The layers pulled and the container started, which is exactly why architecture mismatches surface at run time and must be caught in the manifest before scheduling.

Likely follow-ups
"The layers pulled fine but exec failed. Why does the mismatch surface so late?"

Because nothing before exec checks the architecture. The image layers are just tar files of bytes, so they pull and unpack on any architecture without complaint, and the container filesystem assembles fine.

The mismatch only bites when the kernel is asked to execute the entrypoint binary and reads its ELF header, finds a machine type it cannot run, and returns exec format error.

So the failure is deferred all the way to the first process start, which is why an amd64-only image scheduled onto an arm64 node crash-loops rather than failing to pull.

That late surfacing is exactly why the check has to move earlier, into the manifest at build and admission time, because by the time the kernel refuses the exec it is already a running-time crash-loop across twelve services rather than a caught build error.

"Immediate fix is node affinity to amd64. What is the diagnosis before you pin?"

docker buildx imagetools inspect on the image to see whether it is a single-platform manifest or a manifest list with both linux/amd64 and linux/arm64 entries; a single-platform amd64 image on a mixed cluster is the whole story.

If it is a manifest list but still fails, I check whether a build stage downloaded an amd64 binary by a hard-coded URL despite the multi-arch base, or whether a Java service ships a native library compiled only for amd64 inside its jar.

So before pinning I confirm which of those it is, because the fix differs: no arm64 image at all means rebuild multi-arch, while a hard-coded download or a native jar library means fixing the Dockerfile or the dependency.

Pinning to amd64 nodes stops the crash immediately, but the diagnosis decides what the real rebuild must address.

"The rebuild is multi-arch but the arm64 build is painfully slow. Why and what do you do?"

Because it is almost certainly building under QEMU emulation, where an amd64 runner emulates an arm64 CPU to compile, which for compiled languages is five to ten times slower.

The fix is native arm64 builders: a buildx builder group that includes real arm64 runners, so each platform builds on its own hardware and the manifest list is assembled from both, which is fast and correct.

For Go specifically, cross-compilation is cheaper still, --platform=$BUILDPLATFORM on the build stage with GOARCH=$TARGETARCH produces the arm64 binary from an amd64 runner without emulation.

So I move compiled-language builds to native runners or cross-compilation and reserve QEMU for occasional or interpreted builds where its slowness does not matter. Hard-coded architecture downloads get parameterised with TARGETARCH so the right binary is fetched per platform.

"How do you make sure a single-platform image can never crash-loop on a mixed cluster again?"

Catch it in the manifest before scheduling, at two gates. A pipeline check fails any build whose manifest list lacks a required platform, so a service that silently builds amd64-only never ships.

An admission rule rejects a single-platform image on a mixed cluster, so anything that slipped through is refused before a pod is scheduled onto an arm64 node.

During the rollout I taint the arm64 nodes so a service runs there only after it has proven itself, and the scheduler respects an architecture constraint rather than treating all nodes as equal.

Together these mean the architecture mismatch is a build failure or an admission rejection, both cheap and early, instead of an exec format error discovered at 03:00 across twelve services, which is the whole point of moving the check up the chain.

Q142 · Design. "Design the rollout of multi-architecture support across forty services so that arm64 nodes can be adopted without an incident like the last one."

Reveal answer

Strong answer Requirements: every service produces a manifest list with amd64 and arm64 by default, builds stay under the time budget, and a service that cannot yet run on arm64 is excluded by policy rather than by luck.

The design starts with the base images, because a service cannot be multi-arch until its base is; the golden bases are rebuilt as manifest lists first.

Then the shared pipeline template changes in one place: docker buildx bake with platforms = ["linux/amd64", "linux/arm64"] and a builder group that includes native arm64 runners, so compiled languages build natively instead of under QEMU emulation, which can be five to ten times slower.

Dockerfiles use ARG TARGETARCH for any downloaded tool and --platform=$BUILDPLATFORM on build stages for Go, which cross-compiles cheaply. The rollout is in waves. Wave one is the stateless Go and Java services, which usually work unchanged.

Wave two is Python and Node services, where native extensions must have arm64 wheels or be compiled. Wave three is anything with vendor binaries or native libraries, handled case by case.

Each service passes an arm64 integration test in staging before its amd64-only node affinity is removed, and a manifest check in the pipeline fails a build that lacks a required platform.

Trade-offs: doubling platforms roughly doubles build minutes and registry storage, offset by the 20 to 40 percent compute saving arm64 typically brings; and I load-test one service per language before committing capacity.

What I would not do is flip the whole fleet's scheduling to mixed nodes on day one, or rely on QEMU for production builds of Java native-image or C++ services.

Land it Bases first, template second, waves by language risk, and a pipeline check that makes single-platform images a build failure rather than a 03:00 page.

Likely follow-ups
"Why must the base images go multi-arch first?"

Because a service cannot produce an arm64 image if the base it builds FROM has no arm64 variant; the build would fail or fall back to emulating the wrong architecture.

So the golden bases are rebuilt as manifest lists with both platforms before any consumer is asked to go multi-arch, and only then does the shared pipeline template turn on the second platform.

Doing it in the other order means forty services hit the missing-base wall simultaneously. It also means the platform team validates the arm64 base once, its packages, its libraries, its size, rather than each service discovering base-level arm64 problems independently.

Bases first is the dependency order of the whole rollout: the base is the foundation every service stands on, so it must exist on arm64 before the fan-out begins, which is why it is wave zero rather than part of wave one.

"How do you order the waves and why by language?"

By how likely a language is to just work on arm64, cheapest first.

Wave one is stateless Go and Java services, which are usually architecture-clean because the toolchains cross-compile well and the runtime abstracts the CPU, so they go multi-arch with little more than turning on the second platform.

Wave two is Python and Node, where native extensions must have arm64 wheels or be compiled, so there is real per-dependency work.

Wave three is anything with vendor binaries or native libraries, handled case by case because a closed-source amd64 blob may have no arm64 build at all.

Ordering by language risk means the early waves build confidence and capacity cheaply, and the hard cases come last when the pipeline and the arm64 nodes are proven, rather than starting with the service most likely to fail and stalling the whole programme.

"What is the safe way to actually shift traffic onto arm64 nodes?"

Prove each service on arm64 in staging, then remove its amd64-only constraint gradually while watching it. Each service passes an arm64 integration test in staging before its production node affinity is loosened, so I know it runs correctly on the architecture before any real traffic.

Then I let the scheduler place some replicas on arm64 nodes and watch latency, error rate, and resource use against the amd64 replicas, since arm64 performance characteristics can differ, before allowing full placement.

The arm64 nodes start tainted so only services that have opted in and proven themselves land there. A pipeline manifest check ensures the service actually has an arm64 image before its affinity is removed, so I never loosen the constraint on a single-platform image.

Gradual, verified, per-service, with a fast way back to amd64-only if a service misbehaves.

"What would you cut under time or budget pressure?"

I would cut the breadth, doing only the services that give the most arm64 capacity for the least effort, the wave-one stateless Go and Java services, and defer the Python, Node, and vendor-binary cases indefinitely, since chasing arm64 wheels and missing native builds is where the cost balloons.

I would keep the base-images-first ordering and the pipeline manifest check, because without them even the easy services are unsafe. I would load-test one representative service per language before committing capacity, rather than all forty, to confirm the compute saving is real.

What I would not cut is the admission and pipeline gates that make single-platform images fail early, because the whole reason for the programme is to avoid another exec format error incident, and skipping the gates to move faster reintroduces exactly that risk.

Q143 · Design. "Design the rollback story for a bad image, from the moment someone says 'revert' to the moment traffic is back on the old version — on Kubernetes and on a single Docker host."

Reveal answer

Strong answer Requirements: rollback must not rebuild anything, must complete in under five minutes, and must not silently roll back a database migration it cannot undo. The design rests on immutable images referenced by digest and on keeping the previous digests available.

Every deployment records the digest it replaced in the release manifest, and the registry's retention rule keeps at least the last ten production digests per service regardless of age.

On Kubernetes, a rollback is a change to the deployment manifest pointing the image back at the previous digest, applied through the same Git-driven path as a forward deploy so the audit trail is intact; kubectl rollout undo is the emergency shortcut.

The old digest is still cached on the nodes, so there is no pull.

On a single Docker host I use a blue/green layout: two named containers, api-blue and api-green, behind a local reverse proxy, with the deploy script starting the new digest on the idle colour, health-checking it, switching the proxy upstream, and leaving the old colour running for an hour.

Rollback is switching the upstream back, which takes a second.

The hard part is data: a migration that dropped a column cannot be rolled back by redeploying, so the process requires expand-and-contract migrations, in which the old and new versions can both run against the schema for at least one release, which E7 covers.

What I would not do is rollback by rebuilding the previous commit, because that produces a new, untested digest, and I would not let retention delete last week's production image.

Land it Rollback is re-pointing at a digest you kept, and the only thing that makes it unsafe is a schema change that forgot the old version still needs to run.

Likely follow-ups
"The rollback itself fails because the old digest was garbage-collected. What now, and how do you prevent it?"

Now I find the image wherever it still exists: a node that still has it cached, from which docker save and reload it, a regional mirror that has not yet pruned it, or a rebuild of the exact previous commit as a last resort, which produces an untested digest and is the outcome I most wanted to avoid.

Then I get service back and treat the missing digest as an incident of its own.

Prevention is a retention rule that protects the live set plus the last several production digests per service regardless of age, so a rollback target is never collected, and referencing images by digest so the previous version is concretely named and can be excluded from garbage collection.

Retention deleting last week's production image is a configuration bug, and the fix is that the live-and-recent set is never eligible for collection.

"On the single Docker host, walk me through the blue/green switch and its failure modes."

Two named containers, api-blue and api-green, sit behind a local reverse proxy.

To deploy, the script starts the new digest on the idle colour, health-checks it through its readiness endpoint, and only when healthy switches the proxy's upstream to the new colour, leaving the old one running for an hour as an instant rollback.

The switch is a proxy config reload, a second.

Failure modes: the new colour never becomes healthy, so the switch never happens and the old colour keeps serving, which is the safe default; the proxy reload fails, so I verify the new config before reloading and keep the old on error; and in-flight connections on the old colour must drain, so the proxy stops sending new connections but lets existing ones finish before I stop the old container.

Rollback is switching the upstream back, which is why I keep the old colour warm.

"A migration dropped a column. Why can't you just redeploy the old image, and what is the fix?"

Because the schema has already changed and the old image expects the dropped column, so redeploying it makes the old code query a column that no longer exists and fail, and the data in that column may be gone, which no redeploy restores.

Rolling back the code does not roll back the database. The fix is expand-and-contract migrations: the schema change is split so the old and new code can both run against it for at least one release.

To remove a column, first deploy code that stops using it while leaving it in place (expand), release and bake, and only in a later release drop the column (contract), by which time no running version needs it.

Then a rollback of the code always lands on a schema both versions tolerate, so rollback stays safe. The rule is that a single release never makes a backward-incompatible schema change.

"How do you keep rollback under five minutes as the fleet grows?"

By making rollback a metadata change against pre-cached, immutable images rather than a rebuild or a re-pull.

Because images are referenced by digest and the previous digests are retained and already cached on the nodes, rollback is re-pointing the manifest at the prior digest through the same Git-driven path, which schedules with no pull, or kubectl rollout undo for the emergency case, both completing in a minute or two regardless of fleet size.

The single-host blue/green keeps the old colour warm so its rollback is a proxy switch.

What would blow the budget is rebuilding, re-pulling large images cold, or a schema change that forces a data restore, so I prevent each: build once and keep the digest, warm-cache the running set, and enforce expand-and-contract migrations.

Rollback speed is a property of the design, immutable digests plus retained, cached previous versions, not something I tune per incident.

Drill · Runtime operations, capacity, incident response & judgment

These questions test whether you can run containers as a fleet — seeing them, sizing them, responding when one is compromised — and whether you know when Docker is the wrong tool altogether.

Q144 · Design. "Design observability for a fleet of a few hundred containers across dozens of hosts: metrics, logs, and events. What comes from where?"

Reveal answer

Strong answer Requirements: per-container CPU, memory, network, and disk metrics with a 15-second resolution kept for 30 days, logs searchable within a minute of being written, lifecycle events such as restarts and out-of-memory kills correlated with both.

Metrics come from the kernel's control groups, cgroups, which is where the runtime enforces limits and where the true usage counters live. cAdvisor reads cgroup v2 files per container and exposes them for Prometheus, and docker stats reads the same counters.

The key series are working-set memory against the limit, CPU throttled periods against total periods, which reveals CPU limits that are too tight, and restart counts.

Logs come from the runtime's log driver: the application writes to standard output, the runtime writes a rotated file per container, and a node agent, Fluent Bit or Vector, tails those files, adds container name, digest, and host to each line, and ships them to a central store such as Loki or OpenSearch.

Shipping from files rather than from the application means a slow log backend cannot stall the service.

Events come from the Docker events stream or the Kubernetes event API and from the kernel: out-of-memory kills show up as exit code 137 with OOMKilled: true in docker inspect, and I alert on those directly.

Trade-off: container-ID labels churn Prometheus, so I drop them and keep the stable name. What I would not do is rely on the application's own metrics alone, because the container that is being killed is the one whose metrics stop arriving.

Land it Metrics from cgroups, logs from the runtime's files through a node agent, events from the daemon and the kernel, and the image digest on all three so you can say which release did it.

Likely follow-ups
"Why take metrics from cgroups rather than from the application?"

Because cgroups are where the runtime actually enforces limits, so they hold the true usage numbers and the throttling and OOM counters the application cannot see about itself.

The application can report its own heap and request rate, but it cannot tell you it was CPU-throttled, how close it is to its memory limit, or that it was OOM-killed, because at the moment it is killed its own metrics stop arriving.

cgroup metrics via cAdvisor give working-set memory against the limit, CPU throttled periods against total periods, and restart counts, all from the kernel's accounting, independent of whether the app is healthy.

So application metrics tell me what the app thinks it is doing, and cgroup metrics tell me what the kernel is doing to it, and for the container that is dying, only the second is available. I collect both and correlate them by the image digest.

"Why ship logs from files via a node agent instead of from the application directly?"

Because a log backend that slows down or fails must never stall the service, and shipping from the application couples the two.

If the app writes logs synchronously to a remote store and that store is slow, the app's request threads block on logging, so a logging outage becomes an application outage.

Writing to stdout, which the runtime rotates into a file, decouples them: the app writes locally at memory speed, and a node agent such as Fluent Bit or Vector tails the file and ships it, adding container name, digest, and host.

If the backend is slow, the agent buffers or the file grows, but the app is unaffected. The agent also enriches every line with metadata the app does not know, and it handles rotation.

So the file-and-agent path is about isolation: the service's latency is independent of the observability pipeline's health.

"Container IDs churn and blow up Prometheus cardinality. How do you handle it?"

By dropping the volatile labels and keeping stable ones.

Every container restart creates a new container ID, so labelling metrics with the ID means a new time series per restart, and a service that crash-loops or redeploys often generates thousands of dead series, which bloats Prometheus memory and slows queries.

In the scrape config I relabel to drop the container ID and the pod's random suffix and keep the stable identifiers, the service name, the namespace, and the image digest, which is stable per release and is what I actually want to group and alert on.

That keeps cardinality bounded by the number of services and releases rather than by the number of restarts. The digest gives me per-release breakdown without the churn, so I can still say which release caused a regression while keeping the series count sane.

"How do you catch an OOM kill specifically and alert on it?"

By reading the kernel's own signal rather than inferring it from a metric gap.

An OOM kill exits the container with code 137 and sets OOMKilled: true, visible in docker inspect --format '{{.State.OOMKilled}}' or as the pod's last-state reason in Kubernetes, and the kernel logs it in dmesg naming the cgroup.

I alert directly on that: cAdvisor exposes an OOM-events counter and the container last-terminated reason, and I page when it increments, tagged with the service and digest so I know which release and which container.

This is more reliable than watching memory approach the limit, because a fast allocation can jump straight past the threshold, and it distinguishes an OOM kill from a plain restart or a deliberate stop, which matters because the remediation, more memory or a leak fix, is specific to the OOM case.

Q145 · Scenario. "Someone ran a right-sizing script over the weekend that set memory limits from the last week's p95 usage. Monday morning: exit code 137 across two thirds of the fleet. What went wrong and how do you recover?"

Reveal answer

The real test Whether you understand what a memory limit measures, why a p95 of a week is the wrong number, and how to recover without a second fleet-wide mistake.

Strong answer I would diagnose in this order:

  1. Confirm the symptom: exit code 137 is the process killed by signal 9, and docker inspect --format '{{.State.OOMKilled}}' or the pod's last-state reason distinguishes an out-of-memory kill from a plain docker kill.
  2. Evidence: the old and new limits per service from the script's output, the working-set memory series from cAdvisor for the past two weeks. A weekend p95 is the quietest window of the week and misses the Monday 09:00 peak, month-end batch jobs, and the Java virtual machine's startup burst before garbage collection settles.
  3. Ranked causes: the p95 was computed over a low-traffic window; the script used docker stats usage, which includes page cache that the kernel could reclaim, but then set the limit to exactly that with no headroom, so the first real allocation hits the ceiling; Java services whose heap is sized as a percentage of the container limit through -XX:MaxRAMPercentage now get a smaller heap plus the same off-heap needs, and a limit at p95 leaves no room for metaspace, threads, and direct buffers.
  4. Recover: revert the limits fleet-wide from the script's own before-state, which must exist; if it does not, restore from the last known-good manifests in Git. Do not hand-tune during the incident.
  5. Prevention: a right-sizing rule of peak working set over at least four weeks including month-end, plus 30 to 50 percent headroom, applied in waves of a few services with a soak of a week; alerts on the ratio of working set to limit above 85 percent; and a policy that fleet-wide limit changes go through the same review as code.

Land it A limit is a promise to the kernel about the worst case, and a weekend p95 is a statement about the best case.

Likely follow-ups
"The script has no before-state saved. How do you recover safely?"

From the last known-good deployment manifests in version control, not by hand-tuning during the incident.

If the limits are declared in Git-managed manifests, I revert the commit that the script's change corresponds to, or roll back to the last good manifest set, and reapply, which restores every service's previous limits atomically and with an audit trail.

If the change was applied imperatively and not captured in Git, I reconstruct the previous limits from the cAdvisor history, the working-set memory each service actually used before the change, and apply generous values quickly to stop the bleeding, then right-size properly later.

What I do not do is tweak limits container by container during the incident, because that is a second uncoordinated fleet-wide change on top of the first. The lesson for prevention is that limits live in Git so a bad change is one revert away.

"Why is a weekend p95 specifically the wrong number for a memory limit?"

Because a memory limit must cover the worst case and a weekend p95 describes the best case.

Memory is incompressible: exceeding the limit kills the container, so the limit has to be above the real peak, including the Monday 09:00 traffic peak, month-end batch jobs, and the JVM's startup burst before garbage collection settles.

A weekend is the quietest window of the week, so its p95 misses all of those, and setting the limit at that value means the first real Monday allocation hits the ceiling and the OOM killer fires, which is exactly the exit-code-137 storm described.

Worse, if the script used docker stats usage it included reclaimable page cache and then left no headroom.

So the right basis is peak working set over at least four weeks including month-end, plus 30 to 50 percent headroom, because the limit is a promise about the worst case, not a description of the typical one.

"How is right-sizing memory different from right-sizing CPU here?"

They fail differently, so they are sized differently. Memory is incompressible: over the limit means killed, so I size the memory limit from the peak working set over weeks plus headroom, and set the request equal to the limit so the scheduler never over-commits memory.

CPU is compressible: over the limit means merely slowed by throttling, not killed, so I can size the CPU request from the typical p50-to-p75 usage to pack nodes densely, and set the limit generously or not at all, because a tight CPU limit causes throttling that shows up as latency long before it shows up as an outage.

Applying a p95 rule uniformly to both is the error: it is roughly right for CPU, where being wrong just slows things, and dangerous for memory, where being wrong kills the container. So the recovery and the future rule treat the two resources as separate problems.

"How do you prevent a fleet-wide change like this from happening unreviewed again?"

By treating limit changes as code and rolling them out in waves with a soak.

A script that rewrites limits across the whole fleet over a weekend is a fleet-wide production change that went in without review, so the policy is that any change to limits or requests goes through the same pull-request review and approval as application code, and lands in the Git-managed manifests where it can be reverted.

The right-sizing job proposes changes as pull requests derived from four-plus weeks of peak data with headroom, applied in waves of a few services with a week of soak each, so a bad number affects a handful of services briefly rather than two-thirds of the fleet at once.

Alerts on working-set-to-limit ratio above 85 percent catch under-provisioning before it becomes a kill. Reviewed, gradual, data-derived, and reversible, which is the opposite of a weekend script.

Q146 · Design. "Design a capacity and right-sizing methodology for container CPU and memory limits and requests, including how you would account for image bloat as a cost."

Reveal answer

Strong answer Requirements: fewer nodes without out-of-memory kills or throttling, and numbers re-derived from data on a schedule. The methodology separates the two resources because they fail differently.

Memory is incompressible: when a container exceeds its limit it is killed, so memory limits are set from the observed peak working set over four weeks plus 30 percent headroom, and the request is set equal to the limit so the scheduler never over-commits memory.

CPU is compressible: exceeding the limit only slows the process, so CPU requests are set from the p50 to p75 of usage to enable dense bin-packing, and limits are either removed or set generously at two to four times the request, because tight CPU limits cause throttling that shows up as latency long before it shows up as an outage.

The numbers are produced by a monthly job from cAdvisor data, proposed as pull requests to the manifests, and rolled out in waves with a week of soak per wave.

Image bloat is a capacity cost too: a 1.2 GB image costs storage on every node and in the registry, and its pull time on a cold node, often 30 to 60 seconds, extends every scale-up and every recovery from a node failure.

Trade-off: CPU requests below limits allow noisy neighbours under saturation, acceptable for stateless services but not for latency-critical ones, which get a dedicated node pool.

What I would not do is copy limits from a template across services of different languages, or use a vertical autoscaler in automatic mode on stateful services.

Land it Size memory for the worst four weeks with headroom, size CPU for the typical case and let it burst, and count image size as capacity because pull time is recovery time.

Likely follow-ups
"Why request equals limit for memory but not for CPU? Walk me through what goes wrong if you over-commit memory."

Because memory cannot be taken back from a process without killing it.

If the scheduler places pods on a node whose memory limits add up to 150 percent of the node's RAM, based on requests that are lower than limits, everything is fine until several pods approach their limits at once.

Then the node itself runs out of memory, and the kernel's OOM killer or the kubelet's eviction picks victims by priority and by how far over request each pod is, so a well-behaved pod can be evicted because its neighbour grew.

With request equal to limit the scheduler never places more memory than the node has, and the only way a pod dies is by exceeding its own limit, which is its own fault and its own alert.

CPU is different: if pods burst beyond their requests and the node runs out, the scheduler just gives each one its proportional share and nothing dies, so over-committing CPU is a cost saving with a latency price, not an outage risk.

I would verify the memory policy with a query that flags any pod whose memory request differs from its limit.

"Peak over four weeks plus 30 percent will over-provision most services. How would you tighten it without kills?"

By measuring the shape of the memory, not just the peak.

For a JVM the working set is mostly fixed by MaxRAMPercentage and the non-heap, so a JVM service that never exceeded 60 percent of its limit in four weeks is not going to; its headroom can drop to 15 percent, provided the heap percentage is adjusted with it, because the heap follows the limit.

For garbage-collected services generally, I use memory.peak from the cgroup rather than a sampled metric, since a 30-second sample interval misses spikes. For services with a known nightly batch, I size for the batch or move the batch.

The safety net is a vertical autoscaler in recommendation-only mode, which produces a suggested request from a decaying histogram of usage, and a canary wave: apply the tighter number to 10 percent of instances for a week, watch oom_kill in memory.events and the pod restart count, and only then roll it out.

Tightening is safe when the kill rate on the canary stays at zero for a full weekly cycle.

"Put a number on image bloat. When is it worth an engineer's week to shrink an image?"

I would count three costs.

Pull time: a 1.2 GB image on a node with a 1 Gbps link and a busy registry takes 30 to 60 seconds to pull and unpack, against 3 to 5 seconds for a 150 MB one; multiply by scale-up events per day and by node replacements, and for a service that scales twenty times a day that is fifteen minutes of daily under-capacity, which is a latency SLO cost.

Storage: every node caches every image it has run, so a 40-node fleet with 30 large images holds a terabyte of layers, and registry storage and egress bill on top of that. Scanning and startup: larger images scan slower and carry more packages to patch.

The rule of thumb I use is that an image over 500 MB for a JVM or Go service is worth a day, and the fix is usually mechanical: a distroless or slim base, a multi-stage build so the compiler and build cache stay out, and, for Java, jlink to trim the runtime.

The verification is docker image history before and after, and the pull time on a cold node.

"The monthly job proposes a change and it causes throttling on a service. How do you catch that before it reaches everyone?"

That is what the wave-and-soak structure is for, and the throttling metric is the gate.

Each wave applies the new numbers to a subset, and the soak week has automated checks: container_cpu_cfs_throttled_periods_total divided by container_cpu_cfs_periods_total must stay below 5 percent, oom_kill in memory.events must stay at zero, and the service's own p99 must stay within its SLO. If any check fails, the wave is rolled back by reverting the pull request and the service is flagged for manual review rather than automatic sizing.

For CPU the right-sizing job should also refuse to lower a limit on a service that already shows throttling, because the p75 of a throttled service is already capped by the old limit and is not a true measure of demand.

I would keep a per-service exemption list in the same repository, so a latency-critical service can opt out of automatic CPU changes while still getting memory recommendations.

"What would you cut if you had to ship this methodology in a week?"

I would cut the monthly automation and produce the first numbers as a one-off spreadsheet from four weeks of cAdvisor data, applied by hand to the twenty largest services, because those twenty are where the node savings are.

I would cut the vertical autoscaler entirely for the first pass. I would cut image bloat to a single report listing images by size, with the top five as tickets.

What I would keep is the memory policy, request equals limit from peak plus headroom, because that is the part that prevents the exit-code-137 Monday, and the throttling check, because dropping CPU limits without watching throttling is how a cost saving becomes a latency incident.

I would also keep the wave structure even at small scale, applying to a third of the instances first, because it costs nothing and turns a fleet-wide mistake into a partial one.

Q147 · Scenario. "Your runtime security tool alerts that a container running the payments API spawned /bin/sh and is making outbound connections to an unknown IP. You are the on-call engineer. What do you do in the first 30 minutes?"

Reveal answer

The real test Whether you contain before you investigate, preserve evidence before you destroy it, and know the blast radius questions to ask.

Strong answer I would act in this order:

  1. Treat the symptom as a confirmed compromise until proven otherwise: a shell spawned inside a production API that has no legitimate reason to run one, is the classic post-exploitation pattern. Page security and the service owner in the first two minutes.
  2. Contain without destroying evidence. Isolate the container's network rather than killing it: on Docker that is docker network disconnect from every network it is on; on Kubernetes a deny-all network policy applied to that pod. Do not docker rm it and do not restart it, because the writable layer and process memory are the evidence.
  3. Capture evidence in the next ten minutes: docker inspect for the image digest and mounts, docker diff for files changed in the writable layer, docker top and docker exec ps -ef for the process tree, docker export for the filesystem, and the host's audit and connection logs for the unknown IP.
  4. Bound the blast radius: what credentials were reachable from that container, environment variables, mounted secrets, the node's cloud instance credentials if the metadata endpoint was not blocked, and rotate all of them now rather than later. Check whether the same digest runs elsewhere.
  5. Restore service from a known-good digest on a fresh node, and then start the root-cause work: the entry point is usually an application vulnerability, and the SBOM plus the scanner's history for that digest is the first place to look.
  6. Prevention afterwards: a read-only root filesystem, no shell in the image at all, a distroless base makes spawning /bin/sh impossible, egress policies that deny by default, and a blocked metadata endpoint.

Land it Cut the network, keep the container, capture the evidence, rotate every credential it could see, and only then ask how it got in.

Likely follow-ups
"You isolated the network and the attacker's process is still running inside. Does isolation stop it doing damage?"

Network isolation stops exfiltration and command-and-control, which is the urgent damage, but not local damage.

The process can still read anything mounted into the container, including secret files, and it can still write to the writable layer and to any volumes, so if a volume holds business data, it can be altered or encrypted.

It can also try to escape: a container running as root with a writable host mount, or with a dangerous capability such as SYS_ADMIN, can reach the host.

So after the network cut, I would check those three in the first five minutes with docker inspect: the user id, the capability set, and the mounts.

If it is root with a host mount, I would escalate to isolating the host itself, cordoning the node and draining everything else off it.

And I would use docker pause, which freezes every process in the container with the cgroup freezer without killing it, once the evidence captures that need a live process, the memory dump and the process tree, are done; a frozen container preserves its state and stops all damage at once.

"How exactly do you capture process memory and the network state from a running container without tools inside it?"

From the host, using the container's PID namespace. docker inspect --format '{{.State.Pid}}' gives the host PID of the container's init process, and everything else hangs off it.

The process tree is ps --ppid recursively or pstree -p on that PID. Open sockets and established connections are nsenter -t <pid> -n ss -tunap, which runs ss from the host in the container's network namespace and shows the unknown IP with the owning process.

Open files, including deleted binaries still held open, are under /proc/<pid>/fd, and /proc/<pid>/exe is a link to the running binary even if it was deleted from disk, which attackers do. A memory dump is gcore -o /evidence/dump <pid> from the host, or a full-system tool.

All of this goes into a directory whose hash I record, with timestamps, because chain of custody matters if this becomes a legal matter.

None of it requires a shell in the container, which is good, because an attacker who has the container may have replaced the tools inside it.

"The alert turns out to be a legitimate deploy script that runs a shell. How do you avoid crying wolf without turning the detection off?"

By making the legitimate behaviour impossible rather than by tuning the alert to ignore it.

A payments API has no business running a shell in production; if a deploy step needs one, that step belongs in the image build or in an init container, not in the running service.

So the outcome of the false positive is a change to the deploy, plus a distroless image where there is no shell binary to spawn, which turns the detection rule from "alert on shell" into "a shell spawn is now definitionally an exploit".

If a shell is genuinely unavoidable for some service, the rule gets an exception scoped to that image digest and that parent process, with an expiry date, reviewed monthly.

I would also keep the outbound-connection half of the rule unconditional, because an unknown egress destination from a payments container is always worth thirty minutes of someone's time, and an egress deny-by-default policy makes the alert both rarer and more meaningful.

"How do you decide whether the same compromise exists on other instances?"

Two searches, run in parallel with containment.

First, by indicator: the unknown IP and any file hashes from docker diff are searched across the fleet's network flow logs and the runtime security tool's history, which tells me whether other containers talked to that address or spawned the same binary.

Second, by exposure: every container running the same image digest has the same vulnerability, so docker ps --filter ancestor=<digest> per host, or the orchestrator's image inventory, lists the candidates, and each one gets the same evidence pass, process tree and docker diff, before being replaced.

If the entry point was an application vulnerability reached through the API, then the access logs for the same request pattern across all instances answer whether the attacker tried elsewhere.

The default is to assume every instance of that digest is compromised and replace them all from a patched build, because the cost of replacing a clean instance is minutes and the cost of leaving a dirty one is the whole incident again.

"After thirty minutes, what does the next day look like?"

The next day is root cause, scope, and disclosure.

Root cause: the SBOM for the digest against the vulnerability database, the access logs for the first anomalous request, and the memory dump for the payload, aiming to name the vulnerability and the first time it was exploited.

Scope: what data the container could read, whether it did, which credentials it held, and confirmation that every one was rotated; that answer decides whether this is a security incident or a data breach, which in most jurisdictions starts a notification clock of 72 hours.

Recovery hardening: read-only root filesystem, distroless base, dropped capabilities, non-root user, egress policy, blocked metadata endpoint, each verified on the rebuilt service rather than promised.

And the write-up: a timeline with the detection-to-containment time, which for this scenario should be under ten minutes, and the actions that would have prevented it, with owners.

What I would resist is declaring it over because the service is back; the service being back is the end of the first hour, not the end of the incident.

Q148 · Design. "Design the migration of an estate of thirty services, each on its own virtual machine with configuration management, to containers. Where do you start and what do you leave alone?"

Reveal answer

Strong answer Requirements: no big-bang cutover, every service keeps its current service levels during the migration, and the outcome is measured in cost per service and time from commit to production. The design is a four-phase path.

Phase one is inventory and classification: for each service I record how it is configured, where it writes to disk, what it assumes about the host, and whether it is stateless.

Stateless services with configuration already in environment variables are the first wave; anything writing to local disk or depending on host-installed agents is a later wave; and the database and message broker are left as they are, because containerising stateful infrastructure is a separate project with a different risk profile.

Phase two builds the platform pieces from the earlier designs: the golden bases, the build pipeline, the registry, and the golden path template.

Phase three migrates the first wave, one service at a time, running the container on the same virtual machine next to the old process behind the existing load balancer, shifting traffic gradually, and keeping the old process for a week.

Phase four moves the containers off single virtual machines onto an orchestrator, Kubernetes in practice, covered in E10. Trade-off: running old and new side by side briefly doubles cost.

What I would not do is migrate the database first because it is "the biggest win", because it is the biggest risk; I would not rewrite services during the migration, because then a failure cannot be attributed to packaging or to code; and I would not skip the single-host phase to go straight to Kubernetes.

Land it Containerise the stateless services on the machines they already run on, prove the images, then change the infrastructure — one variable at a time.

Likely follow-ups
"What specifically do you look for in the inventory that makes a service a later wave?"

I look for anything that assumes the process owns the machine. Writing to a local path other than /tmp, because that is state that must become a volume or move to a database.

Reading configuration from files that the configuration management tool templated, because that has to become environment variables or a mounted config.

Running more than one process, such as a web server plus a cron plus a log shipper, because a container should be one process and those need splitting. Binding to a fixed port that another service on the same machine expects, which creates an ordering dependency.

Depending on host agents, a local metrics or backup agent, which will not exist inside the container. Running as root or needing kernel modules, which needs a redesign rather than a Dockerfile.

And long startup, because a service that takes three minutes to start needs a startup probe and an orchestrator that understands it. Each of those is a line in the inventory with a yes or no, and the first wave is the services with all noes.

"A service in the first wave was containerised, and on the same VM it now runs 20 percent slower. Why, and what do you check?"

The same machine and the same code, so the difference is in the container's configuration, and there are four usual suspects. A CPU limit: the container may have been given --cpus based on a guess, and the process is now throttled; cpu.stat answers that in seconds.

A JVM that now sees a different processor count or memory limit and picked Serial GC or a smaller heap; -Xlog:os+container=info shows what it read.

The network: if the container is on the default bridge, every connection passes through NAT and a virtual interface, which adds latency to a chatty service; --network host as a test, and then a decision, settles it.

And the filesystem: writes to the container's writable layer go through overlay2 and are slower than a direct disk write, so anything that writes heavily, a cache or a queue, should be on a volume.

I would compare with the old process still running next to it, because that is the whole point of the side-by-side phase: same host, same load, one variable.

"Why leave the database on its VM? Isn't that just fear?"

It is a risk calculation rather than fear, and I can state it. A stateless service in a container gains everything Docker offers: reproducible builds, fast rollback, and easy scaling.

A database gains almost none of that and risks the one thing it cannot afford: its data.

Containerising a database means its storage must be a volume with the right performance and durability, its backup and restore path must be rebuilt and tested, and failover, which the VM setup probably has through the configuration management tool, must be redone.

The upside is a cleaner install and consistent versions, which is real but small.

So the database moves when there is a reason specific to it, such as a managed offering that takes over backups and failover, and it moves as its own project with a restore drill as the acceptance test.

Leaving it alone during the service migration also keeps the blame boundary clean: if something breaks, the data layer did not change. I would say the same for the message broker.

"What if the requirement changed and management wants all thirty services on Kubernetes in three months?"

Then I would keep the order and cut the durations, not skip the steps, and I would say which risks that buys. Inventory and classification stays but takes a week, done as a survey with the service owners rather than a deep audit.

Platform pieces stay but use a managed Kubernetes service and a vendor's base images rather than building our own; the golden path template is a minimal one.

The side-by-side phase on the same VM collapses to a canary on the cluster with the VM kept as the fallback for a week, which is the same idea with the fallback in a different place.

The thing I would not compress is the first wave being the stateless services: three months for thirty services is about two a week, so the order still matters and the stateful ones still go last, and if the deadline forces a database move, that is the item I would push back to management with the restore-test requirement attached.

I would present the three-month plan with the two or three services most likely to slip named up front, so the deadline conversation happens now rather than in month three.

"How do you measure whether the migration was worth it?"

I would define the numbers before starting. Lead time: time from commit merged to running in production, per service, from the pipeline; the target is under an hour where it was a day.

Deploy frequency and rollback time, from the same source; rollback should become a digest switch measured in minutes.

Cost per service: virtual machine hours before against the share of node hours after, from the cloud bill, expecting a two to three times density improvement once services share nodes.

Reliability: incidents and mean time to recover before and after, with the caveat that a migration temporarily raises incident counts and that the honest comparison is three months after the last wave.

And an engineer-time measure that is often the largest: hours per month spent on host patching and configuration management drift, which should drop to near zero for the migrated services.

If lead time and cost did not move, the migration changed the packaging but not the process, and I would say so.

Q149 · Design. "A small team is starting a new product: one backend, one web front end, a Postgres database, three engineers. Make the case for and against Docker, and tell me what you would actually do."

Reveal answer

The real test Whether you can say "not Docker" with a straight face and reasons, and whether you separate the development use from the production use.

Strong answer Assumptions: low traffic for the first year, three engineers with no operations specialist, and a budget that punishes idle infrastructure. I split the question in two.

For development, Docker Compose is almost always worth it: one docker compose up gives every engineer the same Postgres version and the same backend environment, and licensing is not an issue: Docker Engine is free, and Docker Desktop's paid subscription applies only above 250 employees or 10 million dollars in revenue.

For production, the honest options are three.

First, a managed platform such as Fly.io, Render, Cloud Run, or App Runner, which accepts a container image and handles scaling, TLS, and deploys; this uses Docker as a packaging format but the team never operates a daemon or a cluster.

Second, a single static binary, for example a Go or a Java jar with a bundled runtime, run by systemd on one or two virtual machines behind a managed load balancer, with no containers at all; it is the cheapest, and the deploy is copying a file.

Third, serverless functions, which fit only if the backend is request-shaped with no long-lived connections.

What I would actually do is Compose for development and a managed container platform for production, because the image is the same artifact in both places and the platform removes the operational work that three people cannot afford.

What I would not do is run Kubernetes, or even Docker Swarm, for a three-person product; and I would not choose Docker for the desktop parts, GUI tooling, or anything needing GPUs and kernel modules.

Land it Docker as a packaging format is nearly free; Docker as an operating model has a cost, and a three-person team should buy that model from a platform rather than build it.

Likely follow-ups
"You chose a managed container platform. What does that lock you into, and what happens if you outgrow it?"

The lock-in is smaller than it looks because the artifact is a standard image. What is platform-specific is the deployment configuration, the way secrets are injected, the networking between services, and the managed database if we take theirs.

So I would keep the Dockerfile plain, keep configuration in environment variables, keep the database on a provider whose data I can export as a standard dump, and write the deploy step as one command in CI so it is one file to change.

Outgrowing usually looks like one of three things: a cost curve that crosses over a small Kubernetes cluster somewhere around a few thousand dollars a month, a need for something the platform does not offer, such as GPUs or private networking, or latency requirements that need control over placement.

At that point the move is to a managed Kubernetes service with the same image, and the work is writing manifests and re-plumbing secrets and networking, which is a few weeks, not a rewrite.

The verification that it is portable is running the image locally with the same environment variables and seeing it work.

"Defend the systemd-plus-binary option. When would you actually pick it?"

I would pick it when the runtime is a single static binary and the team is more comfortable with a machine than a platform.

A Go binary or a Java application with a bundled jlink runtime is one file; the deploy is scp, a symlink swap, and systemctl restart, and rollback is swapping the symlink back.

systemd gives restart on failure, resource limits through MemoryMax and CPUQuota, which are the same cgroups Docker uses, journald for logs, and socket activation for zero-downtime restarts.

The cost is one virtual machine per environment, a few dollars a month, and the responsibility for patching the operating system, which unattended upgrades handle.

What it lacks is the reproducible environment: the machine accumulates state, a second engineer's laptop differs from it, and adding a second service means either another machine or a hand-managed port scheme.

So it is right for one service with one dependency and wrong the moment the count grows. I would still use Compose for development even in this option, because that half of the value has no operational cost.

"What would you set up on day one, concretely, for the Compose-plus-managed-platform choice?"

Day one is a repository with four files. A Dockerfile with a multi-stage build and a slim base, producing an image under 200 MB, running as a non-root user.

A compose.yaml with the backend, the front end, and Postgres pinned to the same major version the managed database will run, with a named volume for the data and a health check on Postgres so the backend waits for it.

A CI workflow that builds the image on every push, runs the tests inside it, and on the main branch pushes to the registry by digest and deploys to the platform's staging environment, with production as a manual promotion of the same digest.

And a .env.example documenting every environment variable, because the environment is the only configuration mechanism. That is about a day of work and it means the second engineer's first day is git clone and docker compose up.

What I would explicitly not set up is anything for scaling, because with three engineers the first year's traffic will not need it, and adding it later is a slider on the platform.

"The product succeeds and a year later you have 15 engineers and real traffic. What changes, and what do you regret?"

What changes is that the platform's per-request pricing and the single-service model start to hurt, and the team wants environments per branch, background workers, and a queue.

The move at that point is a managed Kubernetes cluster, with the images unchanged, and the work is manifests, secrets, and networking, roughly a month for one engineer.

The likely regrets are small and predictable: environment variables that grew into a hundred undocumented settings, a Compose file that drifted from production because nobody pinned the Postgres minor version, and a lack of structured logging with request ids, which is cheap on day one and painful to retrofit.

So the day-one list gains two items with almost no cost: JSON logs with a request id from the first commit, and a rule that every environment variable has a line in the example file.

What I would not regret is not running Kubernetes for the first year; the time saved went into the product, which is why there are 15 engineers.

Q150 · Design. "We run production on docker-compose across four virtual machines and it is starting to hurt. Design the path forward — and tell me whether Docker Swarm is a reasonable stop along the way."

Reveal answer

Strong answer Assumptions: about a dozen services, deploys done by hand per machine, no automated failover, and a machine failure takes services down until someone notices.

Requirements for the target: scheduling across machines, rolling deploys with health checks, restart on failure, and secrets that are not in a file on disk.

On Swarm: it is still maintained inside Docker Engine 29.x as of Aug 2026, docker stack deploy takes a compose file almost unchanged, and for four machines and a dozen services it delivers scheduling, rolling updates, and overlay networking with a day of work.

Its weakness is the ecosystem: no equivalent of the admission, policy, autoscaling, and operator tooling that Kubernetes has, and the wider ecosystem, vendor charts, and hiring all assume Kubernetes. So Swarm is a reasonable stop only if the fleet will stay at a handful of hosts.

My actual design has two tracks. Track one fixes the compose estate without changing the platform: images promoted by digest, a deploy script driven from CI instead of a laptop, a reverse proxy per host with blue/green so a deploy is not an outage.

That pays off whatever comes next. Track two, over the following quarter, moves to a managed Kubernetes service, EKS, GKE, or AKS, one service at a time, translating compose files to manifests by hand rather than with a converter.

What I would not do is self-host Kubernetes on those four machines, because a small team should never own a control plane, and I would not adopt Swarm as a "temporary" step when the intent is clearly Kubernetes.

Land it Fix the deploy path first because it pays off under any platform; then pick Kubernetes managed by someone else, and treat Swarm as a valid answer only when the fleet will stay small forever.

Likely follow-ups
"Track one is 'fix compose first'. Give me the specific things and the order."

In order of pain removed per day of work. First, images by digest: the compose files reference image: registry/app@sha256:... written by CI, not a moving tag, so every machine runs exactly what was built and rollback is a file change.

Second, deploy from CI: a job that, for each host, runs docker compose pull and docker compose up -d over SSH with the digest-pinned file, so no laptop is involved and every deploy is logged.

Third, health checks on every service in the compose file, with depends_on: condition: service_healthy, so an instance that is not ready does not take traffic.

Fourth, a reverse proxy per host, Traefik or Caddy, with two copies of each service, blue and green, and a deploy that starts the new one, waits for its health check, switches the proxy, and stops the old one; that turns a deploy from a few seconds of 502s into zero.

Fifth, secrets out of the compose file into an environment file with restricted permissions, or a secrets manager fetched at deploy time. That is about two weeks of work and it survives any platform decision.

"Why translate compose to Kubernetes manifests by hand rather than with a converter?"

Because the converter produces something that runs and that nobody understands, and the point of the migration is a set of manifests the team can operate.

Compose and Kubernetes model different things: Compose has services, networks, and volumes on one host; Kubernetes has Deployments, Services, Ingress, ConfigMaps, Secrets, PersistentVolumeClaims, and probes, with concepts like readiness, resource requests, and pod disruption budgets that Compose has no words for.

A converter maps the words it can and leaves defaults for the rest, and the defaults are the wrong ones: no resource requests, no readiness probe, a volume type that may not exist on the cluster.

Translating by hand, one service at a time, forces each of those decisions to be made, and it is about an hour per service using the template from the platform.

I would use the converter's output only as a checklist of what the compose file contained, so nothing is forgotten, and then write the manifests from the template.

"Make the honest case for stopping at Swarm and staying there."

For four machines and a dozen services, Swarm delivers most of what is hurting: docker stack deploy with the existing compose file gives scheduling across the machines, replicas, rolling updates with health-check gating and automatic rollback, overlay networking so services find each other by name, and encrypted secrets stored in the manager.

It is one day of work and no new vocabulary. The bill is the machines already paid for.

The trade is ceiling and ecosystem: no horizontal autoscaling built in, no admission control, no operators for databases and queues, a small community, and a hiring pool that assumes Kubernetes.

As of Aug 2026 Swarm mode still ships in Docker Engine and receives maintenance, but not new features.

So the honest case is: if the business is steady, the team is three or four people, and the fleet will stay under ten hosts, Swarm is the cheaper answer for years, and switching to Kubernetes would be a cost with no benefit.

The test is whether anyone can name a Kubernetes feature they need today; if not, Swarm, revisited in a year.

"What would you cut if you had one month and one engineer for track two?"

I would cut the per-service translation of everything and move only the services that are hurting most, which is usually the two or three that need more than one machine or that fail when a host fails; the rest stay on Compose behind the CI deploy from track one, and move later or never.

I would cut Helm and any templating in favour of plain manifests in a directory per service, because one engineer in one month should not learn two tools. I would cut Ingress controllers with certificates in favour of the cloud provider's load balancer.

What I would keep is the managed control plane, because self-hosting is the one decision that keeps costing; resource requests and readiness probes on every moved service, because without them Kubernetes is worse than Compose; and a rollback that is a manifest revert, tested once before the first production move.

A month like that ends with a working cluster running three services, which is a foundation, and a written list of what was cut, which is the next month.

"How do you verify the Kubernetes move improved things and not just changed them?"

With the numbers that described the pain in the first place. Deploy time and deploy-caused errors, per service, from CI and the proxy logs, which should go from minutes with a blip to under a minute with zero errors.

Recovery from a host failure, which I would test deliberately by draining a node, expecting services back within the pod startup time instead of waiting for someone to notice. Time from a new service's first commit to production, which measures whether the template works.

And the cost line, which will rise at first because a managed control plane and a minimum node count cost more than four machines, and should be justified by the engineer-hours no longer spent on hand deploys.

I would put those on a single dashboard with the before values marked, and review it a month after the last service moves.

If deploys are no faster and recovery is no more automatic, the move added complexity for nothing, and that is worth knowing before anyone proposes a service mesh.

Quick reference — Production and security

Promote by digest
Build once, then move the same digest through environments. A rebuilt tag is a different image, however identical the source.
Scanning and SBOM
A scanner reports known CVEs; the software bill of materials lists what is actually inside. You need the second to answer “are we affected?” the next morning.
Signing and provenance
Keyless signing proves who built it; provenance attestation records how. Both are checked at admission, or they are decoration.
capabilities
Drop all, add back only what you need. Most services need none.
rootless and seccomp
Run as a non-root user, keep the default seccomp profile. Most container escapes need root inside the container to start.

11 · RecapWhat You Can Do Now

  • You can explain a container as a process plus namespaces, a cgroup and an overlay mount — and walk the CLI, dockerd, containerd, shim, runc chain behind docker run
  • You can read a Dockerfile and predict which instruction invalidates the cache, which layer holds the bloat, and why deleting a file in a later layer does not shrink the image
  • You can write a multi-stage Spring Boot image with a layered jar, a non-root user and an exec-form entrypoint, and a Python image with uv, and defend the base-image choice
  • You can diagnose exit code 137 versus a Java OutOfMemoryError, and size the JVM from the cgroup with MaxRAMPercentage instead of the host
  • You can explain why localhost:5432 is refused inside a container, and fix it with a user-defined network and the service name
  • You can choose between a volume, a bind mount and tmpfs, and know what docker compose down -v destroys
  • You can design a build-once, promote-by-digest pipeline with a registry cache, a scanning gate, SBOMs and keyless signing
  • You can state a container hardening baseline from memory, and name the cases where Docker is the wrong tool
🧠 Flex your memory

Close the page and write down, from memory: the three kernel features that make a container, what each of them hides or limits, and the exact chain of programs between docker run and your application becoming PID 1. Then reach back to Chapter E8's durability chapter: a Postgres container writes its data to a named volume — which of the write-ahead-log and fsync guarantees still hold, which depend on the host disk, and what does a container add or remove from that story?