← Interview Prep

INTERVIEW · DOCKER · EASY → ADVANCED

Docker (Advanced) — Interview Questions.

docker containers buildkit container-security interview
Docker from fundamentals to internals — images & layers, BuildKit & caching, namespaces/cgroups, networking, storage, security hardening, runtimes (containerd/runc), CI pipelines and production debugging — graded easy → hard with full answers. Click to expand. Pair with the Docker cheatsheet, debug guide and Kubernetes admin / container security Q&A.
easy fundamentals / screening medium applied — most loops hard senior / design & debug

Easy — fundamentals

What is Docker and what problem does it solve? easy

Docker packages an app plus its dependencies into an image and runs it as an isolated container that behaves the same on a laptop, CI and prod. It kills "works on my machine": the runtime environment (libs, interpreter, OS userland) ships with the app. Containers are lightweight because they share the host kernel instead of booting a guest OS.

Container vs virtual machine? easy

A VM virtualizes hardware and runs a full guest OS + kernel on a hypervisor — GBs, boots in minutes, strong isolation. A container virtualizes the OS: it is just a Linux process (or tree) isolated with namespaces, limited with cgroups, and built from layered filesystem images — MBs, starts in milliseconds, but shares the host kernel, so isolation is weaker (a kernel bug affects everyone). Use VMs for hard multi-tenant boundaries or different kernels; containers for density and speed. Often combined: containers inside VMs.

Image vs container? easy

An image is a read-only, layered template (filesystem + metadata: cmd, env, ports). A container is a running (or stopped) instance of an image with a thin writable layer on top plus its own process, network and mounts. One image → many containers. Class vs object is the usual analogy.

What is a Dockerfile? easy

A text recipe of instructions (FROM, COPY, RUN, CMD…) that docker build executes to produce an image. Each filesystem-changing instruction creates a layer.

What is Docker Hub / a registry? easy

A registry stores and distributes images (Docker Hub, GHCR, ECR, GCR/Artifact Registry, Harbor, self-hosted registry:2). You docker push / docker pull by registry/repo:tag or by digest.

Common commands you use daily? easy

docker run, ps -a, logs -f, exec -it ... sh, build, images, stop/start/rm, inspect, stats, cp, system df, system prune, network ls, volume ls.

What does docker run -d -p 8080:80 --name web nginx do? easy

Pulls nginx:latest if absent, creates a container named web, starts it detached (-d), and publishes host port 8080 → container port 80 (format is host:container). Without -p the port is reachable only on the container network, not from outside.

EXPOSE vs -p? easy

EXPOSE 80 is only documentation/metadata — it publishes nothing. -p (or -P to publish all exposed ports to random host ports) actually creates the port mapping.

COPY vs ADD? easy

Both copy files into the image. ADD additionally auto-extracts local tar archives and can fetch remote URLs — surprising behaviour. Best practice: use COPY unless you specifically need tar auto-extraction.

CMD vs ENTRYPOINT? easy

ENTRYPOINT is the fixed executable; CMD supplies default arguments (or a default command if no ENTRYPOINT) and is overridden by anything after the image name in docker run. Together: ENTRYPOINT ["python","app.py"] + CMD ["--port","8000"] → run with different flags without retyping the program. Override ENTRYPOINT only with --entrypoint. Always use the exec form (JSON array) so the process is PID 1 and receives signals.

RUN vs CMD vs ENTRYPOINT? easy

RUN executes at build time and bakes the result into a layer (install packages). CMD/ENTRYPOINT define what runs at container start.

What is a volume and why use it? easy

Container writable layers are ephemeral — deleted with the container. A volume is Docker-managed persistent storage that outlives the container, can be shared, and bypasses the union filesystem (faster). Use for databases, uploads, anything that must survive a rebuild.

Volume vs bind mount vs tmpfs? easy

Volume (-v name:/path): managed by Docker under /var/lib/docker/volumes, portable, driver-pluggable — the default for prod data. Bind mount (-v /host/path:/path): maps a specific host path — great for dev (live code reload), but ties the container to host layout and permissions. tmpfs: in-memory only, never hits disk — for secrets/scratch data.

How do containers talk to each other? easy

Put them on the same user-defined bridge network; Docker's embedded DNS (127.0.0.11) resolves container/service names. The default bridge network has no name resolution (only legacy --link).

What are Docker Compose and its use? easy

A YAML file (compose.yaml) declaring a multi-container app — services, networks, volumes, env, dependencies — started with docker compose up. Ideal for local dev, CI integration tests and small single-host deployments; not an orchestrator for multi-node production.

How do you see logs and shell into a container? easy

docker logs -f --tail 100 <c>; docker exec -it <c> sh (or bash). Distroless/minimal images have no shell — use docker debug, an ephemeral debug container sharing namespaces, or nsenter from the host.

What does docker system prune remove? easy

Stopped containers, dangling images, unused networks and build cache. -a also removes all unused images; --volumes removes unused volumes (data loss risk — read the prompt).

What is a dangling image? easy

