Docker interview questions open most DevOps, platform, and backend hiring loops because containers are the delivery unit of modern software, and Kubernetes sits on top of exactly these mechanics. This page is a complete tiered bank: 104 questions with worked answers across beginner, intermediate, and scenario sections, plus three break-and-fix labs, a command cheat sheet, and a five-question check at the end.

TL;DR
- 104 questions, three tiers. Dockerfile fluency, layered filesystems, networking, Compose, and the production incidents that round out real Docker interview questions.
- Mechanism over trivia. Every answer explains what actually happens: layers and copy-on-write, namespaces and cgroups, signals and PID 1.
- Labs included. Three deliberate breakage drills, a cheat sheet of the commands that matter, and a quiz to confirm retention.
How the Docker interview works in 2026
Docker interview questions follow a now-standard arc. The screening round verifies daily fluency: images versus containers, what a Dockerfile does, the run flags everyone uses, and the difference between a volume and a bind mount. These are pass-fail filters, and hesitation here ends conversations early, because container work is table stakes for every role that touches deployment.
The deep round goes inside the machine. Expect Docker interview questions on layer semantics and build cache behavior, copy-on-write storage, the signal-handling trap in shell-form commands, networking modes and port publishing mechanics, image slimming, and Compose orchestration. The strongest candidates answer with mechanisms: saying that each RUN creates an immutable layer, containers add one writable layer on top, and the build cache replays unchanged layers answers three questions before the interviewer asks the second one.
The scenario round hands you a broken thing: the container exits instantly, the port is published but connections refuse, the disk filled up and docker is the suspect, the app ignores SIGTERM and gets killed after ten seconds. Panels score your sequence, logs, then inspect, then events, then one hypothesis with a test, and they notice when candidates reach for docker restart before they know what broke. Restarting a container is not diagnosis; it is hoping.
Role emphasis shifts the weighting. DevOps and platform roles get deeper build engineering: multi-stage builds, cache strategy in CI, registry management, and supply chain scanning. Backend roles lean toward runtime behavior: environment, volumes, signals, and debugging from inside a container. Everyone gets networking, because half of all real Docker interview questions end up being about ports, interfaces, and DNS in disguise.
Preparation is cheap here: install Docker locally, or use a browser sandbox, and break the exact things this page describes. An afternoon reproducing the scenario tier converts every answer from recited to remembered, which is precisely the difference interviewers are listening for.
Core concepts interviewers expect you to know
Two models carry almost every conceptual question in the bank: what an image physically is, and what a container physically is. Docker interview questions keep returning to these two because they explain caching, size, security, signals, and most incidents in one stroke. Learn them as mechanics, not slogans.
Images are stacked layers, containers add one more
An image is a stack of immutable layers: each instruction in a Dockerfile that changes the filesystem, RUN, COPY, ADD, produces one layer containing the differences from the layer below. Layers are content-addressed and shared, so ten images built on the same base store that base once. A container is just these layers plus a thin writable layer on top, managed as a copy-on-write filesystem: reads fall through to the lower layers, writes land in the container’s own top layer and never touch the image beneath.
This single model explains a remarkable share of Docker interview questions: why builds cache (unchanged instructions replay their layers), why deleting a file in a later layer does not shrink the image (the file still exists in the lower layer), why containers start in milliseconds (nothing is copied, just stacked), and why writes inside a container vanish when it is removed (the writable layer is discarded with it).
A container is an isolated process, not a small VM
Run a container and Docker asks the kernel to create an ordinary Linux process, then wraps it in namespaces so it has private views of the process tree, network stack, mounts, and hostname, and a cgroup budget so CPU, memory, and I/O are accounted and limited. There is no guest kernel, no boot, no hypervisor tax: the container shares your host kernel, which is why containers start instantly and why you cannot run a different kernel inside one.
The practical consequences show up everywhere in Docker interview questions. Exit the main process and the container exits, because the container is that process. Signals reach PID 1 in the container, and shell-form commands that insert a shell between Docker and the app break signal delivery, the single most productive debugging story in the runtime section. Resource flags map directly to cgroups, and the security posture, user, capabilities, seccomp, is a list of kernel knobs, which ties this whole model back to the Linux fundamentals page.
Question bank at a glance
The bank ascends from daily fluency to production incident, and the counts are exact so you can pace a week of preparation. Docker interview questions repeat heavily across companies, so working this bank once pays off for years; the scenario tier in particular maps one-to-one onto what panels actually run live.
| Section | Questions | What it proves |
|---|---|---|
| Beginner | 38 | You drive Docker daily: Dockerfiles, run flags, volumes, Compose. |
| Intermediate | 40 | You know the machinery: layers, namespaces, networking, images at scale. |
| Scenario and troubleshooting | 26 | You can take a broken container from symptom to cause in order. |
Rehearse the answers out loud in the same shape they are written: name the mechanism, name the command, add one production-grade caveat. That shape, more than any individual fact, is what Docker interview questions are engineered to detect.
Beginner Docker interview questions
This tier is daily-driver fluency, and in real Docker interview questions these arrive as rapid confidence checks. The winning format is one sentence of definition plus one sentence of consequence, delivered without filler. Slow, padded answers read as unfamiliarity even when the facts are right.
What is Docker, in one paragraph?
Answer: Docker is a platform for building, shipping, and running applications as containers: isolated processes that package an application with its dependencies and run consistently on any Linux kernel. It wraps kernel primitives, namespaces and cgroups, into a developer-friendly workflow of images, registries, and CLI commands. The portability story, build once and run anywhere the runtime exists, is the core of most Docker interview questions at this level.
What is the difference between a container and a virtual machine?
Answer: A VM virtualizes hardware and boots a full guest operating system per workload; a container virtualizes at the OS level and shares the host kernel, isolating views and resources instead of hardware. Consequences: containers start in milliseconds and run with near-zero overhead, while VMs offer stronger isolation and can run different kernels and operating systems. The hybrid reality worth mentioning: most production containers run inside VMs precisely to combine both.
What is the difference between an image and a container?
Answer: An image is an immutable template, a stack of filesystem layers plus metadata; a container is a running instance of that image plus one writable layer. The classic phrasing, class and object or executable and process, lands well, and the detail that earns credit: one image can back a thousand containers, each with private writes that vanish when it exits.
What does a Dockerfile do, and what are its most important instructions?
Answer: A Dockerfile is a build recipe: FROM picks the base image, RUN executes build commands, COPY and ADD bring files in, WORKDIR sets paths, ENV and ARG configure, EXPOSE documents ports, and CMD or ENTRYPOINT say what runs at startup. The order matters as much as the words, which is the bridge to every cache question in Docker interview questions.
What is the difference between CMD and ENTRYPOINT?
Answer: ENTRYPOINT is the fixed executable of the container; CMD is its default arguments, and also what the command line overrides. Together they form command plus args, so docker run image args replaces CMD but keeps ENTRYPOINT unless explicitly overridden. The pairing pattern, an entrypoint script plus default CMD arguments, is the design answer Docker interview questions usually want here.
How do COPY and ADD differ, and which should you use?
Answer: COPY copies files or directories, plainly and predictably. ADD additionally unpacks local tar archives and can fetch remote URLs, magic that surprises reviewers and bloats caching clarity. Best practice, which is also the expected answer: use COPY unless you specifically need tar auto-extraction, and say the reason, not just the rule.
What does EXPOSE actually do?
Answer: Almost nothing at runtime: it documents the port the container listens on, feeds tooling like -P auto-publishing and inter-image metadata, and does not publish anything by itself. Publishing requires -p or --network host. This is a classic trap in Docker interview questions precisely because the name suggests otherwise.
What is a Docker registry, and how do tags work?
Answer: A registry stores images; Docker Hub is the public default, and teams run private ones. A full reference is registry/repository:tag, the tag defaults to latest, and every image also has an immutable content digest you can pin by. Worth adding: latest is a mutable convention, not a guarantee of newest, which is why pinning matters in anything reproducible.
How does the build cache decide what to rebuild?
Answer: Instructions replay from cache top-down; a layer rebuilds when its inputs change, the instruction text, copied file checksums, or build args, and every layer after it rebuilds too. That is why ordering matters: dependencies first, rarely-changing code next, your app last. Cache logic is the single most common theme in Docker interview questions about builds.
Why do builds copy dependency files before the whole source tree?
Answer: Cache granularity: COPY of the lockfile and dependency install can cache for weeks, while COPY of your source invalidates on every save. Put the source copy after dependency installation and every code change replays one cheap layer instead of reinstalling the world. Demonstrating this ordering, even verbally, is the point of the question.
What do the most common docker run flags do?
Answer: -d detaches, -it gives an interactive terminal, --name names the container, -p 8080:80 publishes host to container port, -e sets environment variables, -v attaches volumes or bind mounts, --rm removes on exit, and --restart sets lifecycle policy. Fluency with these six flags is assumed by every question downstream in Docker interview questions.
What is the difference between docker stop and docker kill?
Answer: stop sends SIGTERM and waits a grace period, ten seconds by default, then SIGKILLs; kill sends SIGKILL immediately or whatever signal you pass with -s. The operational habit to state: always prefer stop in production paths so apps can flush and close cleanly, and lengthen the grace for apps with slow shutdowns.
How do you look inside a running container?
Answer: docker logs for stdout and stderr, with -f to follow; docker exec -it NAME sh to get a shell inside; docker inspect for the full JSON of config, mounts, networks, and state; docker top for its process tree from the host view. The logs-then-exec sequence is the reflex order Docker interview questions on debugging expect.
What is docker compose, and what does a minimal file look like?
Answer: Compose defines multi-container applications declaratively in YAML: services with images or builds, ports, volumes, environment, and networks, then runs them as one unit with docker compose up, tears them down with down, and streams logs with logs -f. It is the developer-facing half of Docker interview questions because nearly every local stack uses it.
What is the difference between a volume and a bind mount?
Answer: A named volume lives in Docker’s storage area, is managed and portable, and is the choice for database data; a bind mount maps a host directory straight into the container, ideal for local development where you edit files on the host. Both bypass the writable-layer problem for persistent writes, and saying when you would pick each is the graded half.
Why does data disappear when a container is removed?
Answer: The writable layer belongs to the container and is deleted with it; only volumes survive. The design intent, containers are disposable, data is not, is exactly the framing Docker interview questions want, along with the fix: put state in named volumes or external storage, and treat everything else as regenerable.
What are restart policies?
Answer: no, on-failure with an optional retry count, always, and unless-stopped, which is like always but respects a manual stop across daemon restarts. The nuance worth one sentence: restart policies belong to the Docker daemon on single hosts; orchestrators like Kubernetes or Swarm replace them with their own supervision, so do not stack both.
What is docker system df, and what does it show?
Answer: It reports disk used by images, containers, volumes, and build cache, with -v for the itemized view, and docker system prune reclaims the dead weight, dangling images, stopped containers, unused networks, and cache. Disk pressure from buildup is a top-three real-world topic in Docker interview questions, and this command pair is the first response.
How do you get a container’s resource usage live?
Answer: docker stats streams CPU, memory, and network per container against any limits set with --memory and --cpus. Reading the mem percent against the limit is how you spot near-OOM containers early, which connects this small command to the exit-137 incident later in the scenario tier.
How do you override the startup command of an image?
Answer: Append arguments after the image name: docker run image sh -c "anything" replaces CMD, or --entrypoint swaps the whole executable. Debuggers live on this: run the same image into a shell instead of the app. The nuance to add: appended args land as CMD replacement only when an ENTRYPOINT exists, which is exactly the CMD and ENTRYPOINT interplay from earlier.
How do environment variables reach a container, and how do you inspect them?
Answer: Pass them with -e KEY=value or --env-file, bake defaults with ENV in the Dockerfile, or hand a whole set over through Compose. Inspect the live result with docker exec NAME env or docker inspect. The security caveat that belongs here: docker inspect shows env values to anyone with API access, so real secrets belong in secret managers, not flags in shell history.
What does the HEALTHCHECK instruction do?
Answer: It teaches Docker to run a periodic command inside the container and mark it healthy, starting, or unhealthy based on exit codes, visible in docker ps and usable by Compose and Swarm for gating. It does not restart anything by itself on plain Docker, a nuance that separates careful answers in Docker interview questions from confident ones.
How do containers talk to each other?
Answer: On a user-defined network, by name: Docker’s embedded DNS resolves container and Compose service names to container IPs, so an app connects to db:5432 with no published ports. The default bridge lacks this name resolution, which is why the standard advice is to always create a network or let Compose do it.
What is the default bridge network, and why move off it?
Answer: Bridge0 is where containers land without a network flag, reachable by IP but without embedded DNS or isolation from unrelated containers. User-defined bridges add name resolution, better isolation, and on-the-fly attach and detach. This progression, default to custom network, is a stock arc in Docker interview questions about networking.
What is the difference between -p 8080:80 and EXPOSE 80?
Answer: EXPOSE documents; -p 8080:80 publishes, installing a host-side forwarding rule so traffic to host port 8080 reaches container port 80. Bind specifically with -p 127.0.0.1:8080:80 to avoid exposing services on all interfaces, a one-line security practice that impresses in Docker interview questions.
What is a .dockerignore, and why does it matter?
Answer: It excludes files from the build context, the tarball of your directory sent to the builder. Excluding .git, node_modules, logs, and secrets makes builds faster, caches cleaner, and images safer, because anything in the context is one careless COPY away from the image. Leaked .env files via missing dockerignore are a recurring real-world incident and a recurring Docker interview question.
What do ARG and ENV do, and how do they differ?
Answer: ARG is build-time only: passed with --build-arg, usable in Dockerfile instructions, gone from the final runtime env. ENV persists into the container’s runtime environment. The security note to volunteer: ARG values can linger in image history and layers, so secrets never belong in either, a point Docker interview questions love to verify.
How do you copy files into and out of a container?
Answer: docker cp NAME:/path ./local and the reverse work on running or stopped containers, and Compose users can do the same per service. For anything repeatable, prefer volumes or build-time COPY. docker cp is the rescue tool for artifacts and logs, which is the context in which Docker interview questions usually raise it.
What is the difference between docker attach and docker exec?
Answer: attach connects your terminal to the container’s main process, its PID 1 streams, so exiting can kill the app; exec spawns a new process inside the running container, safe to enter and leave. The rule to state: attach to watch, exec to poke, and never Ctrl+C an attach you did not mean to terminate.
What is docker save and docker load for?
Answer: They tar an image to a file and reload it elsewhere, moving images without a registry: air-gapped installs, evidence capture, or quick laptop-to-server transfers. For anything routine, a registry with push and pull wins, and the format detail worth one sentence: save preserves layers and tags, so the loaded image is byte-identical.
What does docker history show, and why is it useful?
Answer: It lists the layers of an image with the instruction, size, and creation step, which makes it the first tool for why-is-this-image-4GB investigations and for spotting secrets baked into old layers. Pair it with docker image inspect for metadata. History reading is a small skill that Docker interview questions on image size always end up rewarding.
How does a container know when to stop, and what does graceful shutdown mean?
Answer: On docker stop, the container’s PID 1 receives SIGTERM; graceful means the app catches it, stops accepting work, finishes in-flight requests, flushes, and exits before the grace period ends, after which SIGKILL lands. This signal story is the hinge of several Docker interview questions later in the runtime section, so plant it early.
What is the difference between docker pause and docker stop?
Answer: pause freezes the container’s processes with the SIGSTOP signal family, keeping memory and state exactly as they were, resumable with unpause; stop asks the app to terminate and removes the container’s processes entirely. Pause is for brief quiescence, like during a live migration, not for maintenance, and confusing the two is the small trap this item in Docker interview questions sets.
What are official images, and why start from them?
Answer: Official images are curated, scanned, and maintained upstream references like python, node, and postgres, with variant tags for size and platform. Starting from them buys you security patching and correct defaults, and pinning a specific version tag, not latest, is the reproducibility practice Docker interview questions expect you to state unprompted.
Why do people choose Alpine, and what is the catch?
Answer: Alpine is a ~5MB base with musl libc, dramatically smaller than Debian-based images. The catch is compatibility: musl behaves differently for some workloads, rare prebuilt binaries break, and DNS resolution edge cases surprise people. Slim Debian or distroless images are the usual alternatives, and knowing the tradeoff beats reciting Alpine by default.
What is a dangling image, and how do you clean them up?
Answer: Dangling images are untagged layers left behind when a rebuild reuses a tag, shown as none:none in docker images. They are pure disk waste; docker image prune removes them, and docker system prune widens the sweep. This housekeeping item appears in Docker interview questions as the practical follow-up to any image-lifecycle discussion.
What does docker inspect tell you that ps does not?
Answer: Everything: full config, environment, mounts with sources, network settings and IPs, restart policy, health state, and resource limits, as queryable JSON with --format. When behavior puzzles you, inspect shows the container’s actual configuration rather than what you believe you launched, which is the debugging mindset this staple of Docker interview questions is checking for.
How do you check what changed inside a running container?
Answer: docker diff NAME lists files added, changed, or deleted in the writable layer since start, sorted into A, C, and D sets. It is the quickest way to see whether an app writes where you think it does, and whether temp files are accumulating in places that will hurt, a quiet favorite among runtime Docker interview questions.
Intermediate Docker interview questions
Here the questions turn mechanical: storage internals, kernel isolation, network plumbing, and build engineering. Forty questions follow, and the shared trick is to answer with the mechanism and then volunteer the operational consequence, because that two-step is what distinguishes working depth in Docker interview questions.
Which Dockerfile instructions create layers, and which do not?
Answer: RUN, COPY, and ADD create filesystem layers; FROM contributes the base layers; metadata instructions like ENV, EXPOSE, WORKDIR, and CMD change config only, adding zero-byte metadata entries rather than filesystem layers. Knowing this shapes image design, since shuffling metadata lines costs nothing while moving a RUN invalidates everything after it, a fact Docker interview questions on optimization always build on.
Why does deleting a file in a later Dockerfile layer not shrink the image?
Answer: Layers are additive and immutable: the file still exists in the earlier layer, and the deletion is just a whiteout entry in the new layer, so the bytes ride along in every pull. The fix is to not create the file earlier at all, or to do install-and-clean inside one RUN. This copy-on-write consequence is among the most frequently missed Docker interview questions.
What is copy-on-write in Docker’s storage driver?
Answer: Overlayfs stacks image layers as lowerdirs and the container’s writable layer as an upperdir. Reads resolve through the stack; the first write to a file from a lower layer copies it up into the upper layer, then modifies the copy. This is why a thousand containers share one image cheaply, and why first-write latency spikes on big files, the mechanism behind a surprising number of Docker interview questions.
What are multi-stage builds, and why do they matter?
Answer: Multiple FROM blocks in one Dockerfile let a fat build stage hold compilers and dev dependencies while a slim final stage copies only the artifacts with COPY --from=build. Typical wins are dramatic: gigabyte build images become tens of megabytes, and the runtime surface shrinks with the attack surface. For anything compiled or bundled, this is the expected answer in modern Docker interview questions.
What are scratch and distroless base images?
Answer: scratch is the empty image, usable for fully static binaries that need no libc or shell; distroless images add minimal libc and runtime bits but no shell or package manager, for languages like Java, Python, or Node. Both shrink size and attack surface drastically, and the tradeoff to name is debuggability: no shell means ephemeral debug containers or sidecar tooling, which is the nuance senior answers add.
List your image-slimming playbook.
Answer: Multi-stage builds, minimal base, pinned small tags, chained cleanups inside single RUN lines, .dockerignore hygiene, package manager no-cache flags, and only copying what runs. Then measure: docker history and dive attribute bytes per layer, so you optimize facts rather than hunches. Delivering this as a practiced routine is exactly what Docker interview questions on image size probe for.
Why does running as root in containers matter, and what is the fix?
Answer: Root in the container is root on the kernel; an escape via any runtime or kernel vulnerability lands with UID 0 privileges. Fixes: USER in the Dockerfile with a real UID, runAsNonRoot upstream in orchestrators, user namespace remapping on the daemon, and rootless Docker for the strongest form. The honest framing for Docker interview questions: defense in depth, because image-level USER is necessary but not sufficient.
What is rootless Docker?
Answer: The daemon and containers run under an unprivileged user, using user namespaces so container root maps to an unprivileged host user. It removes the largest single blast radius in a Docker install, at the cost of some edge features around networking, storage drivers, and non-privileged ports. Being able to name the tradeoff, not just the feature, is what Docker interview questions on hardening look for.
What is the danger of mounting /var/run/docker.sock into a container?
Answer: That socket is root-equivalent API access to the daemon: the container can spawn privileged containers, read any host file through binds, and effectively own the machine. CI systems and tools like some old monitoring agents demand it anyway. Mitigations in order: avoid it, proxy a scoped API, use rootless with restricted group access, and treat any container with the socket as a control plane component with control plane trust.
How does container networking work on the default bridge?
Answer: The daemon creates a docker0 bridge with a private subnet; each container gets a veth pair, one end in the container, one on the bridge, plus an IP from the subnet. Container-to-container traffic flows over the bridge; egress NATs through the host; published ports are iptables DNAT rules steering host ports into container IPs. Saying veth and DNAT is usually what Docker interview questions on networking are fishing for.
What network modes can a container run with?
Answer: bridge, the default private stack; host, sharing the host network namespace outright, fastest but no isolation; none, loopback only for isolation-heavy jobs; container, sharing another container’s stack, the pattern behind sidecars; plus macvlan and ipvlan for giving containers real LAN identities. Picking modes with reasons, not just naming them, is the difference between passing and impressing in Docker interview questions on networking.
How does Docker’s embedded DNS work?
Answer: On user-defined networks, the daemon runs a DNS server at 127.0.0.11 inside each container, resolving container names, Compose service names, and network aliases to container IPs, forwarding everything else upstream. This name service is what makes db:5432 work, and its failure modes, containers on different networks, misconfigured resolv.conf, are the substance of several Docker interview questions in the scenario tier.
What are Compose depends_on and healthcheck-gated startup?
Answer: depends_on orders creation, not readiness: the database container exists, but its Postgres may not accept connections yet. The fix is condition syntax gating on service_completed_successfully or service_healthy with a healthcheck, so the app starts only when the dependency truly serves. Ready-versus-running is the distinction Compose questions in Docker interview questions always target.
How do you back up a Docker volume?
Answer: Run a throwaway container sharing the volume and stream a tarball: docker run --rm -v data:/data -v $PWD:/backup alpine tar czf /backup/data.tgz -C /data ., and restore by reversing the direction. Alternatively stop the writer first for a consistent snapshot, or use storage-level snapshots for large databases. Knowing the alpine-tar pattern by heart is the expected reflex in Docker interview questions on data.
What is the shell-form versus exec-form problem in CMD?
Answer: Shell form, CMD npm start, runs your app as a child of /bin/sh, and sh does not forward signals, so SIGTERM never reaches the app and docker stop ends in SIGKILL after the grace period. Exec form, CMD ["npm","start"], makes the app PID 1 directly and receives signals cleanly. This one line of YAML difference causes a disproportionate share of shutdown bugs and Docker interview questions alike.
Why is PID 1 special inside containers?
Answer: The kernel treats PID 1 differently: default signal dispositions change, and orphaned processes re-parent to it, so a naive app as PID 1 neither handles SIGTERM properly nor reaps adopted zombies. The standard fixes are an init wrapper, tini or docker run --init, or an entrypoint script that execs the app after installing handlers. The zombie-reaping half is what elevates answers to senior level in Docker interview questions.
How do namespaces and cgroups divide the isolation work?
Answer: Namespaces give the view: pid, net, mnt, uts, ipc, user, each scoping what the process can see. Cgroups give the budget: CPU, memory, pids, and I/O accounting and limits. A container is one process wrapped in a set of namespaces and placed in a cgroup, no virtualization involved, and interviewers use this division as a quick litmus test of real understanding in Docker interview questions.
What security profiles apply to containers by default?
Answer: A default seccomp profile blocks a long list of risky syscalls, dangerous Linux capabilities are dropped, all but a default set, and AppArmor profiles apply on hosts that ship them. Tightening from there means dropping more capabilities, adding no-new-privileges, read-only root filesystems, and custom seccomp. Naming the three default layers, seccomp, capabilities, AppArmor, is the baseline Docker interview questions on security expect.
What does –cap-drop=all and –cap-add do for you?
Answer: It replaces the default capability set with exactly what the app needs: a web server binding port 80 needs NET_BIND_SERVICE, and almost nothing else. Smaller capability sets shrink the post-exploitation toolbox, and combined with read-only filesystems and non-root users it forms the practical hardening trio. Concrete examples beat recitation in Docker interview questions, so have one app-specific list ready.
How do resource limits map to kernel mechanisms?
Answer: --memory sets the cgroup memory cap whose breach triggers the OOM killer, exit 137; --cpus sets cgroup CPU quota, enforced as time slices, producing throttling rather than death; --pids-limit caps process count against fork bombs. Reading docker stats against these limits is the operational loop, and connecting flags to cgroup files is the depth marker Docker interview questions listen for.
Where do container logs go, and how do you keep them from filling disks?
Answer: The default json-file driver writes stdout and stderr to /var/lib/docker/containers under the host, and without rotation those files grow forever, a leading cause of node disk incidents. Set log-driver options, max-size and max-file, per container or daemon-wide, or ship to journald, syslog, or a dedicated driver. Unbounded json-file logs are such a common outage that Docker interview questions use it as a reliability litmus test.
What is BuildKit, and what does it add over the legacy builder?
Answer: BuildKit is the modern builder: a dependency graph that runs independent stages in parallel, a content-addressable cache, mount primitives, cache and secret and SSH mounts, better garbage collection, and digest-level provenance. It is the default in recent Docker versions, and the practical wins, cache mounts for package managers and secret mounts that never hit layers, are the concrete examples Docker interview questions want.
How do build secrets avoid leaking into image layers?
Answer: BuildKit secret mounts pass secrets as tmpfs mounts available during specific RUN steps and absent from layers, history, and cache: RUN --mount=type=secret,id=npm npm install with --secret id=npm,src=.npmrc. The old alternatives, build args and COPY of credentials, leave traces in history forever. This question separates teams that have had a leak from teams that will, which is why it keeps appearing in Docker interview questions.
How does multi-architecture image publishing work?
Answer: Buildx builds per-platform images and pushes a manifest list under one tag, so pulls transparently fetch the matching architecture, amd64 on most servers, arm64 on Apple Silicon and Graviton. CI emulation via QEMU handles cross-compilation, slower but simple, while true cross-builds use target-stage toolchains. The failure this preempts, arm laptops shipping images that crash on amd64 CI, is a very current Docker interview question.
How do you scan images for vulnerabilities?
Answer: Scan images in CI with trivy or Grype, or Docker Scout, gate on high-severity and fixable findings, and keep base images fresh so patches flow. Beyond CVEs, mature setups add SBOMs and provenance attestations with buildx for supply chain audit. Knowing the fix is usually rebuild-on-newer-base, not patching the running container, is the practical point Docker interview questions want made.
Why pin base images, and by what, tag or digest?
Answer: Unpinned bases drift: a rebuild pulls a different patch level, breaking reproducibility and sometimes the build itself. Pin by digest, alpine@sha256:..., for byte-identical rebuilds, or by specific version tag for a balance of clarity and freshness, updated deliberately via automation like Renovate. The interview-grade position: digests in production, tags during development, and a robot that opens the upgrade PRs.
What is docker-in-docker, and why is socket mounting its popular alternative?
Answer: Docker-in-docker runs a full daemon inside a container, needed when you truly require nested isolation, but it complicates storage, caching, and security. CI jobs usually mount the host socket instead, sharing the outer daemon for speed and cache reuse, at the cost of trusting jobs with daemon-level access, the tradeoff from the socket question earlier. Explaining when each is justified is the senior form of this answer in Docker interview questions.
What are Docker contexts good for?
Answer: Contexts point the CLI at different daemons, local, remote over SSH, or a cloud endpoint, switchable with docker context use, so the same commands manage a laptop and a build server. They carry the same wrong-target risk as kubectl contexts, so verify with docker context show before destructive commands. Remote-context fluency is increasingly assumed in Docker interview questions for ops roles.
What does docker events give you that logs do not?
Answer: The daemon’s audit stream: container start, die with exit code, OOM markers, health_status transitions, image pulls, volume and network operations, filterable and followable live. When a container died and nobody knows why, events show the daemon’s side, OOM or process exit or manual stop, in one line. It is the first command I reach for after logs in unexplained-death Docker interview questions.
What are image manifests and content digests?
Answer: A manifest describes an image: config, layer digests, and for multi-arch, a manifest list mapping platforms to image digests. The digest is a content hash of the manifest, which is what makes pulls verifiable and pinning byte-exact. Understanding that tags point at manifests and digests pin content clarifies half the registry behavior Docker interview questions ask about.
How do you handle timezone and locale correctness in containers?
Answer: Containers default to UTC with no locale data; fix by installing tzdata, setting TZ, and configuring the app’s locale explicitly rather than relying on host inheritance. For scheduled jobs, decide a single canonical time zone and set it in the image, because host-mounted time zones differ across nodes. These small correctness topics appear in Docker interview questions as practical maturity checks.
What is an init process option –init, and when do you use it?
Answer: docker run --init inserts tini as PID 1, which forwards signals and reaps zombies, so your real app runs as a well-behaved child even if it ignores signal handling itself. Use it whenever you cannot fix the app’s signal behavior, and prefer fixing the app for anything long-lived. It is the one-flag fix for the PID 1 trap that Docker interview questions circle repeatedly.
How do ulimits and sysctls work inside containers?
Answer: Containers inherit sensible default ulimits from the daemon, overridable per container with --ulimit nofile=65536:65536 for apps needing many open files; a small allowlist of kernel parameters, like net core settings, is settable with --sysctl, since most sysctls are namespaced or global-only. The practical case, raising nofile for databases and proxies, is the expected example in Docker interview questions on tuning.
What is the difference between docker compose up and docker compose run?
Answer: up brings the declared application to life, creating networks, dependencies, and everything in the file; run starts a one-off container for a single command, optionally replacing the entrypoint, with flags to skip dependencies or not create ports. Scripts and migrations use run, applications use up, and mixing them up produces ghost containers that confuse Compose state, a small classic in Docker interview questions.
How do Compose profiles and override files work?
Answer: Profiles tag services as optional, activated with --profile, for debuggers, seeders, or mock APIs that should not run in the base stack; override files merge on top of the base compose.yaml, by convention compose.override.yaml loaded automatically. Together they let one file serve dev, test, and demo without drift, which is the maintainability point Docker interview questions on Compose probe.
How would you run a private registry, and what do you configure around it?
Answer: Run the registry image behind TLS with authentication, htpasswd or a proxy to your identity system, set storage backing to object storage for durability, configure garbage collection for deleted manifests, and put it behind your CI’s login flow. Managed registries replace most of this with IAM. The interviewers’ follow-up is usually purge and retention policy, so have a position ready.
What happens when two containers declare the same published host port?
Answer: The second fails to start: the daemon cannot bind a host port twice, reporting port already allocated, because publishing installs a host-level forwarding rule, one owner per port. The fixes are rebinding, a different host port, or removing the publish and using a shared network with direct container DNS instead. Tracing the error to the DNAT rule, not to the containers, is the insight Docker interview questions are testing here.
How do you pass configuration files to containers the right way?
Answer: Prefer environment for simple settings, mounted volumes or Compose configs for whole files, and image-baked defaults only for constants that never change per environment. Bake secrets into none of these; they arrive from secret managers at runtime. The configuration pyramid, defaults in image, environment in compose, secrets at runtime, is the tidy answer Docker interview questions on configuration want.
What does –read-only do, and how do you make it workable?
Answer: It mounts the container’s root filesystem read-only, so writes fail loudly unless you attach tmpfs or volumes for the paths the app must write, temp dirs, caches, logs. Combined with non-root users it is the strongest runtime posture available on plain Docker. Naming the two or three writable paths your app actually needs is what turns this from theory into a credible answer in Docker interview questions.
How is Podman different, and does it matter for interviews?
Answer: Podman is a daemonless, rootless-first container engine, CLI-compatible with Docker, with pods as a native grouping and systemd integration for running containers as services. Compose and most tooling work through its socket compatibility. The interview-worthy point: engine choice changes operations, not concepts, and everything in this bank of Docker interview questions applies unchanged, because the concepts are kernel mechanics, not Docker Inc. features.
Scenario and troubleshooting questions
This final tier mirrors the live rounds: one broken sentence, then the interviewer waits. Every answer below follows the same professional sequence, observe, hypothesize, test, and says so explicitly, because in scenario Docker interview questions the visible reasoning is the product being evaluated. Practicing these aloud converts them from reading material into reflex.
A container exits immediately after starting. What do you check?
Answer: docker ps -a for the exit code, then docker logs for the reason: exit 0 from a command that finished, like a shell script with no server, is the most common non-error; a traceback names the config or dependency problem; exit 1 with no output means logs went somewhere unexpected or the entrypoint failed early. Then docker inspect the CMD and entrypoint to confirm what actually ran. Run with -it and a shell to poke interactively once the cause is scoped.
A port is published with -p, but connections to it are refused. Where do you look?
Answer: Four links in the chain, test each: is the app listening inside the container, docker exec NAME netstat -tlnp or ss; is it bound to localhost inside rather than 0.0.0.0, the single most common cause; is the mapping the right way around, -p 8080:80 serves host 8080, and docker port NAME confirms; and is a host firewall in the path. The localhost-binding answer alone usually ends this scenario in your favor.
Two containers on the same host cannot reach each other by name. Why?
Answer: Embedded DNS only works on user-defined networks, so two containers on the default bridge resolve names not at all, and containers on different custom networks are strangers even with DNS. Put both on the same network, or in Compose the project network does it automatically, then verify with docker network inspect that both are members and ping by service name. Name resolution equals shared network is the sentence this scenario is built around.
The host disk filled up and Docker looks like the culprit. What do you run?
Answer: docker system df -v itemizes the suspects: images including danglers, stopped containers, volumes, and above all build cache and json-file logs. Then target the cleanup: docker system prune plus builder prune for cache, truncate runaway container logs, and set daemon-wide log rotation so it stays fixed. Finding which category ate the disk before pruning is the discipline that separates operators from chronic rebooters in Docker interview questions.
A container gets OOMKilled under load. How do you confirm and fix it?
Answer: docker inspect shows state OOMKilled with exit 137, and docker events records the kernel’s decision; host dmesg confirms. Fix in order: measure real usage with stats, set --memory honestly with headroom, check for in-container leaks, and remember a JVM or language runtime with its own heap flags must agree with the cgroup cap. Applying a bigger number without measuring is the anti-pattern this scenario exists to catch.
Your app never shuts down cleanly: docker stop always waits ten seconds then kills. Why?
Answer: The signal is not arriving: shell-form CMD put sh between Docker and the app, or the entrypoint script runs the app without exec, so SIGTERM terminates a wrapper while the app ignores it, and the grace period expires into SIGKILL. Fix with exec-form commands, exec ./app inside scripts, and a SIGTERM handler that drains and exits; verify with logs showing your shutdown path ran. This is the single most instructive runtime story in Docker interview questions.
ps inside a container shows dozens of defunct entries. What is happening?
Answer: PID 1 is not reaping: orphans re-parent to PID 1, and if the app is PID 1 without wait logic, zombies accumulate until the pids limit blocks everything. Fix with an init, docker run --init or tini in the image, or correct the app’s child handling. The namespace framing, this is the Linux PID 1 contract showing up in a container, earns the senior nod here.
The app cannot write to a bind-mounted directory and fails with permission denied. What is wrong?
Answer: UID mismatch: the container process runs as its image user, often UID 1000 or root, while the host directory belongs to you, and bind mounts preserve host ownership byte for byte. Fix deliberately: run the container with --user $(id -u):$(id -g), chown the host directory to the container UID, or move runtime state to a named volume that Docker initializes. Permission-denied-on-volume is a top-three real-world item in Docker interview questions.
DNS resolution fails inside a container but works on the host. What do you check?
Answer: Read the container’s resolv.conf: on user-defined networks it should point at 127.0.0.11, the embedded DNS; if a custom network option or a daemon config overrode dns settings, look there. Test with docker exec NAME getent hosts example.com, compare networks with inspect, and on VPN’d hosts check MTU, because DNS over a broken-MTU path fails in confusing ways. The 127.0.0.11 detail is the knowledge marker for this scenario.
Transfers inside containers stall on big uploads through a VPN. What is the classic cause?
Answer: MTU mismatch: VPN tunnels shrink the path MTU, Docker’s default interface MTU stays 1500, and PMTUD breaks on networks that filter ICMP, so big packets vanish while pings succeed. Fix by setting the daemon’s MTU or per-network MTU to the tunnel’s value. Symptoms-are-weird-but-pings-work is the fingerprint, and naming it fast is exactly what this entry in Docker interview questions rewards.
docker run fails with port is already allocated, but no container seems to use it. Now what?
Answer: List the truth: docker ps filtering the port, docker ps -a for paused or restarting containers that still hold bindings, and a host-level ss -tlnp for non-Docker squatters like a dev server. A container in restarting state re-grabs the port every few seconds, which is why it looks haunted. Kill or reconfigure the holder, then start yours, and remember the rule underneath: one host port, one binding.
Cannot connect to the Docker daemon: what are your first three checks?
Answer: Is the daemon running, systemctl status docker or the equivalent; permissions, is your user in the docker group or are you prefixing sudo, the classic new-install error; and environment, does DOCKER_HOST or the current context point somewhere unexpected, including a dead remote. Journalctl on the daemon then reveals deeper failures like storage driver faults. Order matters, and saying it in that order is the whole answer.
An image built yesterday now crashes with glibc or malloc errors. What changed?
Answer: The base moved: an unpinned tag like latest or a moving minor tag pulled a different base with a different libc, and a prebuilt binary compiled against the old one no longer loads. Pin the base by digest or exact version, rebuild cleanly, and prefer binaries that match the base family, musl for Alpine, glibc for Debian. This reproducibility failure is the lead-in to most pinning discussions in Docker interview questions.
TLS calls from inside a container fail certificate verification while the host is fine. Why?
Answer: Minimal images ship no or stale CA certificates, and corporate or proxy environments add custom roots the image never saw. Fix by installing ca-certificates in the image and adding the internal root during build, mounted as a build secret if it is sensitive, then rebuild. Time skew is the second suspect when verification fails in both directions, and checking date inside the container takes two seconds, which is worth saying out loud.
CI builds the image fine, then the container crashes on the server with exec format error. Explain it.
Answer: Architecture mismatch: the CI machine built arm64, often on Apple Silicon, and the amd64 server cannot execute it, reporting exec format error. Check with docker image inspect architecture fields, then build with buildx targeting the server platform, or push a proper multi-arch manifest list. This cross-architecture trap is one of the most modern items in Docker interview questions, and naming buildx answers it completely.
A secret accidentally went into an early layer two weeks ago. Is the image safe now?
Answer: No: later deletions are whiteouts, the secret still sits in that layer’s bytes, visible via docker history and a manual layer export, and every pull carries it. Response: rotate the secret immediately, treat it as compromised regardless, rebuild with the secret removed from the history entirely, using build-time secret mounts going forward, and force-push the replacement while pruning the old tag. The rotate-first instinct is what this scenario tests hardest.
Builds that took seconds now re-download all packages every time. What broke the cache?
Answer: Something before the dependency step invalidates constantly: a COPY of the whole source above the install, a timestamped file in the context, or a build arg feeding the layer. Re-order Dockerfile so lockfile-plus-install precedes source copy, tighten .dockerignore, and on BuildKit add cache mounts for package directories. Walking the Dockerfile top-down narrating invalidation is exactly how interviewers want this answered.
Your image is 2.5GB and deploys take forever. Walk me through slimming it.
Answer: Measure first with history or dive to find the fat layers, then apply the playbook: multi-stage build so toolchains never ship, minimal pinned base, single RUN chains with package-manager no-cache flags, .dockerignore to keep junk out of context, and only production dependencies in the final stage. Expect an order-of-magnitude win, gigabytes to double-digit megabytes for compiled apps, and state the number you would consider done, because Docker interview questions on size want judgment, not just commands.
You need to inspect a stopped container’s filesystem. What are the options?
Answer: docker cp NAME:/path ./ works on stopped containers and is the first tool; docker export flattens the whole filesystem to a tar for full archaeology; starting a throwaway container from the same image with a shell covers configuration experiments; and for volume state, mount the volume into an alpine container and browse. Note the limits: export loses layer history, and none of this runs processes, it is all filesystem forensics.
Data in a named volume must move to a new host. How do you migrate it?
Answer: Tar-pipe it: on the source, back up with the alpine-volume-mount pattern to a file or stream over SSH; on the target, restore into a freshly created volume of the same name, then start the app stack and verify row counts or file sums. For databases, prefer native dumps over file copies for consistency, taking the tar approach only with the writer stopped. Saying when not to use the file-level method is the judgment layer of this answer.
Logs from a Compose stack interleave and you cannot follow one service. What do you use?
Answer: Per service, docker compose logs -f service; across all, docker compose logs -f --tail=100 with service name prefixes; grep or tail to filter, and --since for time windows. For anything durable, set a logging driver that ships to a central place rather than treating CLI logs as the system of record. The habit being verified in this small scenario: log tooling before incident, not during.
Registry push fails with denied: requested access to the resource is denied. What do you check?
Answer: Auth first: are you logged in, docker login to the right registry, with a token that has push scope, not just pull. Then naming: the image must be tagged with the full path, registry or username/repo:tag, because pushing to a namespace you do not own denies regardless of credentials. On self-hosted registries, check the proxy and its config last. The full-path tag mistake is the most common cause, and leading with it shows pattern experience.
A healthcheck passes but the app is actually broken. How is that possible?
Answer: The check tests the wrong thing: a process liveness ping, or a root URL that returns 200 even when dependencies are down, proves very little. Design checks against real function, a dependency-touching endpoint with a short timeout, sensible intervals and retries to avoid flapping, and remember plain Docker does not act on unhealthy, it only reports; Compose and orchestrators act. Health semantics versus reality is precisely the reasoning Docker interview questions here are scoring.
After moving to Compose, one service cannot reach another that worked standalone. What changed?
Answer: Networking and names: Compose puts services on a project network and changes what names resolve, service names rather than container names, plus legacy links behavior is gone. Check both services are up, docker compose ps, share the default project network or a declared one, and use the service name plus internal port, not the published host port, for intra-stack traffic. Host-port habits breaking inside the network is the exact lesson this scenario teaches.
Everything worked, then a daemon upgrade changed behavior subtly. How do you approach Docker upgrades?
Answer: Read release notes for storage driver, networking, and API version changes before upgrading, then canary: upgrade one non-critical host, run the core workloads, compare docker info and behavior. Pin API versions in automation clients so the daemon upgrade does not break tooling, and keep images and volumes, which survive daemon updates, backed up anyway. Treating the daemon as a real piece of infrastructure, not a background utility, is the mature note this scenario wants.
You suspect a container is compromised. What is your response sequence?
Answer: Contain first: stop the container, cut its network, snapshot evidence before pruning anything, export the filesystem, capture logs, and note the image digest. Then scope: how did it get in, image provenance, exposed socket, vulnerable dependency, and rotate everything it could have read, credentials, tokens, SSH keys. Finally rebuild from a known-good pinned base with scanning in the pipeline, and write down the entry point. Preserve, then purge, in that order, is the judgment Docker interview questions on security incidents are testing.
Hands-on scenario labs
These three labs deliberately break the exact things scenario rounds break, and each maps to the highest-frequency Docker interview questions above. Run them on a laptop or a browser sandbox until the diagnosis is narration, not recall, because the narration is what gets scored.
Lab 1: break signal handling, then fix it properly
- Run an app with shell-form command and stop it:
docker run --name lab nginx sh -c "nginx -g 'daemon off;'", then timedocker stop laband watch it burn the full grace period. - Confirm the cause with
docker exec lab ps aux: nginx is a child of sh, and SIGTERM died in sh. - Re-run with exec-form command, stop again, and compare the shutdown time.
- Write the two-sentence explanation you would give an interviewer, naming sh, signal forwarding, and the grace period.
Lab 2: cause and cure a connection-refused container
- Run a web server bound to localhost inside the container and publish the port, then curl it from the host and observe the refusal.
- Prove the cause from inside:
docker execplus ss or netstat shows the listener on 127.0.0.1 only. - Rebind the app to 0.0.0.0, retry, and verify with
docker portthat the mapping points where you think. - Finish by testing the same stack over a user-defined network using container names instead of published ports.
Lab 3: build slim, measure everything
- Write a naive single-stage Dockerfile for a small compiled or bundled app and record the image size.
- Convert it to multi-stage: build stage with toolchain, final stage with runtime and artifacts only, and measure again.
- Run
docker historyon both and attribute the biggest layers out loud. - Add a .dockerignore, reorder dependency installs before source copies, rebuild twice, and demonstrate the cache hits.
Cheat sheet: the commands behind the answers
Nearly every item in this bank of Docker interview questions resolves to one of these commands in a diagnostic order. Learn the table as a sequence, look, then inspect, then events, then act, and the live format stops being stressful.
| Command | What it tells you |
|---|---|
docker ps -a | Every container with status and exit codes, the opening frame |
docker logs [-f] [--tail N] NAME | The app’s stdout and stderr story, including crash output |
docker inspect NAME | Ground truth: config, mounts, networks, state, OOM flags |
docker exec -it NAME sh | Inside a live container, for listeners, files, and processes |
docker events | The daemon’s verdict stream: die, OOM, health, stops |
docker stats | Live CPU and memory against limits, the near-OOM detector |
docker top NAME | The container’s process tree from the host view |
docker diff NAME | What the writable layer changed since start |
docker cp NAME:/path . | Artifact and log rescue from running or stopped containers |
docker images / rmi / image prune | Inventory and cleanup, including dangling layers |
docker history IMAGE | Layer-by-layer size attribution for fat-image diets |
docker build -t name:tag . | The build itself, watch cache hits per step |
docker system df -v | Who owns the disk: images, containers, volumes, cache |
docker system prune --volumes | The careful sweep, after you know what you are deleting |
docker network ls / inspect NET | Which containers share which network, the DNS prerequisite |
docker port NAME | The actual host-to-container port mappings |
docker volume ls / inspect | Persistent state inventory and its mountpoints |
docker compose ps / logs -f / up -d / down | The stack lifecycle in four commands |
docker context ls / show | Which daemon you are about to touch |
docker buildx build --platform linux/amd64 | Cross-architecture builds that prevent exec format errors |
The full CLI reference lives at docs.docker.com, and the networking deep-dive there pairs well with the intermediate tier above.
Key takeaways and FAQ
The pattern across all three tiers of Docker interview questions is the same as the rest of this series: mechanisms beat memorization. Layers, namespaces, signals, and DNS explain every individual question on this page, and once you can narrate those four fluently, unfamiliar questions still land inside your model, which is exactly what interviewers are trying to find out.
How hard are Docker interview questions compared to Kubernetes ones?
Docker questions go shallower but sharper: fewer objects to learn, more mechanism per question, and heavier emphasis on debugging behavior you can reproduce locally in minutes. If this page feels comfortable, the Kubernetes bank becomes mostly vocabulary plus orchestration concepts on top.
Do Docker interview questions overlap with the Linux ones?
Substantially: namespaces, cgroups, signals, PID 1, and permissions are Linux mechanics wearing a container costume. Prepare the two banks together, since the strongest candidates answer container questions by dropping one level down to the kernel and then coming back up with the consequence.
Will Docker interview questions include live terminal work?
Often, yes, usually against a sandbox with a broken container or a Dockerfile to fix. The three labs above are modeled on exactly that format, and practicing them with spoken narration is the highest-yield prep hour available.
Which Docker interview questions matter most for DevOps versus developer roles?
Developers get Dockerfile craft, Compose, volumes, and debugging; DevOps roles add build engineering, registry operations, CI cache strategy, and security posture. The scenario tier matters to both, because production incidents do not respect role boundaries.
What should I read after this page?
Move up a layer with the Kubernetes interview questions bank, drop down a layer with the Linux interview questions page, and follow the DevOps Prep hub as the remaining topic banks ship.