Interview Prep

Top 20 Docker Interview Questions and Answers (2026 Guide)

Prepare for Docker interview questions covering containerization vs VMs, Dockerfile optimization, multi-stage builds, networking, and volumes.

Anuj SainiSep 8, 202613 min read

Containerization is a prerequisite skill across modern software engineering, data platform development, and DevOps. In technical interviews, interviewers assess whether you understand container internals—such as Linux cgroups and copy-on-write image layers—or simply memorize CLI commands.

In this guide, alongside our Kubernetes interview questions and REST API interview questions, we break down the top 20 Docker interview questions, providing clear architectural explanations, Dockerfile templates, and command-line examples.


Mastering Docker Interview Questions: Essential Concepts

Interview questions evaluate whether you can build secure, lean, production-ready images and troubleshoot containerized microservices.


Pillar 1: Fundamental Docker Interview Questions

Question 1: How does a Docker Container differ from a Virtual Machine?

Feature / Criteria

Question 2: What Linux kernel features power Docker container isolation?

Answer: Docker relies on two core Linux kernel primitives:

  1. Namespaces: Provide isolated workspaces for processes. Key namespaces include:
    • pid: Process tree isolation.
    • net: Network interfaces and routing tables.
    • mnt: File system mount points.
    • ipc: Inter-process communication.
    • uts: Hostname and domain isolation.
    • user: User ID mappings.
  2. Control Groups (cgroups): Enforce hardware resource limits (CPU quotas, memory caps, I/O bandwidth, network priority) to prevent noisy neighbor problems.

Question 3: What is the Union File System (UnionFS) and Copy-on-Write (CoW)?

Answer: Docker images are built as a stack of read-only layers. The storage driver (typically overlay2) merges these layers into a single unified view. When a container runs, Docker adds a thin, writable container layer on top.

Under the Copy-on-Write (CoW) strategy, when a container attempts to modify an existing file from an underlying image layer, the file is copied up to the writable top layer before modification. The underlying image layer remains untouched and immutable, allowing multiple containers to share the identical base image safely.


Pillar 2: Dockerfile Engineering & Best Practices

Question 4: CMD vs ENTRYPOINT: What is the difference?

Answer: Both instructions define what executes when a container launches, but they differ in how they accept runtime arguments:

dockerfile
# Option A: ENTRYPOINT with CMD defaults
ENTRYPOINT ["python", "app.py"]
CMD ["--port", "8000"]
  • If executed as docker run my-app, it executes python app.py --port 8000.
  • If executed as docker run my-app --port 9000, the argument overrides CMD, running python app.py --port 9000.
Feature / Criteria

Question 5: What is a Multi-Stage Docker Build and why is it critical?

Answer: A multi-stage build uses multiple FROM statements in a single Dockerfile. You compile dependencies in an early builder stage and copy only the compiled binaries into a lean production image:

dockerfile
# STAGE 1: Build & install dependencies
FROM python:3.11-slim AS builder
WORKDIR /app
RUN apt-get update && apt-get install -y gcc libpq-dev
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
 
# STAGE 2: Final Minimal Production Runtime
FROM python:3.11-slim
WORKDIR /app
# Copy installed packages from builder
COPY --from=builder /root/.local /root/.local
COPY . /app
 
ENV PATH=/root/.local/bin:$PATH
USER 1001
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Benefits:

  • Reduces final image size from 1.2 GB down to ~150 MB.
  • Removes build compilers (gcc), headers, and git from the production image, significantly shrinking the CVE security attack surface.

Pillar 3: Docker Storage & Networking Interview Questions

Question 6: What are the differences between Volumes, Bind Mounts, and tmpfs?

Answer:

  • Volumes: Stored in a directory managed by Docker (/var/lib/docker/volumes/ on Linux). Safest, easiest to back up, and decouples data from host directory layouts.
  • Bind Mounts: Maps an arbitrary host path (e.g., /home/user/code:/app) directly into the container. Excellent for live-reloading during local development.
  • tmpfs Mounts: Stores data strictly in the host system's RAM. Never written to disk; used for temporary secrets or sensitive cache tokens.