An untagged image (<none>:<none>) left behind when a new build re-tags a name. Safe to prune with docker image prune.

What is .dockerignore? easy

Excludes files from the build context (.git, node_modules, *.log, secrets). It shrinks the context sent to the daemon, speeds builds, keeps secrets out of COPY . . and prevents needless cache invalidation.

What is the latest tag? easy

Just a default tag name — not "newest" and not immutable. Pin explicit versions (or digests) in production so deploys are reproducible.

How do you pass configuration to a container? easy

Env vars (-e, --env-file), mounted config files, command args. Never bake secrets into image layers or ENV; build once, configure per environment at runtime (12-factor).

What is a restart policy? easy

--restart no|on-failure[:N]|always|unless-stopped. unless-stopped is the common single-host choice: restarts on crash and after daemon/host reboot, but not if you stopped it manually.

Medium — applied

Explain how Docker image layers and the union filesystem work. medium

Each filesystem-changing Dockerfile instruction produces a read-only layer (a tar diff identified by a content hash). The storage driver (overlay2 on modern Linux) stacks them with OverlayFS: lowerdir = image layers, upperdir = the container's writable layer, merged = the view the container sees. Reads fall through to the first layer containing the file; writes use copy-on-write — a file from a lower layer is copied up to upperdir before modification; deletes create whiteout files. Consequences: layers are shared between images (one pull of ubuntu serves all), a file deleted in a later layer still occupies space in the earlier one, and heavy writes to the container layer are slow — use volumes.

How does the build cache work and how do you order a Dockerfile for it? medium

For each instruction Docker checks whether an identical instruction on an identical parent layer was already built; for COPY/ADD it also compares file content checksums. A cache miss invalidates every layer after it. So order from least- to most-frequently-changing: base image → system packages → copy only dependency manifests (package.json, requirements.txt, go.mod) → install deps → copy source → build. That way a source edit reuses the expensive dependency layer. Use BuildKit cache mounts (RUN --mount=type=cache,target=/root/.cache/pip) to keep package caches across builds even when the layer rebuilds. In CI, export/import cache (--cache-to/--cache-from type=registry or type=gha).

What is a multi-stage build and why use it? medium

Multiple FROM stages in one Dockerfile; later stages COPY --from=builder only the artifacts they need. Build tooling (compilers, dev deps, source) stays in the builder stage and never ships.

FROM golang:1.23 AS build
WORKDIR /src
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /app /app
ENTRYPOINT ["/app"]

Result: 1 GB toolchain image → ~15 MB runtime image, smaller attack surface, faster pulls. Bonus: --target builds a specific stage (e.g. a test or dev stage) and BuildKit builds independent stages in parallel.

How do you reduce image size? medium

