Containerization and Docker Fundamentals Questions
Packaging applications into containers: images and layers, Dockerfiles, registries, image optimization and security, container networking and storage, and the container runtime model. Covers how containers differ from virtual machines, image build and management, and the fundamentals that underpin any orchestration platform. The container primitive before orchestration.
Design a retention and cleanup policy for a private registry that's accumulated hundreds of tags from experiments, feature branches, and old releases. Balance storage cost against developer convenience, reproducibility, and rollback capability: lifecycle rules (keep latest N per branch pattern), tag immutability, and how you'd schedule garbage collection.
Sample Answer
Direct answer
I design retention as tiers keyed to what a tag actually represents, not a single blanket rule: release and production-facing tags are protected and effectively kept forever, branch and experiment tags decay automatically on a short clock, and garbage collection runs as a scheduled, low-traffic maintenance job rather than an ad hoc cleanup, so nobody has to manually decide what is safe to delete.
The design
| Tag class | Retention rule | Immutability | Rationale |
|---|---|---|---|
Release / semantic-version tags (v1.4.2, prod-*) | Keep indefinitely (or until an explicit, reviewed deprecation) | Immutable: once pushed, the tag can never be overwritten | These are the rollback targets; losing one or letting it silently change content is a production incident waiting to happen |
main/default-branch build tags | Keep last N (for example, last 20) plus anything referenced by a currently-deployed environment | Mutable is acceptable, but each build gets a unique tag (commit SHA or build number) so nothing is overwritten in place | Bounds storage growth from continuous integration while preserving enough history for a same-day rollback |
Feature-branch tags (feature/*, pr-*) | Keep the last 3 to 5 pushes per branch pattern, and expire automatically after a fixed idle window (for example, 14 days with no new push and no pull) | Mutable | These exist for review and short-lived testing; nobody rolls back to a feature branch's image in production |
Experiment / scratch tags (exp-*, ad hoc developer pushes) | Keep for a short fixed window (for example, 3 to 7 days) regardless of activity | Mutable | Genuinely disposable; the cost of keeping hundreds of these indefinitely outweighs the rare case someone wants one back |
Garbage collection (GC, the process of reclaiming storage for image layers no longer referenced by any remaining tag or manifest) is scheduled during low-traffic hours rather than triggered manually, because a naive GC run that walks the whole blob store while pushes are actively happening can race with an in-flight push and, on registries that require it, needs the registry put into a read-only or maintenance mode for the duration. This differs sharply by registry implementation and matters when choosing one: a self-hosted registry (the open-source Docker Registry, or Harbor, a registry that adds retention policies and tag immutability rules on top of it) needs an explicit, scheduled GC job and, on the open-source registry specifically, historically needs the registry to be read-only while GC runs to avoid corrupting in-flight uploads. A managed registry like Amazon ECR (Elastic Container Registry, AWS's managed container registry) has no manual GC step at all: you configure lifecycle policies (rules like "expire untagged images after 14 days" or "keep only the last 10 images matching feature/*") and the service reclaims storage automatically and continuously.
Worked example
For a registry that has accumulated hundreds of tags from months of unmanaged experimentation, the rollout is staged rather than a one-shot deletion: first, tag every existing image against the classification above (a one-time audit script that reads push metadata and branch-name patterns), then apply the new lifecycle rules going FORWARD only (new pushes obey the tiers immediately), then run a single manual cleanup pass on the pre-existing backlog using the same rules with a dry-run flag first, so the retention design is validated against real data before anything is actually deleted. Concretely, an ECR lifecycle policy rule expressing the feature-branch tier looks like: match tag prefix feature/, keep the most recently pushed 5 images matching that prefix, expire the rest. A second rule expresses the experiment tier: match tag prefix exp/, expire any image pushed more than 7 days ago, with no count-based exception.
Trade-offs and pitfalls
The main cost-versus-convenience trade-off is the idle-window length on feature and experiment tags: a shorter window saves more storage but increases the chance someone needs an image that already expired (usually recoverable by rebuilding from source, since the tag was never a durable artifact, but still a real interruption). The most common design mistake is applying one retention rule uniformly across all tag classes, which either keeps release tags too loosely (a rollback target could theoretically be garbage-collected) or expires experimental tags too slowly (storage cost creeps up for images nobody was ever going to reuse). Tag immutability on release tags specifically closes a separate but related risk: without it, someone can accidentally push new content to an existing release tag, which silently breaks reproducibility for anyone who redeploys that "same" version later, independent of whatever the retention window is set to.
What is a Docker image layer, and how does Docker's build cache decide whether a layer from a previous build can be reused? Given a project where dependencies rarely change but source code changes often, how would you order your COPY and RUN instructions to maximize cache reuse, and what causes a cache miss?
Sample Answer
Direct answer
Each instruction in a Dockerfile that touches the filesystem (RUN, COPY, ADD) produces one layer, and Docker's build cache reuses a previous layer instead of re-executing the instruction when two conditions hold: the instruction's own inputs are unchanged (the exact command text for RUN, or the exact file contents and metadata for COPY/ADD), and every layer before it in the build was also a cache hit. That second condition is the one people forget: a single cache miss invalidates every layer after it, even if those later instructions did not change at all.
How the cache actually decides reuse
For a RUN instruction, Docker compares the instruction string itself (and the parent layer's cache key) against previous builds; if they match, it reuses the cached layer without re-executing the command. For COPY/ADD, Docker additionally checksums the source files being copied; if any file's contents or metadata changed, that layer is a cache miss, no matter how the instruction was worded. Once a layer misses, Docker cannot know whether the filesystem state going into the next instruction is still what it was before, so it must invalidate and rebuild every instruction after it too.
Worked example
Given requirements.txt (rarely changes) and app.py (changes often), compare two orderings.
Bad order (dependencies installed after the whole context is copied):
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "app.py"]
Good order (dependency files copied and installed first, source copied last):
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
After an initial build of both, changing only app.py and rebuilding gives, for the bad order:
=> CACHED [2/4] WORKDIR /app
=> [3/4] COPY . . # cache miss: app.py is part of this COPY, so its checksum changed
=> [4/4] RUN pip install --no-cache-dir -r requirements.txt # re-runs, no CACHED tag
and for the good order:
=> CACHED [2/5] WORKDIR /app
=> CACHED [3/5] COPY requirements.txt .
=> CACHED [4/5] RUN pip install --no-cache-dir -r requirements.txt # CACHED
=> [5/5] COPY . .
The pip install step is a re-run every time in the bad ordering (that was measured directly: the same one-line change to app.py forced RUN pip install to execute in the bad Dockerfile and stay CACHED in the good one), because COPY . . includes app.py, so any source change invalidates that layer and every layer after it, including the expensive dependency install. In the good ordering, requirements.txt is copied and installed before the source code is ever touched, so a source-only change cannot invalidate the install step at all.
What causes a cache miss
A RUN line's text changing (even whitespace or a reordered flag), any file changing that a COPY/ADD references (including files you did not mean to include, if your .dockerignore is missing or incomplete), a different base image digest, or a build argument (ARG) used earlier in the file changing value. The single most common unintentional miss is copying the entire build context (COPY . .) before installing dependencies, which ties the expensive install step's cache key to files that change on every commit.
What's the difference between CMD and ENTRYPOINT in a Dockerfile, and between their shell form and exec form? Give one example where ENTRYPOINT is preferred and one where CMD is preferred, and explain why exec form matters for how the container's main process receives signals like SIGTERM.
Sample Answer
Direct answer
CMD sets the default command a container runs, and it can be fully overridden by whatever is passed after the image name on docker run. ENTRYPOINT sets the fixed executable that always runs; anything from CMD, or arguments passed to docker run, is appended to it as arguments instead of replacing it. Shell form (CMD myapp --flag) runs the command through /bin/sh -c; exec form (CMD ["myapp", "--flag"]) runs the binary directly, without a shell in between, which matters specifically because of how Linux delivers signals like SIGTERM.
When to prefer each
Prefer ENTRYPOINT when the image should behave like a fixed, single-purpose binary and you want docker run arguments to feel like command-line flags to that binary; the classic example is a CLI tool image like docker run mytool --version, where ENTRYPOINT ["mytool"] plus no CMD means any arguments the user supplies are passed straight through to mytool. Prefer plain CMD when the image is meant to run one sensible default command that a user might reasonably want to replace entirely, such as a base development image where CMD ["python", "app.py"] is the default but someone might run docker run myimage bash to get a shell instead; with only CMD set, that fully replaces the default command as intended.
Shell form, exec form, and why exec form matters for signals
docker stop sends SIGTERM to the container's PID 1 process, waits a grace period (10 seconds by default), and then sends SIGKILL if the process has not exited. In shell form, the actual application is often started as a child of /bin/sh -c "..."; whether the shell then forwards SIGTERM to that child, or the shell instead sits as PID 1 and the application never sees the signal at all, is implementation detail you should not rely on, and it varies by exactly what the command string does (a single simple final command is sometimes optimized away by the shell into a direct exec, but anything with multiple statements, pipes, or && may leave the shell resident as PID 1). Exec form removes that ambiguity entirely by making your application the literal PID 1 process, guaranteed, with no shell in between.
That said, there is a second, separate wrinkle worth knowing: being PID 1 inside a container's process namespace changes how the Linux kernel applies default signal dispositions. A process that has not explicitly installed a SIGTERM handler normally terminates on SIGTERM by default, but the kernel suppresses that default action specifically for PID 1, so an application with no explicit signal handler can ignore SIGTERM even in exec form. This was verified directly: a plain sleep 100 running as exec-form PID 1 with no init process ignored SIGTERM completely and rode out the full grace period before being SIGKILLed (docker stop -t 3 took the full 3.2 seconds), while the same binary run under docker run --init (where a tiny init process, not the application, is PID 1, and sleep runs as a normal child at PID 2) received SIGTERM's default action immediately and exited in about 0.1 seconds.
What this means in practice
Exec form is necessary but not sufficient for graceful shutdown: it guarantees your application (not a shell) receives the signal Docker sends, but if your application does not install its own SIGTERM handler, running it as PID 1 without an init process can still mean it never actually reacts to the signal and just waits out the timeout before being force-killed. The two-part fix is exec form plus either an explicit signal handler in the application, or docker run --init (or an init process like tini baked into the image) so the application is not PID 1 at all and gets ordinary signal-handling semantics.
What's the difference between COPY and ADD in a Dockerfile? Give two concrete examples where ADD's extra behavior (remote URL fetching, auto-extracting local tar archives) matters, and explain why COPY is generally preferred in production Dockerfiles.
Sample Answer
Direct answer
COPY does exactly one thing: it copies files or directories from the build context into the image. ADD does that too, plus two extra behaviors: it can fetch a file from a remote URL directly into the image, and it will automatically extract a recognized local archive (like a .tar.gz) into the destination directory. COPY is preferred in production Dockerfiles precisely because it has no hidden behavior: what you see in the instruction is exactly what happens to the filesystem.
ADD's extra behavior, made concrete
Both behaviors were verified directly in the same Dockerfile:
FROM alpine:3.20
WORKDIR /app
ADD archive.tar.gz /app/extracted/
ADD https://www.google.com/robots.txt /app/remote/robots.txt
RUN ls -la /app/extracted && head -c 100 /app/remote/robots.txt
Building this produced the extracted contents of archive.tar.gz under /app/extracted/ with no separate tar command needed, and the fetched contents of robots.txt readable under /app/remote/, confirming both auto-extraction of a local archive and remote URL fetching happen from a single ADD line with no other instruction involved. (A remote URL source is the one exception to auto-extraction: since a newer Dockerfile syntax release, a tar archive fetched from a URL is left compressed unless you pass ADD --unpack <url> <dest>; only a local archive source auto-extracts with no flag, which is what this example uses.)
Example 1, auto-extraction: shipping a vendored dependency or dataset that arrives as a .tar.gz; ADD dataset.tar.gz /data/ extracts it in one step, where COPY would leave the compressed archive sitting in the image unextracted, requiring an additional RUN tar -xzf ... (which then also leaves the original archive file taking up space in that layer unless you clean it up in the same instruction).
Example 2, remote URL fetching: pulling a fixed, versioned release artifact directly by URL during the build. Two assumptions worth checking here, both tested directly rather than assumed: first, ADD for a URL is not simply cached on the URL and Dockerfile text staying the same. Serving a file locally, building ADD http://.../file.txt /app/file.txt, then changing the file's contents on the server without touching the URL or Dockerfile and rebuilding with no --no-cache flag produced the new content, not a stale cached copy; a further rebuild with the content unchanged then did hit the cache. BuildKit revalidates the remote resource on every build and only reuses the cached layer when the content is actually unchanged. Second, ADD does support integrity verification: ADD --checksum=sha256:<hash> <url> <dest> fails the build outright on a mismatch, confirmed directly by supplying a deliberately wrong digest against a real server and getting ERROR: ... digest mismatch, so "no way to verify integrity" is only true for a bare ADD <url> with no --checksum supplied, not for ADD categorically.
What still makes many teams prefer an explicit RUN curl -fsSL ... -o file && sha256sum -c ... over ADD for this case: --checksum is opt-in and easy to forget (a plain ADD <url> with no flag verifies nothing, and the Dockerfile still builds fine without it, so there is no forcing function to add it), the network fetch happens as an opaque step in the build graph rather than a scriptable command you can retry, mirror, or attach custom auth headers to inline, and either way the build still depends on a live, reachable URL: neither approach makes the build reproducible without network access.
Why COPY is generally preferred in production
COPY's behavior is fully predictable from reading the instruction: no network access happens during the build, no archive is silently unpacked when you only meant to copy a file that happened to be named something.tar.gz, and there is no ambiguity about what ended up in the image. ADD's extra behaviors are occasionally exactly what you want (vendoring a local archive, or a URL fetch with --checksum pinned), but reaching for ADD as a habit means every reader of the Dockerfile has to remember to check whether a given source path might trigger auto-extraction or a network fetch, and whether that fetch is actually checksummed or just a bare unverified download, which is exactly the kind of hidden behavior a production build should not depend on implicit knowledge to get right.
You're asked to harden a container image that currently runs as root, ships shell utilities, and is built from a large general-purpose base image, exposing an API to untrusted input. Propose a runtime hardening policy: seccomp profiles, dropping Linux capabilities, a read-only root filesystem, rootless containers, and how you'd enforce and audit these at deploy time, while keeping the service actually operable.
Sample Answer
Direct answer
For a container that runs as root, ships general shell utilities, is built from a large general-purpose base, and is directly exposed to untrusted input, the goal is defense in depth: assume the application itself will eventually be exploited, since it is the one thing an attacker directly controls, and make sure a successful exploit lands in a process with almost nothing useful available to it. No root privileges, no unnecessary Linux capabilities, no writable filesystem, and no shell or general-purpose tooling to pivot with.
The policy, layer by layer
- Run as a non-root user. Add a dedicated user in the Dockerfile and set
USER, so a process compromise does not automatically hand the attacker root inside the container. This alone does not stop a container-escape-class exploit, but it removes the most common privilege-escalation shortcut and is a prerequisite for the other controls below being fully effective: a read-only root filesystem matters far less if the compromised process is still root and able to remount things. - Drop Linux capabilities. Linux capabilities are the finer-grained privileges historically bundled together into "root": binding low network ports, changing file ownership, loading kernel modules, and dozens more. Docker grants a small default set to every container, and a typical API service needs almost none of it.
--cap-drop=ALL, then adding back only what is strictly required (commonly nothing at all for a plain HTTP service;CAP_NET_BIND_SERVICEonly if it must bind a port below 1024), shrinks what a compromised process can even ask the kernel to do, regardless of its user ID. - Read-only root filesystem.
--read-onlyat runtime makes the entire root filesystem immutable, combined with atmpfsmount for the one or two paths the application genuinely needs to write to, a cache directory,/tmp. Even a successfully injected payload cannot persist itself to disk inside the container or tamper with the application's own binaries. - Rootless containers, a different control from a non-root USER. The
USERinstruction changes which user ID the process runs as inside the container. Rootless mode goes a layer deeper: it runs the container engine itself without root privileges on the host, using Linux user namespaces so that even a process that is user ID 0 inside the container maps to an unprivileged, ordinary account on the host. A container-escape exploit that would normally hand an attacker host root instead hands them an unprivileged host account, a meaningfully smaller blast radius if the layers above somehow fail. - Seccomp. A seccomp (secure computing mode) profile is a kernel-enforced allowlist or denylist of which system calls a process may make at all. The engine's default profile already blocks a range of dangerous, rarely needed syscalls, including loading kernel modules; a custom profile generated from tracing what a specific workload actually uses, denying everything else, closes off entire exploitation techniques, since many container-breakout and privilege-escalation chains rely on a syscall the application itself never legitimately needs.
Enforcing and auditing at deploy time
None of the above helps if it is only a suggestion in a document. Enforce it at the deploy gate, a policy engine or admission controller that rejects a deployment specification missing a non-root user requirement, a dropped-capabilities list, or a read-only filesystem setting, rather than trusting every team to remember. Audit continuously by periodically diffing running container configurations against the required policy and alerting on drift, since a policy checked only at initial deploy time misses a manual run or an emergency change that bypassed the pipeline.
Worked example, measured
This exact hardening stack was built and run against a small HTTP service: a dedicated non-root user baked into the image, started with --read-only --cap-drop=ALL --security-opt no-new-privileges --tmpfs /tmp. Inside the running container, whoami returned the unprivileged application user, not root, and id showed no supplementary groups beyond that user's own group. The service still answered a real request over its published port with the expected response body, confirming the hardening did not break operability. Attempting to write a file outside the tmpfs mount (touch /app/newfile) failed with "Read-only file system," confirming the control was actually enforced rather than merely configured.
Trade-offs and pitfalls
A read-only root filesystem breaks any application that writes logs, temp files, or cache data to an unexpected path by default; audit what the application actually touches, or test it once with --read-only in staging, before enforcing it in production, and provide tmpfs or volume mounts for the legitimate write paths rather than disabling the control entirely. Dropping every capability can break something subtle that quietly relied on one, binding a low port, or a health check needing a specific network privilege, so validate functionally, not just that the image built successfully. A custom seccomp profile generated from one narrow test run can be too restrictive if it never exercised every code path, an error-handling branch that needs a syscall the happy path never calls, so generate it from realistic, broad testing, or accept a slightly looser default profile over an untested custom one that breaks in production on the first edge case.
Unlock Full Question Bank
Get access to all Containerization and Docker Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.