Question 7: Explain Docker Network Drivers (Bridge, Host, None, Overlay).

Answer:

  • bridge (Default): Creates a private internal network bridge on the host (docker0). Containers obtain internal 172.x.x.x IPs and communicate with the outside world via NAT port mappings (-p 80:8000).
  • host: Removes network isolation between the container and Docker host. The container binds directly to host ports, delivering maximum throughput with zero NAT overhead.
  • none: Disables all networking for the container. Used for isolated batch processing jobs.
  • overlay: Connects multiple Docker daemons across different physical machines in Docker Swarm or distributed setups.

Check out our guide on Kubernetes Interview Questions for multi-node container orchestration and FastAPI Interview Questions for backend deployment.


Question 8: How does the Docker Build Cache work, and how do you optimize instruction order?

Answer: Docker builds images layer by layer. For each instruction in a Dockerfile, Docker checks whether an existing cached image layer can be reused:

  1. Cache Invalidation Rules:
    • For RUN, ENV, WORKDIR: Docker checks if the command string matches the cached layer.
    • For COPY and ADD: Docker computes checksums of the referenced files. If a single file checksum changes, that layer's cache and all subsequent layers are invalidated.
  2. Optimization Best Practice: Place infrequently changing instructions first and frequently changing source code last:
    dockerfile
    # GOOD: Cached until requirements.txt changes
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
     
    # Application code changes on every commit; placed at the bottom
    COPY . .
  3. Chaining Commands: Combine related commands into single RUN statements with && and clean up temporary caches (rm -rf /var/lib/apt/lists/*) in the same layer to keep images lean.

Question 9: What is the difference between EXPOSE and -p (or -P)?

Answer:

  • EXPOSE <port>: Purely documentary metadata inside the Dockerfile. It informs developers and orchestrators which ports the container intends to listen on at runtime. It does not publish the port to the host network.
  • -p <host_port>:<container_port>: Explicitly creates an iptables NAT port-forwarding rule on the host network, binding host traffic to the container port (e.g., -p 8080:80).
  • -P (Publish All): Automatically binds all ports listed under EXPOSE to random high-numbered ephemeral ports on the host.

Question 10: How do you enforce non-root execution inside a Docker container for security?

Answer: By default, processes in a container run as root (UID 0), creating severe security vulnerabilities if a container breakout vulnerability occurs:

dockerfile
FROM python:3.11-slim
 
# Create dedicated non-root user and group
RUN groupadd -r appuser && useradd -r -g appuser -u 1001 appuser
 
WORKDIR /app
COPY --chown=appuser:appuser . .
 
# Drop privileges to non-root user
USER 1001
 
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Enforcing USER 1001 ensures compliance with production Kubernetes security standards (runAsNonRoot: true).


Question 11: How do you inspect and clean up dangling images, unused volumes, and stopped containers?

Answer: Docker accumulates build artifacts that consume gigabytes of disk space:

  • Dangling Images: Images with tag <none>:<none> created when a newer image is built with the same tag.
    bash
    docker image prune -f
  • Unused Volumes: Volumes not attached to any running or stopped container. (Warning: verify backups before pruning):
    bash
    docker volume prune -f
  • Comprehensive Nuclear Clean:
    bash
    docker system prune -a --volumes -f
    Removes all stopped containers, all networks not used by at least one container, all dangling and unused images, and all build cache.

Question 12: What is the anatomy and role of a docker-compose.yml file?

Answer: Docker Compose coordinates multi-container environments (e.g., API server, PostgreSQL database, Redis cache, and frontend) using a single declarative configuration:

yaml
version: '3.8'
services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgres://postgres:secret@db:5432/analytics
    depends_on:
      db:
        condition: service_healthy
 
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: analytics
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
 
volumes:
  postgres_data:

Compose automatically creates a shared bridge network, enabling services to resolve each other by service name (db, web) via internal DNS.


Question 13: How do Docker Healthchecks work, and how do they differ from application uptime?

Answer: A container process can remain running (PID active) while being deadlocked, memory exhausted, or unable to connect to its database:

  • HEALTHCHECK Instruction:
    dockerfile
    HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3     CMD curl -f http://localhost:8000/health || exit 1
  • Lifecycle States:
    1. starting: Initial grace period (start-period) while the app boots.
    2. healthy: Healthcheck command returns exit code 0.
    3. unhealthy: Healthcheck command fails consecutively retries times.
  • Orchestration Integration: Docker swarm and Kubernetes monitor this state to route ingress traffic only to healthy instances and restart failing containers.

Question 14: What is the relationship between Docker Daemon (dockerd), containerd, and runc?

Answer: Modern container runtimes follow the Open Container Initiative (OCI) layered architecture:

  1. Docker CLI (docker): The user-facing command-line tool that communicates with the daemon via REST API over UNIX socket (/var/run/docker.sock).
  2. Docker Daemon (dockerd): Manages high-level features: image building, network configuration, volume management, and user authentication.
  3. containerd: A core, decoupled container runtime that manages the complete container lifecycle: image distribution, storage management, and container execution.
  4. runc: The lightweight OCI reference CLI wrapper that interfaces directly with the Linux kernel to configure cgroups, namespaces, and spawn the container process.

Question 15: What is a scratch base image and when is it used?

Answer: scratch is Docker's reserved empty, zero-byte base image:

  • Characteristics: Contains no operating system, no shell (/bin/sh), no standard C library, and no package manager.
  • Use Case: Packaging statically compiled self-contained binaries (written in Go, Rust, or C):
    dockerfile
    FROM golang:1.22 AS builder
    WORKDIR /src
    COPY . .
    RUN CGO_ENABLED=0 GOOS=linux go build -o /bin/api
     
    FROM scratch
    COPY --from=builder /bin/api /bin/api
    EXPOSE 8080
    ENTRYPOINT ["/bin/api"]
  • Benefits: Produces ultra-minimal 5MB images with zero Common Vulnerabilities and Exposures (CVEs) and minimal network transfer latency.

Question 16: How do you pass secrets securely into Docker builds without baking them into image layers?

Answer: Hardcoding API tokens or private SSH keys into ARG or ENV leaves credentials visible in image history via docker history <image>:

  • BuildKit Secret Mounts:
    dockerfile
    # syntax=docker/dockerfile:1.4
    FROM python:3.11-slim
    RUN --mount=type=secret,id=pip_token       PIP_EXTRA_INDEX_URL=$(cat /run/secrets/pip_token) pip install -r requirements.txt
  • CLI Execution:
    bash
    DOCKER_BUILDKIT=1 docker build --secret id=pip_token,src=./token.txt -t myapp .
  • Security Guarantee: The secret file is mounted as a temporary in-memory filesystem during the RUN command only and is never recorded into any layer of the resulting image.

Question 17: How do you debug a failing container that crashes immediately upon startup?

Answer: When a container exits with code 1, 127, or 137, standard interactive execution fails because the container stops instantly:

  1. Inspect Exit Code and Logs:
    bash
    docker ps -a
    docker logs --tail 100 <container_id>
    • Exit Code 137: SIGKILL, typically triggered by kernel Out-Of-Memory (OOM) killer.
    • Exit Code 127: File or command not found (e.g., missing shebang line or wrong path in ENTRYPOINT).
  2. Override Entrypoint with an Interactive Shell:
    bash
    docker run -it --entrypoint /bin/sh <image_name>
  3. Inspect Detailed JSON State:
    bash
    docker inspect <container_id> --format='{{.State.ExitCode}} {{.State.Error}}'

Question 18: What is the difference between docker stop and docker kill?

Answer:

  • docker stop <container> (Graceful Shutdown): Sends a SIGTERM signal to PID 1 inside the container. The application has a grace period (default 10 seconds) to flush buffers, finish in-flight database transactions, and close socket connections. If the process does not terminate within the grace period, Docker follows up with SIGKILL.
  • docker kill <container> (Immediate Termination): Sends SIGKILL directly (or a custom signal via --signal), instantly halting process execution at the kernel level without cleanup.

Question 19: How do you configure CPU and Memory resource limits on a container?

Answer: Without limits, a runaway container memory leak can cause the host Linux kernel to crash or kill vital operating system processes:

bash
docker run -d   --name web-app   --memory="1g"   --memory-swap="1.5g"   --cpus="2.0"   --restart=unless-stopped   nginx:alpine
  • --memory="1g": Restricts container memory allocation to 1 Gigabyte. Exceeding this triggers the cgroup OOM killer.
  • --cpus="2.0": Guarantees the container access to at most two CPU cores' worth of compute cycles per period.
  • Monitoring: Run docker stats to observe real-time CPU, memory, and I/O consumption across all running containers.

Question 20: What is the difference between COPY and ADD in a Dockerfile?

Answer: Senior DevOps and platform interviewers test your understanding of file copy semantics:

  • COPY: Copies local files and directories from the build context into the container filesystem. It is transparent, predictable, and strictly recommended by Docker official best practices for standard file operations.
  • ADD: Has two additional behaviors beyond COPY:
    1. Auto-extracts local tar archives into the destination directory (e.g., ADD archive.tar.gz /opt/).
    2. Downloads remote files from HTTP/HTTPS URLs (though downloading via curl/wget in a RUN step is preferred to allow cleanup in the same layer).
  • Rule of Thumb: Use COPY for 99% of file transfers; reserve ADD strictly for auto-extracting local tarballs.

Summary Checklist for Docker Interview Questions

  • Explain how Linux namespaces and cgroups differ from hypervisor virtualization.
  • Write a clean multi-stage Dockerfile that drops build tools from production layers.
  • Know when to use Docker Volumes vs Bind Mounts.
  • Differentiate between CMD and ENTRYPOINT with clear runtime examples.
  • Understand container security: never run as root, drop capabilities, and pin base image digests.

Practice Technical DevOps & Backend Coding

Master containerization, API development, and software architecture questions with interactive challenges on Topfolio.

Explore Interview Practice

Frequently Asked Questions

What are the most common Docker interview questions?

Common Docker questions cover the difference between containers and virtual machines, image layers and caching, CMD vs ENTRYPOINT, multi-stage Docker builds, volume persistence types, Docker Compose, and networking modes (bridge, host, none).

How do Docker containers differ from Virtual Machines (VMs)?

Virtual Machines virtualize the underlying hardware and run a complete guest OS with separate kernel overhead. Docker containers share the host Linux kernel and isolate processes using Linux namespaces and cgroups, making them lightweight, fast to start (milliseconds vs minutes), and resource-efficient.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

ENTRYPOINT defines the immutable executable command to run when the container starts. CMD provides default arguments to that executable, which can be easily overridden by passing arguments to 'docker run'. When used together, ENTRYPOINT acts as the base binary and CMD supplies default parameters.

What is a multi-stage Docker build and why is it used?

Multi-stage builds allow you to use intermediate builder stages to compile code and install build tools (like compilers and dev packages), then copy only the finalized production artifacts into a minimal final base image (such as Alpine or distroless), slashing image size by up to 90%.

What are the primary Docker storage mechanisms?

Docker provides three storage mechanisms: Volumes (managed entirely by Docker in /var/lib/docker/volumes; recommended for production), Bind Mounts (map arbitrary host paths into the container; ideal for local dev), and tmpfs mounts (in-memory storage that never writes to disk).

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.