Small base (alpine, -slim, distroless, scratch for static binaries); multi-stage builds; combine RUN steps and clean in the same layer (apt-get install --no-install-recommends … && rm -rf /var/lib/apt/lists/*); good .dockerignore; install only prod deps; don't chown -R/chmod -R in a separate layer (it duplicates files — use COPY --chown); inspect with docker history and dive. Caveat: Alpine uses musl libc — can break glibc-linked binaries (Python wheels, DNS edge cases); -slim Debian is the safer default.

Bridge, host, none, overlay, macvlan — explain Docker network drivers. medium

bridge (default): a Linux bridge (docker0 or a custom one); containers get private IPs, outbound is NAT/masqueraded, inbound needs -p. host: container shares the host's network namespace — no isolation, no NAT, best raw performance, port conflicts possible. none: only loopback — total network isolation. overlay: VXLAN-based multi-host network (Swarm) so containers on different nodes talk privately. macvlan/ipvlan: container gets its own MAC/IP on the physical LAN — for legacy apps needing "real" addresses. container:<id> mode joins another container's namespace (the sidecar/Kubernetes-pod pattern).

How does -p 8080:80 actually work under the hood? medium

The daemon installs iptables (or nftables) rules: a DNAT rule in the DOCKER chain of the nat table rewrites traffic hitting host:8080 to containerIP:80, plus a FORWARD allow rule; outbound uses a MASQUERADE rule. (A userland docker-proxy handles localhost/hairpin cases.) Gotcha: because Docker writes its own iptables rules, published ports bypass UFW/firewalld input rules — to restrict, bind to 127.0.0.1:8080:80 or filter in the DOCKER-USER chain.

How does container DNS and service discovery work? medium

On user-defined networks each container's /etc/resolv.conf points to Docker's embedded DNS at 127.0.0.11, which resolves container names, network aliases and Compose service names (round-robin across replicas) and forwards everything else to the host's resolvers. Custom --dns, --add-host and --dns-search override. The default bridge lacks this — a classic "can't resolve the other container" bug.

What is PID 1 in a container and why does it matter? medium

The ENTRYPOINT/CMD process is PID 1 in the container's PID namespace. The kernel gives PID 1 special signal semantics — no default handlers, so SIGTERM is ignored unless the app installs a handler; and PID 1 must reap zombie children. Symptoms: docker stop hangs 10 s then SIGKILLs; zombie pile-up. Causes: shell-form CMD npm start makes /bin/sh -c PID 1, which doesn't forward signals. Fixes: exec form, exec in shell wrappers, or --init (injects tini) / init: true in Compose.

What happens on docker stop? medium

Sends the image's STOPSIGNAL (default SIGTERM) to PID 1, waits --time/stop_grace_period (default 10 s), then SIGKILL. docker kill sends SIGKILL immediately (or a chosen signal). Apps must handle SIGTERM: stop accepting work, drain in-flight requests, flush, exit 0. Tune the grace period for slow shutdowns.

How do you limit CPU and memory, and what happens at the limit? medium

--memory=512m --memory-swap=512m --cpus=1.5 (cgroup memory.max, cpu.max); also --cpu-shares (relative weight, only matters under contention), --cpuset-cpus, --pids-limit. Exceeding memory → kernel OOM-kills the process (exit 137, State.OOMKilled=true). Exceeding CPU → throttled, not killed (visible as latency; check cpu.stat nr_throttled). Runtimes like JVM/Node must be container-aware (modern JVM reads cgroup limits; set heap percentage), or they size themselves off host RAM and get OOM-killed.

How do you debug a container that exits immediately? medium

docker ps -a → exit code; docker logs; docker inspect --format '{{.State.ExitCode}} {{.State.OOMKilled}} {{.State.Error}}'. Codes: 0 normal finish (the process just ended — container needs a foreground process), 1 app error, 125 daemon error, 126 not executable, 127 command not found, 137 SIGKILL/OOM, 139 segfault, 143 SIGTERM. Reproduce interactively: docker run -it --entrypoint sh image. Common culprits: wrong CMD, missing env/secret, Windows CRLF in shell script, no exec permission, daemonizing process (nginx without daemon off;), wrong architecture.

How do you handle secrets in Docker? medium

Never ENV/ARG/COPY secrets into the image — they live forever in layers/history (docker history, registry). Build time: BuildKit RUN --mount=type=secret,id=npmrc … (mounted, never persisted) or --mount=type=ssh. Runtime: Docker/Swarm secrets (files in /run/secrets, tmpfs), Compose secrets:, or inject from Vault / cloud secret managers / Kubernetes Secrets. Env vars are convenient but leak via docker inspect, /proc/<pid>/environ, crash dumps and child processes — prefer files.

ARG vs ENV? medium

ARG exists only at build time (--build-arg); not in the running container, but values still show in docker history. ENV persists into the image and every container. Use ARG for version pins/build toggles, ENV for runtime defaults. ARGs declared before the first FROM are only usable in FROM lines unless re-declared.

Shell form vs exec form? medium

Shell: CMD npm start → runs as /bin/sh -c "npm start" (PID 1 = sh; variable expansion works; signals not forwarded). Exec: CMD ["npm","start"] → no shell, app is PID 1, receives signals, but no $VAR expansion (call sh -c explicitly if needed). Prefer exec for ENTRYPOINT/CMD.

Why run containers as non-root and how? medium

Container root is uid 0 on the host kernel; any escape or bind-mount mistake gives host-root. Create a user: RUN useradd -r -u 10001 app + USER 10001 (numeric UID so Kubernetes runAsNonRoot can verify), COPY --chown. Combine with read-only rootfs, dropped capabilities, no-new-privileges. For unprivileged ports use >1024 (or net.ipv4.ip_unprivileged_port_start).

Explain Linux capabilities in Docker. medium

Root's power is split into ~40 capabilities. Docker starts containers with a reduced default set (CHOWN, NET_BIND_SERVICE, SETUID, KILL…) and drops the dangerous ones (SYS_ADMIN, NET_ADMIN, SYS_MODULE…). Harden with --cap-drop=ALL --cap-add=NET_BIND_SERVICE. --privileged grants all capabilities, disables seccomp/AppArmor confinement, and exposes all host devices — avoid; it's effectively root on the host.

What is the HEALTHCHECK instruction? medium

HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 CMD curl -f http://localhost/health || exit 1. Docker runs it periodically and reports healthy/unhealthy/starting in docker ps. Standalone Docker only reports — it doesn't restart on unhealthy (Swarm does; Compose depends_on: condition: service_healthy uses it for ordering). Kubernetes ignores it and uses its own probes. The check tool (curl/wget) must exist in the image.

How does Compose handle startup ordering? medium

depends_on only orders start, not readiness. Use depends_on: db: condition: service_healthy with a healthcheck on the dependency, and make apps retry connections anyway (they must survive DB restarts in prod). Related: profiles for optional services, docker compose watch for dev sync, multiple files/overrides (-f compose.yaml -f compose.prod.yaml), .env interpolation.

What does docker build actually send to the daemon (build context)? medium

The whole directory (minus .dockerignore) is tarred and sent as the context; COPY can only reference files inside it. Building from / or a repo with GB of assets is slow. Use a tight context, .dockerignore, or -f path/Dockerfile with a subdirectory context. BuildKit transfers only the files it needs, which mitigates but doesn't remove the problem.

What is BuildKit and why is it better than the legacy builder? medium

BuildKit (default since Docker 23) builds a dependency DAG (LLB): parallel independent stages, skips unused stages, smarter cache, --mount=type=cache|secret|ssh|bind, heredocs in Dockerfiles, multi-platform output, remote/registry cache export, SBOM/provenance attestations. Drive it via docker buildx build (with the docker-container driver for advanced features).

How do you build multi-architecture images (amd64 + arm64)? medium

docker buildx build --platform linux/amd64,linux/arm64 -t repo/app:1.0 --push .. Produces a manifest list / OCI index pointing at per-arch images; clients pull the matching one. Build via QEMU emulation (simple, slow) or native builders per arch / cross-compilation in the Dockerfile (FROM --platform=$BUILDPLATFORM with TARGETARCH args) for speed. Classic bug: building on an Apple-silicon Mac and deploying to amd64 nodes → exec format error.

Image tag vs digest — which should you deploy by? medium

Tags are mutable pointers; the same tag can change contents. The digest (repo/app@sha256:…) is the content hash of the manifest — immutable. Deploy by digest (or immutable tags + registry tag-immutability) for reproducibility, rollback certainty and signature verification; keep human tags (1.4.2) for readability, resolved to digests by CI/GitOps.

How do you inspect what's inside an image or why it's large? medium

docker history --no-trunc img (layer sizes + commands), docker image inspect, docker save img | tar -t, the dive tool for per-layer file diffs/wasted space, docker scout/trivy for contents + CVEs, syft for SBOM.

How do you share data between containers? medium

Named volume mounted in both (watch concurrent-write safety); --volumes-from (legacy); shared tmpfs; or network (preferred — sockets/HTTP/queues). A Unix socket on a shared volume is a common sidecar pattern.

How do you back up and restore a volume? medium

Run a throwaway container mounting the volume and a host dir:

docker run --rm -v pgdata:/data -v $PWD:/backup alpine \
  tar czf /backup/pgdata.tgz -C /data .
docker run --rm -v pgdata:/data -v $PWD:/backup alpine \
  tar xzf /backup/pgdata.tgz -C /data

For databases prefer logical/consistent backups (pg_dump, mysqldump, snapshots) over copying live files — a raw tar of a running DB can be inconsistent.

What logging drivers exist and what is the default pitfall? medium

Default json-file writes unbounded logs on the host — a classic disk-full cause. Configure rotation in /etc/docker/daemon.json: {"log-driver":"json-file","log-opts":{"max-size":"10m","max-file":"3"}} (or local driver, which rotates by default). Others: journald, syslog, fluentd, gelf, awslogs, splunk. Apps should log to stdout/stderr, not files inside the container. Note: docker logs doesn't work with some remote drivers unless dual-logging is on.

Docker stats says memory is 400 MiB but the app limit is 512 MiB — are we safe? medium

Not necessarily: docker stats historically included page cache; the OOM decision uses working set (usage − inactive file) plus anonymous memory. Check memory.stat in the cgroup, watch for oom_kill counts, and remember tmpfs mounts, JVM off-heap/metaspace, thread stacks and native libs all count. Size limits from measured RSS under peak load plus headroom.

How do you run a one-off task or cron-like job in Docker? medium

docker run --rm image cmd for one-offs (--rm deletes the container after exit). For schedules use host cron/systemd timers calling docker run, a dedicated scheduler container, or — in a cluster — Kubernetes CronJobs. Avoid running cron inside app containers (PID 1 + logging + env pain).

What is the difference between docker run, start, create, exec, attach? medium

create builds a container without starting; start starts an existing one; run = pull (if needed) + create + start. exec runs a new process inside a running container (shell debugging); attach connects your terminal to the container's existing PID 1 stdio (Ctrl-C may stop it; detach with Ctrl-p Ctrl-q).

How does docker commit compare to a Dockerfile, and should you use it? medium

commit snapshots a container's writable layer into an image. It works for quick experiments but is unreproducible, undocumented and leaves history-less blobs. Production images should always come from a versioned Dockerfile in CI.

Hard — internals, security & design

What actually is a container at the Linux kernel level? hard

No such kernel object — a container is a normal process wrapped with: namespaces (what it can see): pid, net, mnt, uts, ipc, user, cgroup (+ time); cgroups (what it can use): CPU, memory, pids, blkio/io; a root filesystem (overlay mount + pivot_root); security layers: capabilities, seccomp-bpf syscall filter, AppArmor/SELinux, optional user namespace remap. You can build one by hand: unshare --fork --pid --mount-proc --net --uts chroot rootfs /bin/sh. Docker/containerd/runc just automate this and manage images, networking and lifecycle.

Describe the Docker architecture: dockerd, containerd, runc, shim. hard

docker CLI → REST over /var/run/docker.sock → dockerd (images, networks, volumes, build API) → containerd (CRI-capable high-level runtime: image pull/unpack, snapshots, container lifecycle) → containerd-shim-runc-v2 (one per container; keeps stdio/exit status, lets containerd/dockerd restart without killing containers = live-restore) → runc (OCI low-level runtime: sets up namespaces/cgroups, execs the process, then exits). Standards: OCI image-spec, runtime-spec, distribution-spec. Kubernetes talks CRI straight to containerd/CRI-O; dockershim was removed in 1.24 — images built with Docker still run fine because they're OCI images.

What is in an OCI image? Walk through manifest, config, layers. hard

An image = manifest (JSON listing the config digest + ordered layer digests + media types) + config (JSON: entrypoint, cmd, env, user, exposed ports, labels, rootfs.diff_ids, history) + layer blobs (compressed tarballs, content-addressed by sha256). A multi-arch image adds an index (manifest list) mapping platform → manifest. Everything is content-addressed, so layers dedupe across images and pulls verify integrity. Pull = fetch manifest → fetch missing layers in parallel → unpack into snapshotter. skopeo inspect / crane manifest let you look without pulling.

How does overlay2 compare with other storage drivers, and what are its limits? hard

overlay2 is the default: file-level CoW, kernel-native, fast, page-cache friendly (shared layers share cache). devicemapper (block-level, deprecated), btrfs/zfs (snapshot-native, ops overhead), fuse-overlayfs (rootless), vfs (no CoW — copies everything, test only). Limits: first-write to a big file copies the whole file up (slow for large DB files in the container layer), inode exhaustion (df -i) on /var/lib/docker, needs a backing fs with d_type (ext4/xfs with ftype=1), and some apps misbehave with overlayfs semantics (rename of directories, fsync-heavy DBs → use volumes). Put /var/lib/docker on its own fast disk.

Rootless Docker vs userns-remap vs running as non-root — differences? hard

USER non-root in the image only changes the in-container uid; the daemon still runs as host root. userns-remap: daemon (root) maps container uid 0 → an unprivileged subuid range on the host, so a container-root escape is host-nobody; trade-off: volume ownership, some features (privileged, host networking) restricted. Rootless mode: the whole daemon + containers run as an unprivileged user (user namespaces, slirp4netns/pasta networking, fuse-overlayfs or native overlay); strongest defence against daemon compromise but limits: no ports <1024 by default, no cross-uid cgroup limits without systemd delegation, slower networking, some storage drivers. Podman is daemonless/rootless by design.

Why is mounting /var/run/docker.sock into a container dangerous? hard

The socket is the Docker API; whoever can talk to it can start a container with -v /:/host --privileged → full root on the host. Mounting it into CI runners, Traefik, Portainer or "docker-in-docker shortcuts" hands that power to anything compromised in the container. Mitigations: don't mount it; use a socket proxy that allows only read endpoints (e.g. tecnativa/docker-socket-proxy); rootless Docker; Kaniko/BuildKit/Buildah for in-cluster builds without a daemon; separate build nodes. Same logic: membership of the docker group ≡ root.

How do you harden a Docker host and containers end-to-end? hard

Image: minimal/distroless base, pinned digests, scanned (Trivy/Grype/Scout), signed (cosign), SBOM, no secrets, non-root USER. Run: --read-only rootfs + --tmpfs /tmp, --cap-drop=ALL + add back minimal, --security-opt no-new-privileges, default (or custom) seccomp profile, AppArmor/SELinux on, --pids-limit, memory/CPU limits, no --privileged, no host namespaces (--pid=host, --net=host), no docker.sock mount. Daemon/host: rootless or userns-remap, TLS-protect the TCP API (never expose 2375 unauthenticated), keep Docker + kernel + runc patched, audit with docker-bench-security / CIS Docker Benchmark, auditd rules on /var/lib/docker, log shipping, runtime detection (Falco). For hostile multi-tenancy escalate to gVisor / Kata / Firecracker sandboxes.

What is seccomp and how do you tune it? hard

seccomp-bpf filters syscalls a process may call. Docker's default profile blocks ~44 of ~300+ syscalls (e.g. keyctl, mount, ptrace in older kernels, reboot, kexec_load). Custom: --security-opt seccomp=profile.json (allow-list with defaultAction: SCMP_ACT_ERRNO). Build a minimal profile by tracing the app (strace -c, oci-seccomp-bpf-hook, Inspektor Gadget) then verifying in staging. seccomp=unconfined is a red flag in review.

How do container escapes happen and which controls stop them? hard

Typical paths: --privileged or SYS_ADMIN (mount host disk / cgroup release_agent trick), exposed docker.sock, host path mounts of /, /proc, /sys, or /etc, --pid=host + ptrace, kernel/runc CVEs (e.g. CVE-2019-5736 runc overwrite, CVE-2024-21626 "Leaky Vessels" fd leak, Dirty Pipe/Cow), writable hostPath, malicious images running as root. Controls: patch runtime + kernel, non-root + userns, drop caps, seccomp/AppArmor/SELinux, read-only fs, no sensitive mounts, admission policy (Kubernetes Pod Security), sandboxed runtimes for untrusted code.

Explain Docker bridge networking internals. hard

Creating a bridge network makes a Linux bridge (br-xxxx). Each container gets a veth pair: one end in the container netns (eth0), the peer attached to the bridge. Containers on the bridge switch at L2; the bridge IP is their gateway. Egress: iptables MASQUERADE on the subnet. Ingress: DNAT per published port. Inspect with ip -br addr, bridge link, iptables -t nat -S, nsenter -t <pid> -n ip a. Inter-network isolation comes from the DOCKER-ISOLATION chains; --internal networks have no external route at all.

How does overlay networking work across hosts? hard

Swarm overlay wraps container frames in VXLAN (UDP 4789) between nodes, with a distributed key-value state (gossip, port 7946 TCP/UDP) for endpoint discovery; optional IPSec encryption (--opt encrypted). Needs ports 2377 (swarm mgmt), 7946, 4789 open between nodes. Overhead: VXLAN header lowers MTU (~50 B) — a classic source of black-hole packet loss with large payloads; align MTU. At scale people use Kubernetes CNIs (Cilium, Calico) instead.

Compose vs Swarm vs Kubernetes — when would you choose each? hard

Compose: single host — dev, CI, small apps. Swarm: built-in clustering (services, rolling updates, overlay, secrets, VIP load balancing) with tiny operational cost; limited ecosystem, minimal feature growth — fine for small teams with simple needs. Kubernetes: de-facto standard — rich scheduling, CRDs/operators, autoscaling, ecosystem, managed offerings; steep complexity. Decision drivers: team skills, scale, multi-tenancy, ecosystem needs (service mesh, GitOps, operators), cloud strategy. Compose files can be converted/reused via Kompose or Compose Bridge.

Docker vs Podman vs containerd vs CRI-O vs LXC — compare. hard

Docker: full UX + daemon + build + Compose. containerd: the industrial runtime inside Docker, used directly by Kubernetes (nerdctl = Docker-like CLI). CRI-O: Kubernetes-only OCI runtime (OpenShift). Podman: daemonless, rootless-first, Docker-compatible CLI, pods, systemd/Quadlet integration, uses Buildah/Skopeo. LXC/LXD(Incus): system containers (full init, VM-like). All consume OCI images; low-level runtimes: runc, crun, sandboxed runsc (gVisor), kata.

How would you design a secure, fast CI image pipeline? hard

PR → lint (hadolint) → build with BuildKit + registry/GHA cache → unit test via a test target → scan (Trivy: OS + language deps + misconfig + secrets) with a severity gate → generate SBOM (syft) + provenance (SLSA) → push by digest to registry → cosign sign → deploy referencing digest; admission controller (Kyverno/Connaisseur/Sigstore policy-controller) rejects unsigned/unscanned images. Rootless/daemonless builders (Kaniko, BuildKit rootless, Buildah) on ephemeral runners; separate build and deploy credentials; tag immutability; scheduled re-scans since CVEs appear after build; auto-rebase base images (Renovate/Dependabot/Scout).

Why do builds differ between laptop and CI, and how do you get reproducible images? hard

Causes: unpinned base tags, apt-get/apk/pip pulling latest, timestamps in layers, differing arch, cache state, COPY including untracked files, network-dependent steps. Fixes: pin base by digest, pin package versions + lockfiles (npm ci, pip --require-hashes), clean context via .dockerignore, SOURCE_DATE_EPOCH + --output type=image,rewrite-timestamp=true, hermetic builds, same builder everywhere. Perfect bit-for-bit reproducibility is hard; aim for semantic reproducibility plus a recorded provenance attestation.

What is distroless / scratch, and what do you lose? hard

Distroless images contain only the app runtime + CA certs/tzdata/libc — no package manager, shell or coreutils; scratch is an empty fs for static binaries. Win: tiny, far fewer CVEs, hard for attackers to live off the land. Cost: no exec sh debugging (use :debug variants, docker debug, ephemeral containers in Kubernetes), must bring CA bundle, /etc/passwd entry for non-root, timezone data, and be careful with glibc vs musl static linking (CGO_ENABLED=0 for Go).

How do image vulnerabilities get managed over time? hard

Scan at build and continuously in the registry/runtime (new CVEs appear for already-shipped images). Triage by reachability/exploitability (VEX, EPSS, KEV), not raw counts; fix by rebuilding on patched base rather than patching in place; keep images small to reduce surface; automate base-image bumps; define SLAs per severity; track SBOMs so "are we affected by CVE-X?" is a query, not an investigation.

How do you run Docker in Docker for CI safely? hard

Options: (1) mount host docker.sock (DooD) — fast, but root-equivalent and shares host state; (2) docker:dind sidecar with --privileged — isolated daemon but privileged; (3) rootless DinD / Sysbox runtime (system containers that run Docker unprivileged); (4) avoid a daemon: Kaniko / BuildKit rootless / Buildah / ko / Jib; (5) ephemeral VM runners per job. Prefer 3–5 for untrusted code; always isolate runners per project.

Describe how docker run works end-to-end. hard

CLI → API POST /containers/create → dockerd checks image locally, else pulls via containerd (manifest, layers, unpack into snapshotter) → allocates container ID, creates writable overlay layer, network namespace + veth, volumes, cgroup → hands OCI bundle (config.json + rootfs) to containerd → shim spawns runc → runc clones with namespace flags, applies cgroups/seccomp/caps, pivot_roots into rootfs, execs ENTRYPOINT+CMD → runc exits, shim monitors → dockerd streams logs, reports status. docker stop reverses via signals; rm unmounts and deletes layer.

Docker data is lost after docker compose down — why? hard

Anonymous volumes or container-layer data are removed; down -v also removes named volumes. A named volume declared in compose survives plain down. Another trap: project name changes (directory rename) create a new volume namespace, looking like data loss. Fix: declare named (or external: true) volumes, set name: on the project, back up before destructive commands.

How does Docker handle graceful rolling updates on a single host (no orchestrator)? hard

It doesn't by itself — compose up -d recreates the container (brief downtime). Options: run two instances behind nginx/Traefik and update one at a time with health checks (blue/green via labels); docker rollout plugin; Swarm update_config (parallelism, delay, order: start-first, failure_action rollback); or move to Kubernetes. Make apps drain on SIGTERM and keep connections via LB health.

What is live-restore and when do you use it? hard

"live-restore": true in daemon.json keeps containers running while dockerd restarts/upgrades (shims own the processes). Reduces downtime during daemon patching. Not supported with Swarm mode and can't cross major-version changes in some cases; test it. Containers still need a restart policy for host reboots.

How do you troubleshoot high disk usage in /var/lib/docker? hard

docker system df -v (images, containers, volumes, build cache); du -xh --max-depth=2 /var/lib/docker | sort -h; check unbounded json-file logs (/var/lib/docker/containers/*/*-json.log), large container writable layers (docker ps -s), dangling images/volumes, build cache (docker builder prune --filter until=72h), deleted-but-open files (lsof +L1), inode exhaustion (df -i). Prevent: log rotation, scheduled prune, separate disk with alerting, smaller images.

