PrepStack › DevOps & Cloud › Docker

Docker interview cheat sheet

Images, layers, Dockerfiles, volumes, networks, Compose and production hardening

Docker questions show up in almost every backend, DevOps and full-stack interview. Interviewers check that you know what a container really is (a Linux process with namespaces and cgroups, not a small VM), how images and layers work, how to write a small, cache-friendly and secure Dockerfile, and how containers talk to storage and to each other. Senior rounds add PID 1 and signals, BuildKit, multi-platform builds and security hardening. Read the 15-minute revision first, then switch to Quiz mode and answer out loud.

15-minute revision

  1. A container is a normal Linux process isolated with namespaces (what it can see) and limited with cgroups (what it can use). It shares the host kernel. A VM runs a full guest kernel on a hypervisor.
  2. An image is a read-only stack of layers plus config. A container is a running (or stopped) instance of an image with a thin writable layer on top.
  3. Each RUN, COPY and ADD makes a layer. Layers are cached; a change invalidates that step and every step after it. Copy dependency manifests and install deps before copying source.
  4. Stack: docker CLI → REST API → dockerd → containerd → runc (creates the process). Images and runtimes follow the OCI specs, so other tools (Podman, Kubernetes) can use them.
  5. CMD gives default arguments and is easy to override. ENTRYPOINT fixes the executable. Use the exec form (["node","app.js"]) so your app is PID 1 and gets SIGTERM.
  6. ARG exists only at build time. ENV is baked into the image and visible at runtime. Neither is safe for secrets; use BuildKit --mount=type=secret.
  7. Prefer COPY. ADD also extracts local tar files and fetches URLs, which is surprising and less transparent.
  8. Multi-stage builds: compile in a big builder stage, then COPY --from=build only the artifact into a slim, distroless or scratch runtime stage.
  9. Tags (:1.4, :latest) are mutable pointers. A digest (@sha256:...) is the content hash and never changes. Pin digests for reproducible deploys.
  10. Storage: named volumes (managed by Docker, best for data), bind mounts (host path, best for dev), tmpfs (memory only, never on disk).
  11. Networks: default bridge, user-defined bridge (has DNS by container name), host (no isolation), none, overlay (multi-host, Swarm). -p 8080:80 maps host 8080 to container 80; EXPOSE only documents.
  12. docker stop sends SIGTERM, waits 10 s, then SIGKILL. docker kill sends SIGKILL at once. Exit code 137 = killed (often OOM), 143 = SIGTERM.
  13. PID 1 gets no default signal handlers and must reap zombies. Use exec form, exec in shell scripts, or docker run --init / tini.
  14. Restart policies: no (default), on-failure[:N], always, unless-stopped.
  15. Compose: depends_on only orders startup unless you use condition: service_healthy with a healthcheck. Services on the same Compose network reach each other by service name.
  16. Hardening: run as non-root USER, --read-only, --cap-drop ALL, no-new-privileges, scan images (Docker Scout, Trivy), never mount /var/run/docker.sock into untrusted containers.

Container fundamentals

Containers vs virtual machines

Containers share the host kernel and isolate processes; VMs virtualise hardware and run their own kernel.

  • A container packages an app with its libraries and runs it as an isolated process on the host kernel. It starts in milliseconds and uses MBs.
  • A virtual machine runs a full guest OS on a hypervisor (KVM, Hyper-V, ESXi). It boots in seconds to minutes and uses GBs.
  • Containers give weaker isolation: a kernel bug can affect every container on the host. VMs have a much smaller shared attack surface.
  • Linux containers need a Linux kernel. Docker Desktop on macOS and Windows runs a small Linux VM behind the scenes.
  • In practice they are combined: cloud VMs run container hosts, and sandboxes like gVisor or Kata Containers add VM-like isolation to containers.

Interview questions

  • What is the difference between a container and a virtual machine?
  • Can you run a Windows container on a Linux host?
  • When would you still choose a VM over a container?

How containers work: namespaces, cgroups, overlayfs

