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
- 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.
- 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.
- Each
RUN,COPYandADDmakes a layer. Layers are cached; a change invalidates that step and every step after it. Copy dependency manifests and install deps before copying source. - Stack:
dockerCLI → REST API → dockerd → containerd → runc (creates the process). Images and runtimes follow the OCI specs, so other tools (Podman, Kubernetes) can use them. CMDgives default arguments and is easy to override.ENTRYPOINTfixes the executable. Use the exec form (["node","app.js"]) so your app is PID 1 and getsSIGTERM.ARGexists only at build time.ENVis baked into the image and visible at runtime. Neither is safe for secrets; use BuildKit--mount=type=secret.- Prefer
COPY.ADDalso extracts local tar files and fetches URLs, which is surprising and less transparent. - Multi-stage builds: compile in a big builder stage, then
COPY --from=buildonly the artifact into a slim, distroless orscratchruntime stage. - Tags (
:1.4,:latest) are mutable pointers. A digest (@sha256:...) is the content hash and never changes. Pin digests for reproducible deploys. - Storage: named volumes (managed by Docker, best for data), bind mounts (host path, best for dev), tmpfs (memory only, never on disk).
- Networks: default
bridge, user-defined bridge (has DNS by container name),host(no isolation),none,overlay(multi-host, Swarm).-p 8080:80maps host 8080 to container 80;EXPOSEonly documents. docker stopsendsSIGTERM, waits 10 s, thenSIGKILL.docker killsendsSIGKILLat once. Exit code 137 = killed (often OOM), 143 = SIGTERM.- PID 1 gets no default signal handlers and must reap zombies. Use exec form,
execin shell scripts, ordocker run --init/ tini. - Restart policies:
no(default),on-failure[:N],always,unless-stopped. - Compose:
depends_ononly orders startup unless you usecondition: service_healthywith ahealthcheck. Services on the same Compose network reach each other by service name. - Hardening: run as non-root
USER,--read-only,--cap-drop ALL,no-new-privileges, scan images (Docker Scout, Trivy), never mount/var/run/docker.sockinto 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) andcgroup. - cgroups (control groups) cap and account for CPU, memory, PIDs and block I/O.
--memoryand--cpusbecome 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
psinside 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 committurns 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.
FROMpicks the base image and starts a stage.RUNruns a command at build time.COPYcopies files from the build context.WORKDIRsets (and creates) the working directory.CMDandENTRYPOINTdefine what runs at container start.USERsets the user for later steps and runtime.EXPOSEdocuments a port; it does not publish it.- COPY vs ADD:
COPYonly copies local files.ADDcan also fetch a URL and auto-extracts local tar archives. PreferCOPYunless you need those features. - ENV vs ARG:
ARGis a build-time variable (--build-arg) gone at runtime.ENVpersists into the image and every container. AnARGdeclared beforeFROMis only usable inFROMlines. HEALTHCHECKtells Docker how to test the app; status shows ashealthy/unhealthy.VOLUMEmarks a path as a mount point and creates an anonymous volume if none is given.LABELadds metadata,STOPSIGNALchanges the stop signal,SHELLchanges the default shell for shell-form commands.
Interview questions
- What is the difference between
COPYandADD? - What is the difference between
ARGandENV? - Does
EXPOSEpublish a port? - What does
HEALTHCHECKdo?
Layers, build cache & instruction order
Order the Dockerfile from least to most frequently changing so the cache is reused and builds stay fast.
RUN,COPYandADDadd 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/ADDit 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. RUNcache is based on the command text only.RUN apt-get updatemay reuse a stale cached layer; combine it withapt-get installin the sameRUN.- Files deleted in a later layer still take space in the earlier layer. Clean up in the same
RUNthat created the files. - Use
--no-cacheto rebuild everything,--pullto 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 updateandapt-get installbe in the sameRUN?
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.jsruns/bin/sh -c "node app.js". The shell is PID 1 and usually does not forwardSIGTERM, sodocker stopwaits 10 s and kills. - Only CMD:
docker run img other-cmdreplaces the whole command. - ENTRYPOINT + CMD: CMD becomes default arguments to ENTRYPOINT.
docker run img --flagreplaces only the arguments.--entrypointoverrides 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
CMDandENTRYPOINT? - What is the difference between shell form and exec form?
- Why does
docker stoptake 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
FROMstarts a new stage. Name stages withAS buildand copy from them withCOPY --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 --fromcan also copy from any image, for exampleCOPY --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.
.dockerignoreexcludes files from the build context:.git,node_modules, build output, logs,.envand 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), orscratch(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 thedivetool to see which layer is large.
Interview questions
- How do you reduce Docker image size?
- What is the build context and what does
.dockerignoredo? - 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:1to get the latest stable Dockerfile features. - Cache mounts
RUN --mount=type=cache,target=/root/.cache/pipkeep package caches across builds without putting them in a layer. - Secret mounts
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ciexpose 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/TARGETARCHbuild 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 errorwhen a container starts?
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> shruns a new process in a running container.docker attachconnects 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 stopsends SIGTERM, waits (default 10 s, change with-t), then SIGKILL.docker killsends SIGKILL right away (or-sanother signal).docker ps -a,docker start/restart,docker rm,docker cp,docker stats,docker top, anddocker system prunecover daily use.
Interview questions
- What is the difference between
docker stopanddocker kill? - What is the difference between
docker execanddocker attach? - A container exits right after
docker run -d. How do you investigate? - What does
--rmdo?
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. alwaysrestarts even after a manual stop once the daemon restarts.unless-stoppedstays 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 512msets a hard limit; above it the kernel OOM-kills the process (exit 137,OOMKilled: true).--memory-swapcontrols swap.--cpus 1.5caps CPU time (CFS quota).--cpu-sharesis a relative weight used only under contention.--pids-limitstops fork bombs.- Change limits on a running container with
docker update. Watch usage withdocker stats.
Interview questions
- What is the difference between
alwaysandunless-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-onlyroot 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 -vordocker volume pruneremoves them;docker compose down -vremoves 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
docker0bridge and get private IPs. NAT is used for outbound traffic;-padds 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.
-pis ignored. - none: only loopback. overlay: spans multiple Docker hosts (Swarm). macvlan/ipvlan: give a container its own address on the physical LAN.
-p 8080:80maps host port 8080 to container port 80;-p 127.0.0.1:8080:80binds only to localhost;-Pmaps allEXPOSEd 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:3000but 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.yamldefines services (containers), networks and volumes. Compose v2 is thedocker composeplugin; the top-levelversion:key is obsolete. - Every project gets a default network, so services reach each other by service name.
depends_oncontrols start order only. To wait until a dependency is ready, add ahealthcheckto it and usecondition: service_healthy(orservice_completed_successfullyfor one-off jobs like migrations)..envvsenv_file: the.envfile next to the Compose file is used for${VAR}interpolation in the YAML.env_file:andenvironment: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(-valso 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_onwait for the database to be ready? - What is the difference between
.envandenv_filein 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-onlyplus--tmpfs /tmpfor writable scratch. Add--security-opt no-new-privilegesto block setuid escalation. - Secrets: never in
ENV,ARGor 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.sockrisky? - 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
execmakesshPID 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, Composestop_grace_period, KubernetesterminationGracePeriodSeconds). STOPSIGNALchanges the signal used bydocker stop(for exampleSIGQUITfor 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. Setmax-sizeandmax-file(per container or indaemon.json), or use thelocaldriver, which rotates and compresses. - Other drivers:
journald,syslog,fluentd,gelf,awslogs,gcplogs,splunk,none. Newer engines keep a local cache sodocker logsstill 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 likenicolaka/netshootor 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
conmonlaunched by the CLI. It is rootless by default and uses the same OCI images and registries. - Its CLI mirrors Docker's (
alias docker=podmanmostly 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
ContainerfileorDockerfile.podman composeorpodman-composehandles 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”?