Container can't reach the internet / DNS fails. Debug. hard

Layer by layer: (1) docker exec c ping 8.8.8.8 (IP works? → DNS issue); (2) cat /etc/resolv.conf, nslookup name 127.0.0.11 (embedded DNS) vs host resolver — corporate/VPN resolvers or 127.0.0.53 systemd-resolved stubs need --dns or daemon dns setting; (3) host sysctl net.ipv4.ip_forward=1; (4) iptables: MASQUERADE rule present? firewalld/ufw/nftables flushed Docker's chains → restart docker; (5) MTU mismatch on VPN/overlay — large packets hang, small ones work (lower --mtu); (6) proxy env vars; (7) IPv6 vs IPv4 only. Tools: nicolaka/netshoot sidecar with tcpdump, curl -v, dig, ss.

What happens when two containers/projects collide on subnet or port? hard

Default bridge uses 172.17.0.0/16 and custom networks pull from 172.18+/192.168; they can overlap corporate VPN ranges, causing blackholed traffic. Set default-address-pools in daemon.json or explicit ipam subnets. Port collisions: only one binding per host IP:port — use different host ports, bind to specific IPs, or front with a reverse proxy routing by host/path.

What are the cgroup v1 vs v2 differences relevant to Docker? hard

v2 = single unified hierarchy, better memory accounting (includes kernel memory), memory.high (throttle before OOM), pressure-stall info (PSI), safer delegation for rootless, eBPF device control. Docker ≥20.10 supports v2; old images with JVM/Node versions that don't detect v2 limits can mis-size heaps. Check with stat -fc %T /sys/fs/cgroup (cgroup2fs = v2).

