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.
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.
Walk through Docker's client-daemon architecture: the Docker CLI/client, the dockerd daemon, and where containerd and runc fit underneath it via the OCI runtime spec. Then name the core objects a Docker user works with day to day (images, containers, registries, volumes, networks) and give one CI/CD example of each.
Sample Answer
Direct answer
Docker is a layered system, not one program. The docker CLI (command-line interface) is a thin client that talks over a REST API to dockerd, the Docker daemon, which owns image builds, networks, and volumes but does not run containers itself. It delegates that, over gRPC (a fast protocol two separate processes use to call functions in each other directly, instead of a general-purpose web API), to containerd, a separate runtime that manages the full container lifecycle: pulling images, unpacking them, starting containers, and supervising them while they run. For each container start, containerd calls runc, the low-level tool that does the actual kernel work (creating Linux namespaces and cgroups, control groups that isolate and limit a process's resources) to spin up the isolated process. runc implements the OCI (Open Container Initiative) runtime spec, an industry-standard contract for "how to run a container," which is exactly what lets other tools, including how Kubernetes nodes run containers, and Podman (a Docker-compatible container engine that runs without any background daemon at all), share the same runtime layer instead of every tool reinventing container startup from scratch.
The layering, end to end
flowchart TD
CLI["docker CLI"] -->|"REST API"| Daemon["dockerd (daemon)"]
Daemon -->|"gRPC"| Containerd["containerd"]
Containerd --> Shim["containerd-shim"]
Shim --> Runc["runc (OCI runtime)"]
Runc --> Kernel["Linux kernel: namespaces + cgroups"]
Between containerd and runc sits containerd-shim: a small, long-lived process containerd spawns once per running container. runc itself only runs briefly, just long enough to set up the container and start the real process, then it exits; the shim is what stays behind for the container's whole lifetime, keeping its standard I/O streams open and reporting its exit status back to containerd, so a container keeps running even if containerd itself is restarted or upgraded in between.
Why this separation matters in practice: it means containerd can run without dockerd at all, which is exactly how a Kubernetes node runs containers directly through containerd's own interface, with no Docker daemon installed. It also means the OCI runtime spec is what makes an image genuinely portable across engines: an image built by Docker can be run by any OCI-compliant runtime, not just Docker's own stack.
The core Docker objects, each with a CI/CD (continuous integration / continuous delivery) example
- Images: an immutable, layered filesystem plus metadata that serves as a template for containers. CI/CD example: the build stage produces one versioned, immutable image tag that gets pushed exactly once and then deployed unchanged through every later environment.
- Containers: a running (or stopped) instance of an image, with its own writable layer and its own network and process namespace. CI/CD example: the pipeline's own build and test steps often run inside an ephemeral container so every job gets an identical toolchain regardless of which physical runner picked it up.
- Registries: a versioned store and distribution point for images, addressed by name and tag, or more precisely by content digest. CI/CD example: the pipeline authenticates to a private registry to push the freshly built image after the build stage, then pulls that same image by digest in the deploy stage.
- Volumes: durable storage that is decoupled from any one container's lifecycle. CI/CD example: a build-cache volume, or an exported BuildKit cache, persisted between pipeline runs so dependency installation is not repeated from a cold start on every job.
- Networks: the virtual networking Docker creates so containers can reach each other and the outside world. CI/CD example: an integration-test stage starts the application container and a real database container on one shared, user-defined network so tests hit the database by container name, then tears the whole network down when the job finishes.
Trade-offs and pitfalls
Knowing this layering matters when triaging a "Docker" problem that is actually one layer down: a rootless or dockerd-less environment is a containerd question, and a kernel-level failure (a namespace or cgroup error) is a runc question, not a daemon bug. A common confusion worth naming directly: the OCI image spec (the format of an image) and the OCI runtime spec (how to run one) are two separate specifications under the same OCI umbrella, not the same thing.
A containerized service doesn't shut down cleanly during deployments and leaves requests hanging for several seconds. Walk through how you'd investigate PID 1 behavior, signal handling, and graceful termination in Docker to find the cause.
Sample Answer
Direct answer
When a container hangs for several seconds during shutdown, the first thing I check is what process is actually running as PID 1 (the first process in the container's process namespace, which the Linux kernel treats specially: it does not apply default signal behavior the way it does for every other process) and whether that process, or whatever is standing between it and the real application, actually reacts to SIGTERM (the signal Docker sends to ask a process to shut down gracefully). Most "hangs on shutdown" bugs are the application never receiving or never acting on that signal, and Docker eventually giving up and force-killing it once its grace period expires, which is exactly the multi-second delay the symptom describes.
Investigation steps
- Confirm what PID 1 actually is.
docker exec <container> ps auxand look at the process with PID 1. If it is the application binary directly, it is receiving signals directly. If it is a shell (/bin/sh -c "...", which is what Docker uses when aCMDis written in shell form rather than exec form), the shell is PID 1 and the real application is a child process; many shells do not automatically forward a receivedSIGTERMto their children, so the child, the process actually serving requests, may never see the signal at all. - Reproduce and time the shutdown. I verified this directly: running a container whose entrypoint script traps and ignores
SIGTERM(trap 'echo ignoring' TERM; while true; do sleep 1; done),docker stoptook 10.177 seconds to return, anddocker inspect --format='{{.State.ExitCode}}'showed exit code 137 (128 + 9, meaning the process was terminated bySIGKILL, not by exiting on its own). That 10-second figure is not incidental: it is Docker's documented default grace period between sendingSIGTERMand escalating toSIGKILL(configurable viadocker stop -t <seconds>, or aSTOPSIGNAL/stop_grace_periodsetting), which is exactly why a process that ignoresSIGTERMproduces a delay in that neighborhood rather than an immediate or indefinite hang. - Distinguish "ignoring the signal" from "not receiving it." If PID 1 is a shell wrapping the real application, the fix target is different than if the application itself is PID 1 and simply has no signal handler: in the shell case, the shell needs to
execthe application (replacing itself rather than forking a child) so the application becomes PID 1 directly, or a minimal init process needs to sit in front of it to forward signals correctly. - Fix by giving the application a real handler, not just fixing signal delivery. Docker's
--initflag (or an explicit minimal init binary such astini) solves signal forwarding and reaps zombie processes, but it does not by itself make the application shut down gracefully; the application still needs to catchSIGTERM, stop accepting new connections, finish in-flight requests, and exit on its own. Fixing only the forwarding without adding an actual handler still ends in aSIGKILLafter the same grace period, just with the signal correctly reaching the right process. - Verify the fix the same way you reproduced the bug. Re-running the same
docker stoptest after adding a handler should return in well under the grace period, with a clean exit code (typically 0, or 128 + the signal number the application chose to exit on) instead of 137.
Worked example
A Dockerfile using CMD ["node", "server.js"] (exec form) makes the Node process PID 1 directly, so SIGTERM reaches it immediately; if that process has no listener for the SIGTERM event, Node's default behavior does terminate the process, but without ever draining in-flight HTTP requests first, which is why "leaves requests hanging" points more precisely at either a shell-form CMD swallowing the signal, or a caught-but-mishandled signal (a handler registered that does something other than start a graceful drain, such as the trap in my reproduction above, which explicitly ignored the signal and did nothing). The fix in the application is to register a SIGTERM handler that stops the HTTP server from accepting new connections, waits for existing requests to complete (with its own internal timeout shorter than Docker's grace period), and then exits, rather than relying on Docker's grace period as the mechanism that ends in-flight work.
Trade-offs and pitfalls
Reducing docker stop -t to make deployments feel faster without fixing the application's signal handling just changes the symptom from "hangs for several seconds" to "drops in-flight requests sooner," which is worse, not better, for exactly the reliability reason the question is asking about. Adding tini/--init is close to free (negligible overhead, one extra thin process in the tree) and fixes real classes of bugs (signal forwarding through a shell, zombie process accumulation), but it is not a substitute for the application actually implementing a graceful drain, and treating it as one is the most common half-fix I see.
A latency-sensitive service shows occasional CPU throttling, memory pressure, and noisy-neighbor effects when several containers share a host. How would you tune container runtime settings (cgroups, CPU shares, --cpuset-cpus) and application behavior to improve tail latency and node stability, including how you'd share GPU resources fairly if the workload uses them?
Sample Answer
Direct answer
On a shared host, protecting tail latency means giving the latency-sensitive container a guaranteed floor rather than trusting best-effort scheduling to sort itself out: dedicate specific cores to it and cap what noisy neighbors can burst to, rather than only weighting priorities and hoping. GPU sharing needs the same discipline but a different mechanism entirely, because a GPU has no built-in kernel-level time-slicing fairness the way CPU cores do under cgroups (control groups, the Linux kernel mechanism containers use to enforce per-process CPU, memory, and I/O limits).
Diagnosing which kind of contention you actually have
Before tuning anything, distinguish a container being throttled by its own configured quota (checkable per-container via /sys/fs/cgroup/cpu.stat's nr_throttled and throttled_usec fields, which count how often and for how long the cgroup's CPU quota was exhausted) from the host's CPUs genuinely being oversubscribed across containers despite each individual container having headroom in its own quota (checkable via the host's overall load average and run-queue length). The fixes for these two are different: the first is a quota problem for one container, the second is a host-level capacity or scheduling-weight problem across all of them.
Tuning levers
--cpuset-cpusfor hard isolation. Pinning the latency-sensitive container to specific physical cores it does not share with best-effort workloads eliminates cross-core migration and cache-thrashing entirely for that container, at the cost of those cores being reserved even when idle (no automatic work-stealing across the pin boundary).--cpu-sharesfor prioritization under contention. Shares are a relative weight (default 1024) that only changes behavior when the host is actually CPU-contended; giving the sensitive container a higher share (say 4096 against everything else's default) means it wins a larger fraction of CPU time specifically when there is competition, with zero effect when there is not. This alone does not stop a noisy neighbor from bursting to 100% of a shared core for the length of one scheduling period before the weighting evens out, which is enough to cause a visible latency spike even if the long-run average looks fine.- A hard
--cpusquota on the noisy batch containers, not just low shares, caps their absolute ceiling so they cannot burst into full core usage at all, directly bounding the size of the disruption they can cause to a co-located latency-sensitive workload. - Memory:
--memoryplus--memory-swappiness=0for the latency-sensitive container, so a neighbor's memory pressure does not push it into swap, which is catastrophic for tail latency.--memory-reservationsets a soft floor the kernel tries to protect during host-wide memory pressure, which is the safer lever than--oom-kill-disable(removing the kernel's out-of-memory safety valve entirely is not a fix, it just changes what kind of failure happens next). - Application behavior: connection pooling and backpressure so the application sheds load explicitly under contention rather than queuing silently, since an unbounded queue is what actually turns a brief CPU stall into a multi-second latency spike downstream.
GPU fairness
Unlike CPU cores, a GPU is not preemptible the same way: once a compute kernel is running, it generally cannot be paused mid-execution to let another process's work through, so naive sharing means one workload's launch can block the GPU's execution queue for as long as it runs. Two real hardware/software mechanisms exist for fairness on newer NVIDIA data-center GPUs: MIG (Multi-Instance GPU), which physically partitions one GPU into isolated hardware instances with their own memory and compute slice, giving hard capacity isolation at the cost of fixed, coarse-grained partition sizes (you cannot carve out an arbitrary 10% slice); and MPS (Multi-Process Service), which time- and space-shares a single GPU context across processes with a configurable per-client limit (the CUDA_MPS_ACTIVE_THREAD_PERCENTAGE environment variable), giving finer-grained sharing but no fault isolation between clients, since a client that crashes can potentially disrupt the shared MPS server context for everyone co-scheduled on it. Where neither is available, the practical fallback on a single host is coarser: assign whole GPUs per workload (--gpus device=<id>) rather than attempting to share one GPU between a latency-sensitive and a best-effort workload at all.
Trade-offs and pitfalls
--cpuset-cpus pinning is a static partition: it wastes capacity when the pinned cores sit idle while other cores are saturated, since nothing can migrate across the boundary automatically. MIG's hard isolation can under-utilize a large GPU for a small job because partition sizes are fixed, not arbitrary. MPS's finer granularity comes at the cost of losing the fault isolation MIG provides. The most common mistake on a single shared host is reaching only for --cpu-shares and assuming it solves burst-driven tail-latency spikes, when a hard quota on the noisy workload, or physical core separation, is what actually bounds the worst case rather than just improving the average.
Your CI Docker builds intermittently fail while downloading packages, with timeouts or 502s. Walk through how you'd systematically troubleshoot and mitigate this: retries, package mirrors, dependency caching, and how you'd rule out DNS or proxy issues on the CI runner network.
Sample Answer
Direct answer
I treat intermittent package-download failures as a network triage problem before a build problem: first isolate whether the failure sits on the CI (continuous integration, the automated system that builds and tests every change) runner's network path or on the far side at the registry, then add resilience (retries, mirrors, caching) so a transient blip does not fail the whole pipeline, and only after that look at whether the underlying rate or capacity limit needs a structural fix.
Systematic troubleshooting steps
- Capture the exact failure, not just "it failed." A timeout (the client gave up waiting) and a 502 (the server or an intermediate proxy returned a bad gateway response) point in different directions: a timeout suggests a slow or congested path, a 502 suggests the registry or a caching proxy in front of it is unhealthy or overloaded, not the runner's network.
- Rule out DNS on the runner itself. Docker builds can resolve names using a different resolver configuration than the host (the daemon's
--dnssetting, or aresolv.confbaked into the build container), so test resolution from inside the same execution context the build uses, not just from the host shell:docker run --rm alpine nslookup registry.npmjs.org(or the relevant registry hostname) using the same network mode the CI job uses. - Rule out a proxy misconfiguration. If the runner sits behind an HTTP/HTTPS proxy, confirm the proxy environment variables are actually propagated into the build (
--build-arg HTTP_PROXY=... --build-arg HTTPS_PROXY=... --build-arg NO_PROXY=...for BuildKit (Docker's build engine, the default backend behinddocker build), since build-time environment is not automatically inherited from the host shell), and check whether internal package mirrors were accidentally routed through the external proxy via a missingNO_PROXYentry. - Check for shared-egress rate limiting. Self-hosted runners commonly share one NAT (Network Address Translation, the mechanism that lets many internal machines share one public IP address) gateway IP. If several concurrent jobs pull from the same public registry, they can collectively exhaust that registry's per-IP rate limit even though no single job is doing anything wrong. Docker Hub, for example, currently documents a pull-rate limit of 100 pulls per 6-hour window per IP address for unauthenticated pulls and 200 pulls per 6-hour window for an authenticated free-tier account; a fleet of shared runners hitting Docker Hub anonymously is a textbook source of intermittent 5xx-and-timeout style failures that look random but are actually load-dependent.
- Add retries with backoff at the package-manager level, not just at the CI-step level: most package managers support this natively (
npm config set fetch-retries 5 fetch-retry-mintimeout 5000,pip install --retries 5,apt-getwithAcquire::Retries=5), so a single dropped connection does not fail the whole job. CI-step-level "retry the whole job" retries are a much blunter and slower fallback for the same problem. - Add a mirror or pull-through cache for the packages and images the build depends on (an internal npm/PyPI proxy such as Artifactory or Verdaccio, or an authenticated pull-through mirror for base images) so most requests never leave the internal network, and the ones that do are authenticated rather than anonymous.
- Add dependency caching (a package-manager cache directory persisted between CI runs, or a BuildKit cache mount, which keeps a package-manager cache across builds without baking it into an image layer) so a transient failure on a package you already fetched last run does not even trigger a new network request.
- Confirm the fix by measuring failure rate, not a single green run. Re-run the pipeline enough times (or track the failure rate over the following days) to see the intermittent-failure rate actually drop, since a single passing run after a change proves nothing about a problem that was intermittent to begin with.
Trade-offs and pitfalls
Retries alone can mask a real, worsening capacity problem: if a shared-IP rate limit is the root cause, retries just spread the same load over more time and eventually stop working as traffic grows, so the actual fix is authenticating pulls or standing up a mirror, not retrying harder. Mirrors and caches add an operational dependency of their own (someone now owns keeping that internal proxy up and its cache warm), and a mirror that silently falls behind upstream can serve a stale or vulnerable package version without anyone noticing until it matters.
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.