Namespaces limit what a process can see, cgroups limit what it can use, and a union filesystem gives it a layered root filesystem.

  • Namespaces give a process its own view of a resource: pid (process tree, app is PID 1), net (interfaces, ports), mnt (mounts), uts (hostname), ipc, user (UID mapping) and cgroup.
  • cgroups (control groups) cap and account for CPU, memory, PIDs and block I/O. --memory and --cpus become cgroup settings. Modern distros use cgroup v2.
  • A union filesystem (Docker's default storage driver is overlay2) stacks the read-only image layers and adds one writable layer per container.
  • Copy-on-write: reading a file comes from the lower layer. The first write copies the file up into the writable layer. Deleting adds a whiteout file that hides the lower copy.
  • Extra guard rails: capabilities split root's power into pieces, seccomp filters syscalls, and AppArmor or SELinux add mandatory access control.

Interview questions

  • What are namespaces and cgroups?
  • What is copy-on-write in Docker's storage?
  • Why does ps inside a container show the app as PID 1?
  • How would you build a container without Docker?

Docker architecture & OCI

The CLI talks to the dockerd daemon, which uses containerd to manage containers and runc to create them; images come from registries.

  • Docker CLI (docker) is a client. It sends REST calls to the daemon over a Unix socket (/var/run/docker.sock) or TCP.
  • dockerd (Docker Engine) handles the API, image builds (via BuildKit), networks, volumes and talks to containerd.
  • containerd is a CNCF runtime that manages the container lifecycle, image pull and storage. Kubernetes can use it directly through CRI.
  • runc is the low-level OCI runtime. It sets up namespaces and cgroups, starts the process and exits. A small containerd-shim stays as the parent, so containers survive a daemon restart.
  • A registry (Docker Hub, GHCR, ECR, GCR/Artifact Registry, Harbor) stores and serves images through the OCI distribution API.
  • OCI (Open Container Initiative) defines three specs: image format, runtime (how to run a bundle) and distribution (registry API). That is why images built by Docker run on Podman, containerd and Kubernetes.

Interview questions

  • Explain Docker's architecture.
  • What is OCI and why does it matter?
  • Kubernetes dropped Docker support. Do Docker images still work?

Images vs containers

An image is a read-only template; a container is a runnable instance of it with its own writable layer and state.

  • An image is an ordered list of read-only layers plus a config (default command, env, user, exposed ports, labels). It is identified by a content digest.
  • A container = image layers + a thin writable layer + runtime config (name, ports, mounts, env) + a process.
  • One image can back many containers. Each container's changes stay in its own layer and vanish when the container is removed with docker rm.
  • Container states: created → running → paused → stopped (exited) → removed.
  • docker commit turns a container into an image, but it is not reproducible. Always build from a Dockerfile.

Interview questions

  • What is the difference between an image and a container?
  • If you change a file inside a running container, does the image change?
  • Why should you avoid docker commit?

Images & Dockerfiles

Dockerfile instructions

A Dockerfile is a list of steps; know what each instruction does, which create layers, and the classic pairs COPY/ADD and ENV/ARG.

  • FROM picks the base image and starts a stage. RUN runs a command at build time. COPY copies files from the build context. WORKDIR sets (and creates) the working directory.
  • CMD and ENTRYPOINT define what runs at container start. USER sets the user for later steps and runtime. EXPOSE documents a port; it does not publish it.
  • COPY vs ADD: COPY only copies local files. ADD can also fetch a URL and auto-extracts local tar archives. Prefer COPY unless you need those features.
  • ENV vs ARG: ARG is a build-time variable (--build-arg) gone at runtime. ENV persists into the image and every container. An ARG declared before FROM is only usable in FROM lines.
  • HEALTHCHECK tells Docker how to test the app; status shows as healthy/unhealthy. VOLUME marks a path as a mount point and creates an anonymous volume if none is given.
  • LABEL adds metadata, STOPSIGNAL changes the stop signal, SHELL changes the default shell for shell-form commands.

Interview questions

  • What is the difference between COPY and ADD?
  • What is the difference between ARG and ENV?
  • Does EXPOSE publish a port?
  • What does HEALTHCHECK do?

Layers, build cache & instruction order

Order the Dockerfile from least to most frequently changing so the cache is reused and builds stay fast.

  • RUN, COPY and ADD add filesystem layers. Other instructions (ENV, CMD, LABEL, ...) only change image metadata.
  • The cache key for a step is the parent layer plus the instruction. For COPY/ADD it also includes a checksum of the copied files.
  • Once a step misses the cache, every following step is rebuilt. So put rarely changing steps (base image, OS packages, dependency install) first and COPY . . near the end.
  • RUN cache is based on the command text only. RUN apt-get update may reuse a stale cached layer; combine it with apt-get install in the same RUN.
  • Files deleted in a later layer still take space in the earlier layer. Clean up in the same RUN that created the files.
  • Use --no-cache to rebuild everything, --pull to refresh the base image, and BuildKit cache mounts to keep package caches between builds.

Interview questions

  • How does Docker's build cache work?
  • How would you speed up a slow Docker build?
  • Why should apt-get update and apt-get install be in the same RUN?

CMD vs ENTRYPOINT, shell vs exec form

ENTRYPOINT is the fixed executable, CMD is the default (overridable) command or arguments, and exec form keeps your app as PID 1.

  • Exec form ["node", "app.js"] runs the binary directly. No shell, no variable expansion, and the app is PID 1 so it receives signals.
  • Shell form node app.js runs /bin/sh -c "node app.js". The shell is PID 1 and usually does not forward SIGTERM, so docker stop waits 10 s and kills.
  • Only CMD: docker run img other-cmd replaces the whole command.
  • ENTRYPOINT + CMD: CMD becomes default arguments to ENTRYPOINT. docker run img --flag replaces only the arguments. --entrypoint overrides the executable.
  • Only the last CMD and the last ENTRYPOINT in a Dockerfile take effect.
  • Entrypoint scripts should end with exec "$@" so the final app replaces the shell and becomes PID 1.

Interview questions

  • What is the difference between CMD and ENTRYPOINT?
  • What is the difference between shell form and exec form?
  • Why does docker stop take 10 seconds for my container?

Multi-stage builds

Use one stage to build and another minimal stage to run, copying only the final artifact across.

  • Each FROM starts a new stage. Name stages with AS build and copy from them with COPY --from=build.
  • The final image contains only the last stage (or the one picked with --target). Compilers, dev dependencies and source code stay behind.
  • Benefits: much smaller images, smaller attack surface, and no build secrets or tools leaking into production.
  • docker build --target test . builds an intermediate stage, which is handy for running tests or a dev image from the same Dockerfile.
  • With BuildKit, stages that do not depend on each other build in parallel, and stages not needed by the target are skipped.
  • COPY --from can also copy from any image, for example COPY --from=busybox:1.36 /bin/busybox /busybox.

Interview questions

  • What is a multi-stage build and why use it?
  • How do you run tests as part of a Docker build without shipping them?
  • Your multi-stage image fails at runtime with “no such file or directory” for a binary that clearly exists. Why?

.dockerignore & reducing image size

Send less context, pick a minimal base, clean up in the same layer and ship only runtime files.

  • .dockerignore excludes files from the build context: .git, node_modules, build output, logs, .env and secrets. It speeds up builds, keeps caches stable and stops secrets leaking into images.
  • Pick a smaller base: -slim (Debian minus extras), Alpine (musl, ~5 MB), distroless (no shell or package manager), or scratch (empty).
  • Combine install and cleanup in one RUN: apt-get install --no-install-recommends ... && rm -rf /var/lib/apt/lists/*.
  • Install only production dependencies (npm ci --omit=dev, pip --no-cache-dir) and use multi-stage builds.
  • Inspect size with docker history, docker image ls, or the dive tool to see which layer is large.

Interview questions

  • How do you reduce Docker image size?
  • What is the build context and what does .dockerignore do?
  • Alpine or distroless: which would you pick?

BuildKit, buildx & multi-platform builds

BuildKit is the modern build engine: parallel stages, cache and secret mounts, remote cache, and multi-arch images via buildx.

  • BuildKit is the default builder since Docker Engine 23.0. It builds a dependency graph, runs stages in parallel and skips unused ones.
  • Start Dockerfiles with # syntax=docker/dockerfile:1 to get the latest stable Dockerfile features.
  • Cache mounts RUN --mount=type=cache,target=/root/.cache/pip keep package caches across builds without putting them in a layer.
  • Secret mounts RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci expose a secret only for that step; it never lands in a layer or history. SSH agent forwarding uses --mount=type=ssh.
  • buildx is the CLI plugin for BuildKit. It manages builders (docker buildx create) and builds multi-platform images with --platform linux/amd64,linux/arm64.
  • A multi-platform image is an image index (manifest list) pointing to one image per architecture. The client pulls the one that matches its platform.
  • Cross-platform builds use QEMU emulation (slow) or cross-compilation with the automatic BUILDPLATFORM/TARGETOS/TARGETARCH build args (fast).

Interview questions

  • What is BuildKit and what does it improve?
  • How do you use a secret (like an npm token) during a build without leaking it?
  • How do you build an image for both amd64 and arm64?
  • What causes exec format error when a container starts?

Tags, registries & digests

An image reference is registry/namespace/repo:tag@digest; tags are mutable labels, digests are immutable content hashes.

  • Full reference: registry.example.com:5000/team/app:1.4.2@sha256:.... With no registry it means Docker Hub (docker.io); with no tag it means :latest.
  • latest is just a default tag name, not “newest”. It moves only when someone pushes it.
  • A digest (sha256:...) is the hash of the image manifest. Same digest = byte-identical image. Pin by digest for reproducible builds and deploys.
  • Tagging strategy: immutable version tags (1.4.2), plus the git SHA, plus floating tags (1.4, 1) for convenience.
  • Workflow: docker login, docker tag local repo/app:1.4.2, docker push. Pull with docker pull.
  • Registries: Docker Hub (has pull rate limits for anonymous and free users), GHCR, Amazon ECR, Google Artifact Registry, Azure ACR, self-hosted Harbor or registry:2.

Interview questions

  • What is the difference between a tag and a digest?
  • Why is using :latest in production a bad idea?
  • How would you design an image tagging strategy for CI/CD?

Running containers

Container lifecycle & core commands

Know docker run's main flags and how to exec, inspect, read logs, stop and clean up.

  • docker run = create + start. Key flags: -d (detached), -it (interactive TTY), --name, -p host:container, -v/--mount, -e KEY=val/--env-file, --rm (delete on exit), --network, --restart.
  • docker exec -it <c> sh runs a new process in a running container. docker attach connects to the main process's stdio.
  • docker logs -f --tail 100 <c> shows stdout/stderr. docker inspect <c> returns full JSON (IP, mounts, env, state, exit code).
  • docker stop sends SIGTERM, waits (default 10 s, change with -t), then SIGKILL. docker kill sends SIGKILL right away (or -s another signal).
  • docker ps -a, docker start/restart, docker rm, docker cp, docker stats, docker top, and docker system prune cover daily use.

Interview questions

  • What is the difference between docker stop and docker kill?
  • What is the difference between docker exec and docker attach?
  • A container exits right after docker run -d. How do you investigate?
  • What does --rm do?

Restart policies & resource limits

Restart policies decide when Docker restarts a container; cgroup limits cap memory, CPU and PIDs so one container cannot starve the host.

  • Restart policies: no (default), on-failure[:max-retries] (non-zero exit only), always, unless-stopped.
  • always restarts even after a manual stop once the daemon restarts. unless-stopped stays stopped if you stopped it yourself.
  • Docker uses an increasing back-off delay between restarts, and a policy only applies after a container has run successfully for at least 10 seconds.
  • --memory 512m sets a hard limit; above it the kernel OOM-kills the process (exit 137, OOMKilled: true). --memory-swap controls swap.
  • --cpus 1.5 caps CPU time (CFS quota). --cpu-shares is a relative weight used only under contention. --pids-limit stops fork bombs.
  • Change limits on a running container with docker update. Watch usage with docker stats.

Interview questions

  • What is the difference between always and unless-stopped?
  • A container keeps exiting with code 137. What is happening?
  • What happens if you do not set any resource limits?

Volumes, bind mounts & tmpfs

Container layers are ephemeral; persist data in named volumes, share host files with bind mounts, and keep sensitive scratch data in tmpfs.

  • Named volume (-v pgdata:/var/lib/postgresql/data): created and managed by Docker under /var/lib/docker/volumes. Portable, backup-friendly, best for databases.
  • Bind mount (-v $(pwd):/app): mounts an exact host path. Great for live-reload in development, but depends on host layout and permissions.
  • tmpfs (--tmpfs /tmp): stored in memory only, gone when the container stops. Good for secrets and scratch files, and with --read-only root filesystems.
  • --mount type=...,source=...,target=... is the explicit syntax. Unlike -v, it errors if a bind source path does not exist instead of creating a directory.
  • An empty named volume is pre-populated with the image's files at that path the first time. A bind mount hides whatever the image had there.
  • Volumes outlive containers. docker rm -v or docker volume prune removes them; docker compose down -v removes the project's volumes.

Interview questions

  • What is the difference between a volume and a bind mount?
  • How do you persist data for a database container?
  • When would you use tmpfs?

Networking & port publishing

Containers get their own network namespace; drivers decide how they connect, and user-defined bridges give built-in DNS by container name.

  • bridge (default): containers join the docker0 bridge and get private IPs. NAT is used for outbound traffic; -p adds port forwarding for inbound.
  • User-defined bridge (docker network create appnet): adds automatic DNS so containers reach each other by name, plus better isolation. The default bridge has no name resolution.
  • host: shares the host's network stack. No NAT, no port mapping, best performance, no isolation. -p is ignored.
  • none: only loopback. overlay: spans multiple Docker hosts (Swarm). macvlan/ipvlan: give a container its own address on the physical LAN.
  • -p 8080:80 maps host port 8080 to container port 80; -p 127.0.0.1:8080:80 binds only to localhost; -P maps all EXPOSEd ports to random host ports.
  • Container-to-container traffic on the same network uses the container port directly (http://db:5432), not the published host port.

Interview questions

  • How do two containers talk to each other?
  • Why can't containers on the default bridge resolve each other by name?
  • What is the difference between bridge and host networking?
  • I published -p 8080:3000 but get “connection refused”. What do you check?

Docker Compose

Docker Compose

Compose describes a multi-container app in one YAML file and runs it with docker compose up.

  • A compose.yaml defines services (containers), networks and volumes. Compose v2 is the docker compose plugin; the top-level version: key is obsolete.
  • Every project gets a default network, so services reach each other by service name.
  • depends_on controls start order only. To wait until a dependency is ready, add a healthcheck to it and use condition: service_healthy (or service_completed_successfully for one-off jobs like migrations).
  • .env vs env_file: the .env file next to the Compose file is used for ${VAR} interpolation in the YAML. env_file: and environment: set variables inside the container.
  • Profiles mark optional services (profiles: [debug]); they start only with --profile debug. Override files (compose.override.yaml) are merged automatically for dev tweaks.
  • Daily commands: up -d --build, down (-v also removes volumes), ps, logs -f svc, exec svc sh, config (prints the merged, resolved file), watch (sync code changes in dev).

Interview questions

  • What is Docker Compose used for?
  • Does depends_on wait for the database to be ready?
  • What is the difference between .env and env_file in Compose?
  • How do you run some services only in certain situations?
  • Compose vs Kubernetes: when do you use which?

Production & operations

Container security

Reduce what an attacker gets: non-root user, minimal image, dropped capabilities, read-only filesystem, scanned images and real secrets handling.

  • Run as non-root: create a user and set USER app (or a numeric UID). Root in a container is root on the host if it escapes and user namespaces are not used.
  • Drop capabilities: --cap-drop ALL --cap-add NET_BIND_SERVICE. Avoid --privileged; it disables almost all isolation.
  • Read-only root filesystem: --read-only plus --tmpfs /tmp for writable scratch. Add --security-opt no-new-privileges to block setuid escalation.
  • Secrets: never in ENV, ARG or image layers. Use BuildKit secret mounts at build time and Compose/Swarm secrets, Kubernetes secrets or a vault at runtime.
  • Scan images for CVEs (Docker Scout, Trivy, Grype), use minimal or distroless bases, pin by digest, rebuild often for patches, and sign images (Cosign, Notation).
  • Rootless mode runs dockerd itself without root. User namespace remapping (userns-remap) maps container root to an unprivileged host UID. Seccomp and AppArmor/SELinux profiles are on by default.

Interview questions

  • How do you secure a Docker container?
  • Why is running as root inside a container dangerous if it is isolated?
  • Why is mounting /var/run/docker.sock risky?
  • What is rootless Docker?

PID 1, signals & graceful shutdown

The container's main process is PID 1: it must handle SIGTERM itself and reap zombie children, or you need an init like tini.

  • The Linux kernel gives PID 1 no default signal handlers. If your app does not install a SIGTERM handler, SIGTERM is ignored and Docker falls back to SIGKILL after the timeout.
  • PID 1 must also reap zombies: orphaned child processes get re-parented to it, and if it never calls wait() they pile up as zombies.
  • Shell form or a wrapper script without exec makes sh PID 1. The shell typically does not forward signals to your app.
  • tini (or docker run --init, which injects Docker's bundled tini) is a tiny init that forwards signals to the child and reaps zombies.
  • Graceful shutdown: on SIGTERM stop accepting new work, finish in-flight requests, close DB connections, then exit 0 within the grace period (docker stop -t, Compose stop_grace_period, Kubernetes terminationGracePeriodSeconds).
  • STOPSIGNAL changes the signal used by docker stop (for example SIGQUIT for nginx's graceful shutdown).

Interview questions

  • Why is PID 1 special in a container?
  • What is tini and when do you need it?
  • How do you make a containerised service shut down gracefully?

Logging drivers & debugging containers

Log to stdout/stderr and let a logging driver ship it; debug with logs, inspect, exec, events, stats and sidecar debug containers.

  • Apps should write logs to stdout/stderr, not files. Docker captures them and passes them to the configured logging driver.
  • Default driver is json-file, which does not rotate by default. Set max-size and max-file (per container or in daemon.json), or use the local driver, which rotates and compresses.
  • Other drivers: journald, syslog, fluentd, gelf, awslogs, gcplogs, splunk, none. Newer engines keep a local cache so docker logs still works with remote drivers.
  • Debug toolkit: docker logs, docker inspect, docker exec, docker events (daemon event stream), docker stats, docker top, docker diff, docker cp.
  • For minimal images with no shell, attach a debug container that shares the target's namespaces: --network container:<name> and --pid container:<name> with a toolbox image like nicolaka/netshoot or busybox.

Interview questions

  • How does logging work in Docker?
  • How do you debug a container that has no shell (distroless)?
  • The Docker host's disk filled up. What do you look at?

Docker vs Podman & best-practices checklist

Podman is a daemonless, rootless-first, Docker-compatible engine; the checklist sums up how to build and run images well with either.

  • Podman has no central daemon: each container is a child of conmon launched by the CLI. It is rootless by default and uses the same OCI images and registries.
  • Its CLI mirrors Docker's (alias docker=podman mostly works). It adds pods (shared network namespace like Kubernetes), podman kube generate/play, and systemd integration via Quadlet files.
  • Builds use Buildah under the hood; Podman reads Containerfile or Dockerfile. podman compose or podman-compose handles Compose files.
  • Docker's strengths: Docker Desktop, BuildKit/buildx, Compose and the largest ecosystem. Podman's: no root daemon, systemd-native, Red Hat default.
  • Checklist: small pinned base, multi-stage, .dockerignore, deps before source, one process per container, non-root, exec-form CMD, healthcheck, logs to stdout, config via env, no secrets in image, resource limits, scanned and versioned images.

Interview questions

  • What is the difference between Docker and Podman?
  • What are your Docker best practices for a production image?
  • Why “one process per container”?