How do you make a stateful service like Postgres safe in Docker? hard

Named volume (or bind to a fast disk) for PGDATA, never the container layer; stop gracefully with enough stop_grace_period for checkpoint; pin major version (upgrades need pg_upgrade/dump-restore, not just a new tag); set shared memory (--shm-size) and memory limits above shared_buffers; healthcheck with pg_isready; regular logical + physical backups tested via restore; replication/HA outside Docker semantics. For serious prod use managed DBs or an operator on Kubernetes — containers don't remove state-management complexity.

Scenario-based

Production container keeps getting OOMKilled (exit 137). Walk through it. hard

Confirm: docker inspect -f '{{.State.OOMKilled}}' and dmesg | grep -i 'killed process'. Determine which limit: container cgroup (--memory) vs host-wide OOM. Measure working set over time (docker stats, cAdvisor/Prometheus container_memory_working_set_bytes). Distinguish leak (monotonic growth) vs spike (batch, big request) vs mis-sizing (JVM heap/off-heap, Node --max-old-space-size, Python workers × memory). Fix: tune runtime to the cgroup, raise limit with data, cap concurrency/request size, fix the leak, add swap policy knowingly, and alert on 80% of limit.

Image builds take 15 minutes in CI. Make it fast. hard

Profile with --progress=plain; reorder for cache (deps before source); add BuildKit cache mounts; ship registry/GHA remote cache; shrink context (.dockerignore); multi-stage with parallel stages; use a prebuilt base image with heavy toolchains; pin versions so cache keys stay stable; use larger or native-arch builders instead of QEMU; skip builds when only docs changed (path filters); run tests from the built image rather than rebuilding.

