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.
A large model or data file needs to be available to an inference container, and it's updated periodically without wanting to rebuild the image every time. Compare baking the file into the image, mounting it as a volume, and downloading it at container startup: discuss image size, deployment speed, reproducibility, and how you'd make sure a running instance references the correct version and can be rolled back.
Sample Answer
Direct answer
Downloading the artifact at container startup is usually the right default for a large model or data file that updates periodically: it keeps the image small and fast to build and deploy, and it decouples "ship a new model" from "ship a new image," as long as you pin an explicit, immutable version identifier (not a mutable "latest" pointer) so a given running instance's artifact version is always known and reproducible, and can be rolled back by simply changing that identifier and restarting. Baking the file into the image is worth the size and rebuild cost only when startup-time download latency or availability of the download source is itself unacceptable; mounting it as a volume is a reasonable middle ground mainly when many containers on the same host need to share one already-downloaded copy without each downloading it independently.
Structured elaboration
Baking the file into the image
- Image size: the artifact becomes part of every image layer and every pull; a multi-gigabyte model turns a normally fast image pull into a slow one, on every deploy, even when the model itself has not changed.
- Deployment speed: startup is instant once the image is pulled (no download step at container start), but the image pull itself is now the bottleneck, and it is paid by every node that pulls the image, not just once.
- Reproducibility: strongest of the three options. The exact model version is content-addressed as part of the image's own layers; a given image tag can never silently start serving a different model version later, because the model is baked into that specific, immutable image.
Mounting it as a volume
- Image size: smallest of the three for the image itself, since the artifact never touches the image at all.
- Deployment speed: fast once the volume is already populated on a given host, since no download happens at container start; the cost instead shows up as an out-of-band step (populating or updating the volume) that needs its own process and timing, separate from a normal container deploy.
- Reproducibility: weakest of the three unless carefully managed, because the volume's contents can drift independently of the container image (nothing about deploying a new image guarantees the volume was also updated to match), so this needs an explicit, disciplined process to keep the two in sync.
Downloading it at container startup
- Image size: smallest, same as the volume approach, since the artifact is fetched fresh from wherever it is stored (an artifact registry, object storage) and never lives in the image.
- Deployment speed: startup now includes a download, which adds real latency (and a real dependency on the download source's own availability) to every container start, including autoscaling events, not just deploys.
- Reproducibility: as strong as baking it in, provided the artifact reference used at startup is an immutable, versioned identifier (a specific object key or a content hash), not a mutable pointer like
latestorcurrent; with an immutable reference, "which version is this instance running" is answered exactly, by simply reading which reference it was started with.
Ensuring a running instance references the correct version, and can be rolled back
Regardless of which mechanism is chosen, the version identifier itself is the actual source of truth, and it needs to be explicit and immutable: an environment variable or deployment manifest field naming an exact artifact version (MODEL_VERSION=2026-09-01-a3f1c9, or a specific, versioned object storage key), never a mutable alias. Rolling back is then just redeploying with the previous version identifier; the mechanism (baked-in, volume, or download-at-startup) determines how that identifier gets translated into actual bytes on disk, but the rollback operation itself is the same regardless: change one value, restart. Emitting the resolved version identifier into the application's own logs and a /version-style endpoint at startup makes "which model is this specific running instance actually using right now" answerable directly, rather than inferred from deploy history.
Worked example
A team ships weekly model updates and picks download-at-startup with an explicit versioned key. The deployment manifest sets MODEL_URI=s3://models/fraud-detector/2026-09-15-v14.bin (an immutable, dated, versioned object key, never latest); on startup, the container downloads exactly that object, logs loaded model version 2026-09-15-v14, and serves from it. When the newly trained 2026-09-22-v15 model shows a regression in production, rolling back is changing the manifest's MODEL_URI back to the v14 key and restarting the affected containers; every instance immediately downloads and serves the known-good version again, with no image rebuild involved, and the exact version any given instance is serving is always visible in its own startup log line and version endpoint.
Trade-offs & pitfalls
- Using a mutable pointer (
latest.bin,current-model) instead of an explicit version identifier is the single most common mistake here: it makes "which version is running" unanswerable from the deployment configuration alone, and makes rollback impossible without separately tracking what the pointer used to mean at some earlier time. - Download-at-startup adds a real dependency on the download source's availability and latency at exactly the moment a container is trying to become ready (including during an autoscaling event under load, which is a bad time to discover the artifact store is slow); this needs its own retry and timeout handling, and ideally a local cache shared across restarts on the same host so a full re-download is not required every time.
- A volume-based approach without a disciplined, automated update process is prone to silent drift, where the volume's actual contents no longer match what anyone believes is deployed; this option is worth the complexity mainly when the sharing benefit (many containers on one host, one download) clearly outweighs that risk.
A faulty release tagged prod just got deployed. Walk through how you'd perform an immediate rollback to the previous known-good image using image digests with a Docker Compose stack, and how automation (recording the last-known-good digest, a one-command rollback script) could make this safer and faster next time.
Sample Answer
Direct answer
A rollback under a faulty prod tag has one job: get back to the exact previous image bytes as fast as possible, without relying on a rebuild, since even a rebuild from "the same" source tag is not guaranteed to reproduce identical bytes if a base image or a dependency resolves differently since then. With Docker Compose, that means pointing the affected service at the previous image's content digest directly and recreating just that one service.
The immediate rollback
- Find the last known-good digest. If digests were already being recorded at deploy time, this is a lookup in the deploy log, not a hunt. Without that record,
docker images --digestsor the registry's own tag history is the fallback, which is exactly the gap worth closing before an incident, not during one. - Point the compose file at that digest, not the floating tag:
services:
app:
image: registry.example.com/app@sha256:d6cd6f0583314b6592c3e0b0ae2f6778a6b2373e9cf283c3d979c65c7ebf47d7
- Recreate only that service:
docker compose up -d --no-deps app(adding--force-recreateif Compose believes nothing changed). This pulls the pinned digest, guaranteed to be the same bytes as before since digests are content-addressed, and swaps only that one container, leaving sibling services and the network untouched. - Verify before declaring it done. Confirm the running container's actual image digest matches what was intended (
docker inspect --format='{{.Image}}'cross-checked against the pulled digest), and that health checks or smoke tests pass. A rollback that silently landed on the wrong digest is worse than a slower, correct one.
Making this safer and faster with automation
- Record last-known-good automatically. Every successful, health-checked deploy writes its digest to a small, durable record, a file, a row in a deploy-tracking table, or a tag like
app:last-goodthat only the automated pipeline is ever allowed to move. This turns step one above from a stressful hunt through logs into a lookup that already exists before the incident happens. - A one-command rollback script. Wraps the steps above into a single invocation: it reads the last-known-good record, updates the compose file's image reference for that one service, runs the targeted
docker compose up -d --no-deps, then runs the same smoke test the normal deploy pipeline runs before declaring success. The goal is that an on-call engineer under pressure runs one command instead of reconstructing this whole sequence from memory. - Guardrails. The rollback script should refuse to "roll back" to the digest that is already running, protecting against accidentally rolling back twice, and should log its own action to the same deploy-tracking record a normal deploy would, so the audit trail stays accurate even during an incident.
Trade-offs and pitfalls
Rolling back the image alone does not roll back anything that shipped alongside it: a database migration that ran with the bad release does not reverse itself, so a rollback plan needs a documented answer for what happens when the bad release also changed schema, not just code. --no-deps matters specifically because a full docker compose up -d can recreate dependent services too if their configuration appears to have changed, a much bigger blast radius (a bigger set of things a mistake could break) than the incident called for. Automating "last known good" purely as "the previous deploy" is subtly wrong if that previous deploy was also bad; the record should track the last deploy that actually passed a real health check, not merely the one immediately before this one chronologically.
How would you containerize a training job that needs a GPU? Discuss the host driver and container runtime requirements, choosing a CUDA-enabled versus CPU-only base image, how you pass GPUs into the container (--gpus, the NVIDIA Container Toolkit), and the common pitfalls that leave GPU devices invisible inside the container.
Sample Answer
Direct answer
Containerizing a GPU training job needs three things lined up correctly: the GPU driver lives on the host, never inside the container; the container runtime needs the NVIDIA Container Toolkit installed and configured so Docker knows how to expose GPU devices to a container at all; and the image itself needs a CUDA-enabled base only if the code actually calls into CUDA (NVIDIA's GPU programming toolkit and runtime), since a CPU-only base is smaller, faster to pull, and perfectly correct for anything that does not use the GPU. GPUs are then made visible to a specific container with the --gpus flag (--gpus all, or --gpus device=0 for a specific one); when that flag is missing, or the toolkit is not configured, the container silently gets no GPU access at all rather than a clear error, which is the single most common way this setup goes wrong.
Structured elaboration
Host driver and container runtime requirements
- The NVIDIA driver is installed once, on the host, matching the host's actual GPU hardware; it is never installed inside the container image, and containers do not each need "their own" driver.
- The NVIDIA Container Toolkit is installed on the host and configured against Docker specifically by running
sudo nvidia-ctk runtime configure --runtime=docker, which edits Docker's own daemon configuration to register an NVIDIA-aware container runtime, followed by restarting the Docker daemon. Without this step, the--gpusflag has nothing to act on, and Docker treats the request as a no-op rather than an error. - The container's CUDA toolkit version (whatever the base image ships) has to be compatible with the host driver's supported CUDA version ceiling; a driver only supports CUDA versions up to a certain release, so a container built against a much newer CUDA toolkit than the host driver supports will fail or silently fall back at run time, not at build time.
Choosing a CUDA-enabled versus CPU-only base image
NVIDIA publishes the nvidia/cuda image family in three flavors: base (just the CUDA runtime libraries needed to execute already-compiled CUDA code), runtime (base plus the CUDA math libraries used by common frameworks), and devel (runtime plus the compiler and headers needed to build CUDA code from source). A training job that only runs pre-built framework code (a standard PyTorch or TensorFlow training script) needs at most a runtime base; a job that compiles a custom CUDA kernel needs a devel base in its build stage specifically, with the smaller runtime base used for the final image in a multi-stage build, following the same builder-then-copy pattern used for any other compiled artifact. Anything that never touches the GPU (a data-preprocessing step, a CPU-only inference path) should use a plain CPU-only base image; there is no correctness reason to carry CUDA's libraries into a container that never calls them, only unnecessary image size.
Passing GPUs into the container
docker run --gpus all ...exposes every GPU on the host to the container;--gpus device=0(or a comma-separated list of device indices) restricts it to specific ones, useful for pinning different jobs to different GPUs on a multi-GPU host.- Inside the container,
nvidia-smi(the driver's own status and management tool, present because the base image or an installed package provides the client binary that talks to the host's driver) should list the exposed device or devices, confirming the pass-through actually worked, before assuming the training code itself is the problem if something is not using the GPU.
Common pitfalls that leave GPU devices invisible
- Forgetting the
--gpusflag entirely: the container starts successfully, with no error, and simply has no GPU access; frameworks that can silently fall back to CPU execution can make this look like a slow training run rather than an obviously missing device. - The NVIDIA Container Toolkit installed but never actually configured against Docker specifically (the
nvidia-ctk runtime configure --runtime=dockerstep skipped, or the daemon never restarted after it ran). - A host running a
systemctl daemon-reloadon a system using the systemd cgroup driver (cgroups, short for control groups, are the Linux kernel feature that limits and tracks resources like CPU, memory, or device access per group of processes; the "driver" is which component, systemd itself or Docker's own simpler cgroupfs, actually creates and manages those groups) has a known issue of causing already-running containers to lose access to previously granted GPUs, because the reload can reset the cgroup's device access list; a restart of the affected container after such a reload restores access. - A version mismatch between the container's CUDA toolkit and the host driver's supported CUDA ceiling, which can produce a confusing runtime error from inside the framework rather than an obvious "GPU not found" message.
- Running on a platform with no real GPU passthrough support at all for containers (for example, Docker Desktop on macOS has no GPU passthrough to a Linux container, regardless of any host GPU); this class of workload needs a genuine Linux host (bare metal, a cloud VM, or WSL2 on Windows with the appropriate driver support) to work at all.
Worked example
A training container is built FROM nvidia/cuda:12.4.1-runtime-ubuntu22.04, installs a Python training framework, and is started with docker run --gpus all -it mytrainer. Inside the container, nvidia-smi lists the host's GPU with its driver version and memory, confirming pass-through succeeded before the training script itself even starts; if that same container is started without --gpus all by mistake, nvidia-smi instead reports that the command is not found or that no devices are visible, giving a fast, unambiguous signal to check the run command before spending any time debugging the training code itself.
Trade-offs & pitfalls
- Defaulting every image to a CUDA base "just in case" bloats images that never need it and adds unnecessary attack surface and pull time; reserve CUDA bases for stages and services that actually call into the GPU.
--gpus allis convenient for a single-tenant training host but is the wrong default on a shared, multi-job host, where explicit device assignment (--gpus device=0) prevents two jobs from silently contending for the same GPU's memory.- Because the current documented setup path (
nvidia-ctk runtime configure) is specific to the version of the toolkit installed, and NVIDIA has changed this mechanism before, always verify the exact current command against NVIDIA's own container toolkit documentation for the version in use, rather than trusting an older internal runbook that may reference a superseded flag or file path.
An image that used to be around 900 MB is now over 4 GB after recent changes. Walk through how you'd investigate layer by layer to find the source of the bloat, and name the most common Dockerfile or package-manager mistakes that cause images to balloon like this.
Sample Answer
Direct answer
Start with docker history, which prints every layer in the image along with the size it added and the instruction that created it; sort mentally (or pipe through sort -h on the size column) to find the one or two layers responsible for most of the growth, then go fix whatever Dockerfile instruction produced them. Growth from 900 MB to 4+ GB is almost always one of a handful of well-known mistakes, not death by a thousand small cuts.
A layer-by-layer investigation method
- Run
docker history --no-trunc <image>and look at theSIZEcolumn for each layer; the--no-truncflag matters because it shows the full command instead of a truncated one, which you need to tell two similarRUNlines apart. - For any suspiciously large layer, look at what
CreatedBycommand produced it; aRUN apt-get installorRUN pip installline that jumps by hundreds of megabytes is your first suspect. - Check the base image itself:
docker images <base-image>for the tag you are using; a fullpython:3.12ornode:20image can be over a gigabyte on its own, versus low hundreds of megabytes for the-slimvariant. - Check whether the build context has a
.dockerignore; without one, aCOPY . .can silently pull in.git, local virtual environments, ornode_modulesfrom the host, none of which belong in the image.
Worked example
Building a deliberately unoptimized image and inspecting it:
FROM python:3.12
RUN apt-get update && apt-get install -y build-essential
RUN pip install --no-cache-dir pandas==2.2.3 scikit-learn==1.5.2
COPY . .
$ docker history --no-trunc --format "{{.Size}}\t{{.CreatedBy}}" bloated-image
393MB RUN /bin/sh -c pip install --no-cache-dir pandas==2.2.3 scikit-learn==1.5.2
22.6MB RUN /bin/sh -c apt-get update && apt-get install -y build-essential
...
73.5MB RUN ... (compiling Python from source inside the base image)
$ docker images bloated-image --format '{{.Size}}'
2.14GB
Two things jump out immediately from that history: the pip install layer alone is 393 MB, and the base image is python:3.12 (the full, non-slim variant), which compiles CPython from source and measures roughly 1.6 GB to 2 GB on its own before a single application dependency is added (the exact figure moves a little with CPU architecture and the current Debian point release). For comparison, python:3.12-slim pulled fresh is 204 MB, roughly an eighth of that (measured directly: 204 MB against a 1.62 GB python:3.12 pull), not the mere rounding difference a smaller gap would suggest. In a real "900 MB became 4 GB" case, docker history on the new image would show the same signature: either a newly-added large RUN layer, or a base image tag that quietly changed from a slim variant to a full one (for example, someone bumped FROM python:3.12-slim to FROM python:3.12 to "fix" a missing build tool, and never reverted it).
The usual suspects
Using a full, non-slim base image instead of a slim or distroless one; installing build tools (compilers, -dev headers) in the same layer as the final application instead of a multi-stage build, so the toolchain ships in production; not cleaning package-manager caches in the same RUN layer they were populated in (rm -rf /var/lib/apt/lists/* has to happen in the same RUN as the apt-get install, or the cache is already baked into an earlier layer and cannot be removed by a later one); and a missing or incomplete .dockerignore letting COPY . . pull in .git, log files, or dependency directories from the host.
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.
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.