Docker Interview Questions and Answers
Last updated 2026-11-19
Docker questions test whether you understand what a container really is, not just whether you can run docker run. Strong answers explain namespaces and cgroups, why layer order changes build time, how networking and volumes behave, and what makes an image safe to ship. This page has 16 worked questions with Dockerfiles and commands you can type into a terminal to verify each claim.
The questions are ordered from basics to production concerns. If you are preparing for a wider role, pair this page with the Kubernetes questions and the DevOps questions.
| Core concepts | Images, containers, layers, registries, volumes, networks, Compose |
|---|---|
| Kernel features | Namespaces for isolation, cgroups for resource limits, union filesystems |
| Commonly asked | Multi-stage Dockerfile, CMD vs ENTRYPOINT, reducing image size, debugging a crashing container |
What interviewers look for
Expect to be asked to write or review a Dockerfile live. The reviewer checks four things: a small pinned base image, cache-friendly instruction order, a non-root user, and a sensible start command in exec form. Memorise the pattern in the multi-stage question below and you will cover most practical rounds.
Also be ready for why-questions. Why does a container exit immediately? Why is my image 1.2 GB? Why can't two containers talk by localhost? Each has a short mechanical answer that shows real understanding.
Docker Interview Questions and Answers: questions with worked answers
1 What is the difference between an image and a container, and how does a container differ from a virtual machine?
easyAn image is a read-only, layered template containing a filesystem and metadata such as the default command. A container is a running (or stopped) instance of an image with a thin writable layer on top. A VM virtualises hardware and runs a full guest operating system with its own kernel; a container is an ordinary process on the host kernel, isolated using Linux namespaces (pid, net, mnt, uts, ipc, user) and limited using cgroups. That is why containers start in milliseconds and use far less memory, but share the host kernel, so isolation is weaker than a VM. On Windows and macOS, Docker Desktop runs a lightweight Linux VM to provide that kernel.
2 Explain image layers and how the build cache works.
mediumEach Dockerfile instruction that changes the filesystem (RUN, COPY, ADD) creates a layer. Layers are content-addressed and shared between images, so pulling a second image with the same base downloads only the differing layers. During a build, Docker reuses a cached layer if the instruction and its inputs are unchanged, but once one layer is invalidated, every later layer rebuilds. So order instructions from least to most frequently changing: copy only the dependency manifest, install dependencies, then copy the source. Otherwise a one-line code edit reinstalls every dependency. Inspect layers with docker history.
dockerfileFROM python:3.12-slim WORKDIR /app # dependencies change rarely: cache this layer COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # source changes often: keep it last COPY . . CMD ["python", "app.py"]3 What is the difference between CMD and ENTRYPOINT, and between shell and exec form?
easyENTRYPOINT defines the executable that always runs; CMD supplies default arguments to it, or the default command when there is no ENTRYPOINT. Arguments passed to docker run replace CMD but are appended to ENTRYPOINT. Exec form (a JSON array) runs the process directly as PID 1, so it receives signals such as SIGTERM from docker stop and can shut down gracefully. Shell form (a plain string) wraps the command in /bin/sh -c, so the shell is PID 1 and often swallows signals, causing a 10-second delay then SIGKILL. Always use exec form for the main process.
dockerfileFROM alpine:3.20 ENTRYPOINT ["ping"] CMD ["-c", "3", "localhost"] # docker run img -> ping -c 3 localhost # docker run img -c 1 8.8.8.8 -> ping -c 1 8.8.8.84 What is the difference between COPY and ADD?
easyCOPY copies files or directories from the build context into the image and nothing more. ADD does the same but also auto-extracts local tar archives and can fetch remote URLs. Because those extras are surprising (a remote URL changes without your cache noticing and unverified downloads are a supply-chain risk), the guidance is to use COPY by default and ADD only when you specifically want tar auto-extraction. For downloading files, use RUN curl with a checksum verification instead.
5 Write a multi-stage Dockerfile for a Java Spring Boot application. Why use multi-stage builds?
mediumA multi-stage build compiles in one stage that contains the full JDK and Maven, then copies only the finished artefact into a small runtime stage. The final image has no compiler, build cache or source code, so it is smaller and has a smaller attack surface. Naming stages lets you also build a test or debug target. The example uses a JRE-only runtime image and runs as a non-root user.
dockerfileFROM maven:3.9-eclipse-temurin-21 AS build WORKDIR /src COPY pom.xml . RUN mvn -q -B dependency:go-offline COPY src ./src RUN mvn -q -B package -DskipTests FROM eclipse-temurin:21-jre RUN useradd --system --uid 10001 app WORKDIR /app COPY --from=build /src/target/*.jar app.jar USER app EXPOSE 8080 ENTRYPOINT ["java", "-jar", "app.jar"]6 How would you reduce the size of a Docker image?
mediumStart from a smaller base such as slim, alpine or distroless; be aware that Alpine uses musl libc, which occasionally breaks native Python or Node modules. Use multi-stage builds so toolchains do not ship. Combine related RUN steps and clean package caches in the same layer, for example apt-get install --no-install-recommends followed by rm -rf /var/lib/apt/lists/*, because deleting in a later layer does not shrink earlier ones. Add a .dockerignore to keep node_modules, .git and logs out of the build context. Install only production dependencies. Use docker image ls and a tool such as dive to see which layers are large.
7 What are Docker's network drivers, and how do containers talk to each other?
mediumThe bridge driver is the default: containers on a bridge get private IPs and reach the outside through NAT. On a user-defined bridge network, containers resolve each other by name through Docker's embedded DNS, which the default bridge does not provide. The host driver removes network isolation and uses the host's network stack directly. None disables networking. Overlay networks span multiple Docker hosts in Swarm. Containers in the same Compose project share a network automatically, so the app reaches the database at hostname db, never localhost, because localhost inside a container is the container itself. Publish ports with -p host:container to expose a service externally.
bashdocker network create appnet docker run -d --name db --network appnet -e POSTGRES_PASSWORD=secret postgres:16 docker run --rm --network appnet postgres:16 pg_isready -h db8 Volumes versus bind mounts versus tmpfs: when do you use each?
easyA named volume is managed by Docker under its own storage area, survives container removal and is the right choice for databases and other persistent data. A bind mount maps a specific host path into the container, ideal for development where you edit source on the host and see changes inside; it depends on host directory layout and permissions. A tmpfs mount lives in memory only and is discarded when the container stops, useful for sensitive scratch data. The container's writable layer is deleted with the container, so anything you want to keep must be on a volume or mount.
bashdocker volume create pgdata docker run -d --name pg -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:16 docker run --rm -v "$PWD":/work -w /work alpine ls docker run --rm --tmpfs /scratch:rw,size=64m alpine df -h /scratch9 Write a Docker Compose file for a web app with a Postgres database and explain depends_on.
mediumCompose describes a multi-container application declaratively. Services share a default network and reach each other by service name. Plain depends_on only controls start order, not readiness, so the app may start before Postgres accepts connections. Add a healthcheck to the database and use depends_on with condition service_healthy so the app waits for a real ready signal. Named volumes at the bottom persist data. Start with docker compose up -d, and tear down with docker compose down, adding -v to delete volumes.
yamlservices: web: build: . ports: - "8080:8080" environment: DATABASE_URL: postgres://app:secret@db:5432/app depends_on: db: condition: service_healthy db: image: postgres:16 environment: POSTGRES_USER: app POSTGRES_PASSWORD: secret POSTGRES_DB: app volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U app -d app"] interval: 5s timeout: 3s retries: 10 volumes: pgdata:10 A container exits immediately after starting. How do you debug it?
mediumA container lives only as long as its main process (PID 1). Start with docker ps -a to see the exit code, then docker logs for output. Exit code 0 means the command simply finished, 1 is an application error, 137 means SIGKILL (often out-of-memory; confirm with docker inspect and the OOMKilled field), and 139 is a segfault. Common causes are a command that daemonises into the background so PID 1 returns, a missing environment variable or config, or wrong ENTRYPOINT arguments. To explore, override the entrypoint with docker run -it --entrypoint sh image, or use docker exec into a running container.
bashdocker ps -a --format 'table {{.Names}}\t{{.Status}}' docker logs --tail 50 myapp docker inspect myapp --format '{{.State.ExitCode}} {{.State.OOMKilled}}' docker run -it --rm --entrypoint sh myimage11 How do you limit CPU and memory for a container?
mediumDocker uses cgroups for limits. The --memory flag sets a hard cap; exceeding it makes the kernel OOM-kill the process. --memory-swap controls swap, and setting it equal to memory disables swap. For CPU, --cpus=1.5 limits to one and a half cores of time, while --cpu-shares gives relative weight only under contention. Without limits a runaway container can starve the host. In Kubernetes the same ideas appear as resource requests and limits. Applications such as the JVM should be container-aware so they size heaps from the cgroup limit; modern JVMs do this by default.
bashdocker run -d --name api --memory=512m --memory-swap=512m --cpus=1.5 myimage docker stats --no-stream api12 How do you make a Docker image more secure?
hardRun as a non-root user with a USER instruction, since root in a container is a bigger problem if escaped. Use minimal, pinned base images, ideally by digest, and rebuild regularly to pick up patches. Scan images in CI with Trivy or Grype. Keep secrets out of images: ENV and ARG values are visible through docker history, so use BuildKit secret mounts at build time and runtime secret injection otherwise. Drop capabilities with --cap-drop=ALL, add back only what is needed, use a read-only root filesystem with --read-only, and avoid --privileged and mounting the Docker socket. Sign images and verify provenance if your registry supports it.
bashdocker run -d --read-only --cap-drop=ALL --security-opt=no-new-privileges --user 10001:10001 --tmpfs /tmp myimage trivy image --severity HIGH,CRITICAL myimage:latest13 Why shouldn't you use the latest tag in production?
easyThe latest tag is a mutable default, not a statement about recency. It points to whatever was last pushed without an explicit tag, so two hosts pulling it at different times can run different code, rollbacks are ambiguous, and builds are not reproducible. Tag images with an immutable identifier such as the git commit SHA or a semantic version, and for base images pin a version, or a digest like python@sha256:... for strict reproducibility. Kubernetes pulls latest with imagePullPolicy Always by default, which compounds the surprise.
14 What does docker build send as the build context, and why does .dockerignore matter?
easyThe build sends the whole context directory (the path you pass, often a dot) to the builder. Large contexts slow every build, and anything copied with COPY . . ends up in the image, including .git, local .env files and node_modules. A .dockerignore file excludes patterns from the context just as .gitignore does for Git, which speeds builds, keeps secrets out and prevents cache invalidation from irrelevant file changes.
text.git node_modules *.log .env dist Dockerfile .dockerignore15 How does a container handle signals and zombie processes as PID 1?
hardPID 1 in a Linux namespace has special rules: the kernel does not apply default signal handlers to it, so a process that does not register a SIGTERM handler ignores docker stop and is killed after the timeout. PID 1 is also responsible for reaping orphaned children, and an application that does not do this leaves zombies. Use exec form so your app is PID 1 and handles signals, or add a tiny init process with docker run --init (which uses tini) or ENTRYPOINT of tini. Shell wrappers that do not use exec are a classic cause of slow shutdowns.
16 What is the difference between docker stop and docker kill, and between docker rm and docker rmi?
easydocker stop sends SIGTERM, waits for a grace period (10 seconds by default, changeable with --time), then sends SIGKILL; docker kill sends SIGKILL immediately, or another signal with -s. docker rm removes a container, including its writable layer unless data is on a volume; docker rmi removes an image, and fails while a container still references it. docker system prune clears stopped containers, dangling images and unused networks, and adding -a also removes unused images, so use it carefully on shared hosts.
17 How do ARG and ENV differ, and how do you pass build-time secrets safely?
hardARG exists only during the build and can be set with --build-arg; ENV persists into the running container as an environment variable. Neither is safe for secrets, because both can be recovered from image history or the container's environment. For secrets needed only at build, such as a private registry token, use a BuildKit secret mount: the secret is available at a temporary path during one RUN step and never stored in a layer.
dockerfile# syntax=docker/dockerfile:1 FROM node:22-slim WORKDIR /app COPY package*.json ./ RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci --omit=dev COPY . . CMD ["node", "server.js"] # build: docker build --secret id=npmrc,src=$HOME/.npmrc -t app .
Frequently asked questions
Is Docker still relevant now that Kubernetes is everywhere?
Yes. Kubernetes runs OCI containers, and most teams still build images with Docker or BuildKit and test locally with Docker or Compose. Kubernetes itself uses containerd or CRI-O as its runtime, but the image format and Dockerfile skills carry over directly.
Do I need to know Docker Swarm for interviews?
Rarely. Know that Swarm is Docker's built-in orchestrator with services, overlay networks and stacks, and that most employers use Kubernetes. A one-line comparison is usually enough.
What is the difference between Docker and containerd?
containerd is the container runtime that manages image pulls, storage and container lifecycle, and it is what Docker Engine uses underneath. Docker adds the CLI, the build tooling and developer-friendly features on top.
How can I practise Dockerfile questions without a cloud account?
Install Docker Engine or Docker Desktop locally, containerise a small app in each language you know, then optimise it with multi-stage builds and compare image sizes with docker image ls. Free browser playgrounds exist too.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Ethical Hacking Interview Questions and Answers
- ETL and Data Warehousing Interview Questions and Answers
- Excel Interview Questions and Answers
- Express.js Interview Questions and Answers (Express 5)
- FastAPI Interview Questions and Answers
- Flask Interview Questions and Answers
- Flutter Interview Questions and Answers (Flutter 3, Dart 3)
- Frontend Developer Interview Questions and Answers
- Full Stack Developer Interview Questions and Answers
- Generative AI and LLM Interview Questions and Answers
- Google Cloud (GCP) Interview Questions and Answers
- GraphQL Interview Questions and Answers