The app works locally but exec format error in prod. Why? medium

Architecture mismatch — image built for arm64 (Apple silicon) running on amd64 or vice versa; or a shell script missing its shebang/with CRLF line endings. Check docker image inspect --format '{{.Architecture}}'; rebuild with buildx --platform and publish a multi-arch manifest.

docker stop takes exactly 10 seconds every time. Cause? medium

The app ignores SIGTERM (PID 1 semantics or shell-form CMD), so Docker waits the grace period then SIGKILLs. Fix with exec-form entrypoint, a signal handler, --init/tini, or exec "$@" at the end of wrapper scripts; raise stop_grace_period only if shutdown legitimately takes longer.

A teammate says: "just add --privileged, it fixes the permission error". Response? hard

Don't. Find the minimal need: which syscall/capability/device is denied (dmesg, audit logs, strace)? Then grant exactly that — --cap-add=NET_ADMIN, --device /dev/fuse, a custom seccomp rule, correct volume ownership (--user, chown, :z/:Z for SELinux). --privileged removes the container boundary and is a host-root equivalent.

Files created by the container on a bind mount are owned by root on the host. Fix? medium

Container uid is written straight to host fs. Run with matching ids: --user $(id -u):$(id -g), or build the image with a configurable USER, or use userns-remap/rootless, or write to a named volume instead. On SELinux hosts add :z/:Z.

