Docker Interview Questions
Containerization internals: Linux namespaces, cgroups v2, copy-on-write overlay2 filesystems, multi-stage builds, and container daemon security hardening.
Practice Docker Interview Questions
Showing 16 of 16 technical questions with engineering explanations
How does a Docker container differ architecturally from a traditional virtual machine?
Senior Engineering Answer
A virtual machine runs a full guest operating system and kernel atop a hypervisor, consuming gigabytes of RAM and taking tens of seconds to boot. A Docker container shares the host Linux kernel directly and isolates a standard user-space process using kernel namespaces and cgroups. Because there is no guest OS or hardware emulation layer, containers start in milliseconds with minimal memory overhead.
# Inspect the shared host kernel from inside a running container docker run --rm alpine uname -r
Claiming containers have their own Linux kernel is incorrect; on macOS and Windows, Docker Desktop runs a lightweight Linux VM transparently because containers require a Linux kernel.
What is the difference between a Docker image, a container, and a volume?
Senior Engineering Answer
A Docker image is an immutable, layered read-only template containing application code, libraries, and runtime metadata. A container is a runnable instance of an image with a thin writable copy-on-write layer on top that is discarded when the container is removed. A volume is a host-managed persistent storage mount outside the container's union filesystem, preserving database state or uploads across container restarts and upgrades.
docker volume create pgdata docker run -d --name postgres -v pgdata:/var/lib/postgresql/data postgres:16-alpine
Writing persistent database files to the container's writable layer causes silent data loss on container recreation and incurs copy-on-write storage performance penalties.
What is the difference between COPY and ADD, and between CMD and ENTRYPOINT in a Dockerfile?
Senior Engineering Answer
COPY strictly copies local build-context files into the image, whereas ADD also auto-extracts local tar archives and can fetch remote URLs (without checksum verification). ENTRYPOINT defines the fixed executable of the container, while CMD provides default arguments that users can override at runtime. Combining exec-form ENTRYPOINT with CMD creates clean CLI-style images.
COPY ./bin/server /usr/local/bin/server ENTRYPOINT ["/usr/local/bin/server"] CMD ["--port", "8080"]
Using shell form (CMD node server.js) instead of exec form (CMD ["node", "server.js"]) wraps your process in /bin/sh -c, which prevents SIGTERM from reaching your application during docker stop.
How do you prevent sensitive files, build artifacts, and bloated directories from slowing down Docker builds?
Senior Engineering Answer
Place a .dockerignore file alongside the Dockerfile to exclude .git, node_modules, local .env files, test fixtures, and compiled outputs before the Docker CLI sends the build context tar stream to the daemon. Excluding large unnecessary directories dramatically shrinks build context transfer time and prevents leaking local secrets or host-compiled native binaries into image layers.
# .dockerignore .git node_modules .env* dist *.log
Running COPY . . without .dockerignore can bake local .env credentials into an intermediate image layer; even if a later RUN rm .env deletes it, the secret remains retrievable from layer history.
How does Docker layer caching work, and how should you order Dockerfile instructions to maximize cache reuse?
Senior Engineering Answer
Each Dockerfile instruction (FROM, RUN, COPY, ENV) produces an immutable layer identified by the parent chain and input checksums. Once any layer changes, Docker invalidates and rebuilds every subsequent instruction. To maximize cache hits, place stable OS packages early, copy only dependency manifests (package.json, package-lock.json, go.mod) and install dependencies next, and copy rapidly changing application source code last.
FROM node:22-alpine WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY src ./src CMD ["node", "src/index.js"]
Running COPY . . before npm ci invalidates the dependency installation cache on every single source code edit.
How do multi-stage Docker builds shrink production images and improve security?
Senior Engineering Answer
Multi-stage builds use multiple FROM blocks in a single Dockerfile. Early stages include heavy SDKs, compilers, and devDependencies to compile binaries or bundle assets. The final stage starts from a minimal runtime base like alpine or gcr.io/distroless/static and uses COPY --from=builder to copy only the compiled artifact, removing package managers, shells, and compilers from the production attack surface.
FROM golang:1.23-alpine AS builder WORKDIR /src COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -o /out/api ./cmd/api FROM gcr.io/distroless/static-debian12:nonroot COPY --from=builder /out/api /api ENTRYPOINT ["/api"]
Copying only a dynamically linked Go or C binary into scratch or distroless/static without CGO_ENABLED=0 or shared libraries fails at runtime with 'exec /api: no such file or directory' because the dynamic linker ld-linux is missing.
How do Docker bridge, host, and none network drivers work, and how does container DNS resolution function?
Senior Engineering Answer
The default bridge network uses a virtual Ethernet pair (veth) attached to docker0 with NAT for outbound traffic, while user-defined bridge networks additionally provide Docker's embedded DNS server (127.0.0.11) so containers resolve each other by service or container name. Host networking binds the container directly to the host network namespace without NAT overhead. None disables all external network interfaces except loopback.
docker network create app-net docker run -d --name redis --network app-net redis:7-alpine docker run -d --name api --network app-net -e REDIS_HOST=redis my-api:1.0
Containers attached to the default legacy 'bridge' network cannot resolve each other by container name; automatic DNS discovery only works on user-defined networks.
Why does PID 1 inside a Docker container behave differently for signals and zombie processes?
Senior Engineering Answer
The Linux kernel grants PID 1 special signal semantics: default signal dispositions like terminating on SIGTERM or SIGINT are ignored unless the process explicitly registers a signal handler. Additionally, if child processes terminate and their parent exits, they are reparented to PID 1, which must call wait() to reap zombies. Running via tini or docker run --init provides a lightweight init wrapper as PID 1 to forward signals and reap zombies.
# Use built-in init process or tini inside the Dockerfile docker run --init --rm my-worker:latest # Or in Dockerfile: RUN apk add --no-cache tini ENTRYPOINT ["/sbin/tini", "--", "/usr/local/bin/worker"]
Ignoring PID 1 signal handling causes docker stop to wait the full 10-second timeout before sending SIGKILL, corrupting in-flight requests and delaying rolling deployments.
How do OverlayFS (overlay2) layers enable copy-on-write storage in Docker, and what happens during file deletion or modification?
Senior Engineering Answer
The overlay2 storage driver stacks multiple read-only image layers as lowerdir, an empty writable container directory as upperdir, and presents a unified view at merged. When a container reads a file, it reads directly from lowerdir. When modifying an existing file, OverlayFS performs copy-up—copying the entire file from lowerdir to upperdir before editing. Deleting a lowerdir file creates a zero-byte whiteout character device (0/0) in upperdir to mask it.
# Inspect overlay2 mount directories for a container
docker inspect --format '{{json .GraphDriver.Data}}' my-containerRunning RUN chmod -R or chown -R on a large directory created in an earlier Dockerfile layer copies every touched file into the new layer, doubling the image size.
How do Linux namespaces and cgroups v2 work together under the hood to isolate and constrain containers?
Senior Engineering Answer
Namespaces isolate visibility: PID hides host processes, NET gives private interfaces and routing tables, MNT isolates filesystem mount points, IPC isolates shared memory, UTS isolates hostnames, and USER maps container UIDs to unprivileged host UIDs. Control Groups v2 (cgroups) enforce resource quotas and accounting in a unified hierarchy—capping memory (memory.max, triggering container-scoped OOM kills), CPU bandwidth (cpu.max), and PIDs (pids.max) to prevent noisy-neighbor exhaustion.
docker run -d --memory=512m --memory-swap=512m --cpus=1.5 --pids-limit=256 my-api:latest
Setting --memory without setting --memory-swap equal to --memory allows Docker to allocate an equal amount of swap, masking memory leaks until host swap saturates.
How does BuildKit improve Docker builds with cache mounts, secret mounts, and SSH forwarding?
Senior Engineering Answer
BuildKit executes Dockerfile stages as a concurrent DAG rather than linearly and introduces ephemeral RUN --mount options. A cache mount (--mount=type=cache) persists compiler or package caches (like /root/.cache/pip or /go/pkg/mod) across builds without storing them in the final image layer. Secret mounts (--mount=type=secret) inject private tokens or .npmrc files into a single RUN command in tmpfs without baking credentials into layer history.
# syntax=docker/dockerfile:1
FROM python:3.12-slim
RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=secret,id=pip_conf,target=/etc/pip.conf \
pip install -r requirements.txtPassing secrets via ARG or ENV exposes them permanently via docker history and image metadata; always use BuildKit --mount=type=secret for build-time credentials.
What security hardening flags and capabilities should you apply when running production containers?
Senior Engineering Answer
Production containers should run as a non-root USER, mount the root filesystem read-only (--read-only) with explicit tmpfs mounts for scratch directories, set --security-opt=no-new-privileges:true to block setuid escalation, and drop all Linux capabilities (--cap-drop=ALL), adding back only what is strictly needed (e.g., NET_BIND_SERVICE). Default seccomp and AppArmor profiles further block dangerous syscalls like kexec_load or mount.
docker run -d \ --user 10001:10001 \ --read-only --tmpfs /tmp:rw,noexec,nosuid,size=64m \ --cap-drop=ALL \ --security-opt=no-new-privileges:true \ my-service:2.1
Granting --privileged to troubleshoot permissions disables all namespace/device isolation, seccomp, and capabilities, effectively giving the container full root control over the host.
How does Rootless Docker work via user namespaces, and what operational trade-offs does it introduce?
Senior Engineering Answer
Rootless Docker runs both dockerd and container runtimes as an unprivileged host user by leveraging Linux user namespaces (newuidmap/newgidmap via /etc/subuid and /etc/subgid) and rootlesskit with slirp4netns or pasta for user-space networking. Even if an attacker escapes the container runtime, they land on the host with an unprivileged UID. Trade-offs include higher network packet forwarding overhead from slirp4netns, inability to bind privileged ports <1024 without sysctl tweaks, and limited AppArmor support.
# Verify rootless daemon context and UID mapping inside container
docker info --format '{{.SecurityOptions}}'
docker run --rm alpine cat /proc/self/uid_mapAssuming --user 1000 in a Dockerfile is equivalent to Rootless Docker: --user 1000 only drops privileges inside the container process, whereas Rootless Docker eliminates root ownership of the dockerd daemon socket itself.
How do OCI image manifests, multi-architecture builds (buildx), and content-addressable digests guarantee supply chain integrity?
Senior Engineering Answer
An OCI image index (manifest list) maps CPU architecture/OS pairs (linux/amd64, linux/arm64) to individual platform manifests, each referencing immutable config and layer blobs by SHA-256 digest. Docker buildx uses QEMU emulation or remote native builders to assemble multi-arch indexes in one push. Pinning base images and deployments by immutable @sha256:... digests—combined with Cosign signatures and SBOM attestations—prevents mutable tag-hijacking attacks.
FROM node:22-alpine@sha256:9b1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b # Multi-arch build & push with provenance # docker buildx build --platform linux/amd64,linux/arm64 --provenance=true --push -t ghcr.io/org/app:1.4.0 .
Deploying mutable tags like :latest or :22-alpine across staging and production can silently roll out different image digests between nodes if a registry tag is overwritten.
How do containerd, containerd-shim, and runc interact when dockerd starts and manages a container?
Senior Engineering Answer
dockerd delegates container lifecycle management over gRPC to containerd. containerd pulls OCI images and invokes a per-container containerd-shim process, which calls runc to configure namespaces, cgroups, and rootfs via clone() and execve(). Once the container process starts, runc exits immediately, leaving containerd-shim as the lightweight parent that keeps stdio pipes open and reports exit codes—allowing dockerd and containerd to restart or upgrade without killing running containers.
# Observe daemon -> containerd -> shim -> container process tree on Linux host ps -ef --forest | grep -E 'dockerd|containerd|shim'
Thinking dockerd itself stays in the runtime execution path of container processes; with live-restore enabled, containers continue running uninterrupted even if dockerd crashes.
How do you diagnose and fix container memory accounting discrepancies (RSS vs Page Cache vs OOM Kill 137) in production?
Senior Engineering Answer
Exit code 137 indicates SIGKILL—commonly triggered by the cgroup OOM killer when anonymous memory plus active file page cache and kernel slab memory exceed the cgroup limit. JVM, Node.js, or Go runtimes that read /proc/meminfo instead of /sys/fs/cgroup/memory.max will size heaps to host RAM rather than container limits unless container-aware runtime flags are active. Inspect memory.stat (anon vs file vs slab) to distinguish genuine heap leaks from buffered disk I/O cache.
# Check container exit code and cgroup v2 memory breakdown
docker inspect my-app --format 'Exit={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}'
docker exec my-app cat /sys/fs/cgroup/memory.stat | grep -E '^(anon|file|slab) 'Assuming high container memory usage in docker stats always indicates an application leak; Linux includes reclaimable filesystem page cache in usage metrics until memory pressure forces reclamation.
Docker Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis Docker preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Cloud, DevOps & Systems.
How does a Docker container differ architecturally from a traditional virtual machine?
What is the difference between a Docker image, a container, and a volume?
What is the difference between COPY and ADD, and between CMD and ENTRYPOINT in a Dockerfile?
How do you prevent sensitive files, build artifacts, and bloated directories from slowing down Docker builds?
How does Docker layer caching work, and how should you order Dockerfile instructions to maximize cache reuse?
How do multi-stage Docker builds shrink production images and improve security?
Frequently Asked Technical Interview Questions (Docker)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
What is the difference between docker stop and docker kill?
Why should you avoid mounting /var/run/docker.sock into application containers?
How do Docker healthchecks work and what are their limitations?
When should you use bind mounts versus named Docker volumes?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.