Compose stack: API crashes at boot with "connection refused" to the database although depends_on is set. Why? hard

depends_on waited for the DB container to start, not accept connections. Add a healthcheck (pg_isready) and condition: service_healthy; also add connect retry/backoff in the app so DB restarts don't take it down; verify the app uses the service name (not localhost) and the right network.

A container works with -p but is reachable from the whole internet despite UFW deny. Explain. hard

Docker inserts DNAT/FORWARD rules ahead of UFW's INPUT chain, so published ports bypass UFW. Bind to loopback (-p 127.0.0.1:5432:5432) behind a reverse proxy, put restrictions in the DOCKER-USER iptables chain, or use a cloud firewall / security group. Audit with ss -tlnp and an external port scan.

Registry pull is slow/rate-limited across a 200-node fleet. Improve. hard

Authenticate to avoid anonymous limits, run a pull-through cache/mirror (registry:2 proxy, Harbor, ECR pull-through), host images in your own registry, shrink and dedupe layers, use lazy-pulling (stargz/SOCI/Nydus) or P2P distribution (Dragonfly, Kraken), pre-pull base images on nodes, and stagger rollouts.

You must run untrusted customer code in containers. Design? hard

Plain Docker isn't a hostile-tenant boundary. Layer: dedicated nodes/VMs per tenant tier, gVisor/Kata/Firecracker sandboxes, rootless/userns, non-root + read-only fs + all caps dropped + strict seccomp, no host mounts, egress-deny network policy, CPU/memory/PID/disk quotas, short lifetimes (ephemeral), no cloud-metadata access (block 169.254.169.254), per-tenant secrets, and runtime monitoring (Falco/eBPF) with automated kill.

Migrating a Compose app to Kubernetes. What changes? hard

Services → Deployments + Services; volumes → PVC/StorageClass; env/secrets → ConfigMap/Secret (external-secrets); healthchecks → readiness/liveness/startup probes; ports → Service/Ingress; depends_on → init containers/readiness + retries; restart policy → controllers; build → CI pipeline pushing to a registry; logging stays stdout → cluster log stack. Do not rewrite blindly: first make the app 12-factor (stateless, config via env, graceful shutdown), then use Kompose/Compose Bridge as a starting skeleton, not a final answer.

Image scan shows 300 CVEs on a Debian base. What do you do? medium

Don't panic-count. Filter to fixable + reachable + exploitable (KEV/EPSS); rebuild on the latest patched base; switch to slim/distroless to drop unused packages; remove build tools via multi-stage; suppress documented non-applicable ones with VEX; set a policy gate (block Critical/High with fix available) and a re-scan schedule.

what industry actually asks

Docker rounds start with image vs container, layers, CMD vs ENTRYPOINT, volumes, networking and quickly move to "how would you shrink / speed up / secure this Dockerfile?" (multi-stage, cache ordering, non-root, pinned digests). Senior loops probe internals (namespaces, cgroups, overlayfs, runc/containerd, PID 1 + signals), security (capabilities, seccomp, rootless, docker.sock risk, supply-chain signing/SBOM) and live debugging (exit 137, DNS, disk full, exec format error). Answer with a method — ps -a → logs → inspect → reproduce with run -it --entrypoint sh — and always state the trade-off (Alpine vs slim, distroless vs debuggability, DinD vs daemonless builders).

← prev: Kubernetes Admin next: Kafka Admin →