These Docker interview questions are for developers, QA engineers moving into DevOps, and backend engineers who ship services in containers. Freshers are usually asked to explain images, containers and a basic Dockerfile. With two or more years of experience, interviewers at Indian product companies, service companies and startups expect you to reason about layer caching, image size, non-root users, signal handling and why a container behaves differently in CI than on your laptop.
The page is organised in four groups: freshers, intermediate, experienced (3+ years) and scenario-based questions that mirror real production incidents. Each answer explains what a strong response includes and where candidates commonly slip. The questions were compiled by VidhaiX trainers from the mock interviews they run with learners, so treat them as practice prompts. Build the examples yourself, break them, and be ready to explain the trade-offs in your own words.
How to Prepare for a Docker Interview
- Write a multi-stage Dockerfile for a real Node.js or Python service, then measure the final image size with `docker image ls` and try to cut it in half.
- Run `docker history` and `docker image inspect` on your image so you can explain exactly which instruction created each layer and why cache was invalidated.
- Build a Docker Compose v2 stack with an app, PostgreSQL and Redis, using healthchecks and `depends_on` with `condition: service_healthy` so startup order is reliable.
- Practise debugging: exec into a running container, read logs, inspect networks, and use `docker debug` or an ephemeral busybox container against a distroless image.
- Send SIGTERM to your container with `docker stop` and confirm the app shuts down gracefully within the timeout, using exec-form `CMD` and `--init` where needed.
- Scan an image with Docker Scout or Trivy, generate an SBOM, and be ready to explain how you would triage and fix the critical vulnerabilities it reports.
- Learn enough Kubernetes vocabulary (pods, deployments, services, probes) to explain where Docker stops and an orchestrator takes over, without overclaiming experience.
Docker Interview Questions for Freshers
12 questions
Q1.What is a container, and how is it different from a virtual machine?
A container is a normal Linux process isolated with kernel features: namespaces give it its own view of PIDs, network, mounts, hostname and users, and cgroups limit how much CPU, memory and I/O it can consume. All containers share the host kernel. A VM runs a full guest OS on a hypervisor with its own kernel.
So containers start in milliseconds and are lighter, but the isolation boundary is weaker. A weak answer says 'containers are lightweight VMs'; interviewers want namespaces, cgroups and the shared-kernel trade-off for security.
Q2.What is the difference between a Docker image and a container?
An image is an immutable, layered filesystem plus metadata such as the default command, environment variables, exposed ports and user. A container is a running (or stopped) instance of that image with a thin writable layer on top and its own runtime configuration.
You can start many containers from one image, and anything a container writes to its writable layer disappears when the container is removed. That is why state belongs in volumes, not inside the container. Good candidates also mention that images are addressed by content digest.
Q3.How do image layers and the build cache work?
Each filesystem-changing instruction in a Dockerfile (RUN, COPY, ADD) creates a layer. Layers are content-addressed and shared between images, so pulling a second image built on the same base downloads only the new layers.
During a build, Docker reuses a cached layer if the instruction and its inputs are unchanged. Once one step misses the cache, every step after it rebuilds. That is why you copy dependency manifests and install dependencies before copying the rest of the source code.
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]Q4.What is the difference between CMD and ENTRYPOINT?
ENTRYPOINT defines the executable the container always runs; CMD provides default arguments, or a default command if there is no entrypoint. Arguments passed to docker run image ... replace CMD but are appended to ENTRYPOINT. You override the entrypoint only with --entrypoint.
A common pattern is ENTRYPOINT ["python", "app.py"] with CMD ["--port", "8000"]. Interviewers also check that you use exec form (JSON array), because shell form wraps the process in /bin/sh -c and breaks signal handling.
Q5.When would you use COPY instead of ADD?
Use COPY almost always. It does one thing: copies files from the build context into the image. ADD also auto-extracts local tar archives and can fetch remote URLs, which makes its behaviour less obvious and remote downloads harder to cache and verify.
Reach for ADD only when you deliberately want local tar extraction, or when using its newer support for Git sources or checksum-verified URLs. A strong answer mentions predictability and reviewability rather than just 'best practice says so'.
Q6.What is the difference between ARG and ENV in a Dockerfile?
ARG is a build-time variable, set with --build-arg, and is not present in the running container. ENV sets an environment variable that persists into the image and every container started from it. An ARG declared before FROM is only usable in FROM lines unless redeclared inside the stage.
The trap: neither is safe for secrets. Build args are visible in docker history and image metadata, and ENV values are readable by anyone who can inspect the image. Use BuildKit secret mounts at build time and runtime secret injection instead.
Q7.What does a .dockerignore file do, and why does it matter?
It excludes paths from the build context sent to the builder. Without it, COPY . . can pull in node_modules, .git, local .env files, test artifacts and build output, which slows builds, busts the cache on irrelevant changes and can leak secrets into the image.
A good .dockerignore usually lists .git, dependency folders, logs, coverage output and environment files. Candidates who have been bitten by a leaked .env in a public image tend to remember this one well.
.git
node_modules
dist
coverage
*.log
.env*
Dockerfile*
docker-compose*.ymlQ8.What is the difference between a volume and a bind mount?
A named volume is storage managed by Docker, created with docker volume create or by Compose, and it lives independently of any container. A bind mount maps a specific host path into the container, so the host filesystem layout and permissions leak in.
Use volumes for persistent data such as database files, because they are portable and perform well on Docker Desktop. Use bind mounts for local development when you want source edits to appear immediately. Also mention tmpfs mounts for scratch data that should never touch disk.
Q9.How do you publish a container port, and what does EXPOSE actually do?
EXPOSE is documentation: it records which port the app listens on but does not open anything. Publishing happens at run time with -p 8080:3000, which maps host port 8080 to container port 3000.
Two common traps. First, the app must listen on 0.0.0.0 inside the container, not 127.0.0.1, or the published port returns connection refused. Second, -p 8080:3000 binds on all host interfaces by default; use -p 127.0.0.1:8080:3000 when the service should not be reachable from the network.
Q10.Which Docker commands do you use most often, and what do they do?
A practical answer covers the lifecycle: docker build -t name:tag ., docker run -d --name api -p 8080:3000 image, docker ps -a, docker logs -f api, docker exec -it api sh, docker stop and docker rm, plus docker image ls and docker system prune for cleanup.
Interviewers listen for whether you understand what each one does, not memorised flags. For example, docker stop sends SIGTERM and then SIGKILL after a timeout, while docker kill sends SIGKILL immediately.
Q11.What is Docker Compose and when would you use it?
Compose describes a multi-container application in a YAML file: services, images or build contexts, ports, volumes, networks, environment and dependencies. docker compose up creates a dedicated network so services can reach each other by service name.
It is ideal for local development, integration tests in CI and small single-host deployments. Note that Compose v2 is the docker compose CLI plugin; the old Python docker-compose binary is retired. It is not a cluster orchestrator, so it does not replace Kubernetes for multi-node scheduling.
Q12.Why should you avoid using the latest tag?
latest is just a default tag name, not 'the newest version'. It moves whenever someone pushes without a tag, so two machines pulling the same reference can get different images, and rollbacks become guesswork.
In production, tag images with something traceable such as a semantic version or Git commit SHA, and for strict reproducibility pin by digest (image@sha256:...), which is immutable. Base images in a Dockerfile benefit from the same treatment, ideally with a bot that updates the pinned digests.
Docker Intermediate Interview Questions
12 questions
Q13.What is a multi-stage build and why would you use one?
A multi-stage build uses several FROM stages in one Dockerfile. You compile or bundle in a build stage that has compilers and dev dependencies, then copy only the artifacts into a minimal runtime stage with COPY --from=build.
The final image is smaller, has fewer packages to patch and exposes no build tooling. Stages can also run tests or lint, and BuildKit builds independent stages in parallel and skips stages the target does not need. You can build a specific stage with --target.
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
ENTRYPOINT ["/api"]Q14.How do you reduce the size of a Docker image?
Start with a smaller base: -slim variants, Alpine (aware of musl libc differences), or distroless images that contain only the runtime. Use multi-stage builds so compilers stay out of the final image, install only production dependencies, and clean package manager caches in the same RUN step that created them.
A trap: deleting files in a later layer does not shrink the image, because the earlier layer still contains them. Check results with docker history or a tool like dive instead of guessing. Smaller images also mean a smaller attack surface.
Q15.Why should containers run as a non-root user, and how do you set it up?
By default, processes in a container run as root (UID 0). If an attacker escapes the app or the container, root inside maps to root on the host unless user namespaces are in use. Running as an unprivileged user limits the damage and is required by many Kubernetes security policies.
Create a user in the Dockerfile and switch with USER, ensuring the app's writable directories are owned by it. Many official images already ship a user, like node or distroless nonroot. Also bind to ports above 1024.
FROM python:3.13-slim
RUN useradd --create-home --uid 10001 app
WORKDIR /home/app
COPY --chown=app:app . .
RUN pip install --no-cache-dir -r requirements.txt
USER app
CMD ["python", "main.py"]Q16.How do containers on the same Docker network find each other?
On a user-defined bridge network, which Compose creates automatically, Docker runs an embedded DNS server, so containers resolve each other by container name, service name or alias. Your app connects to postgres:5432, not to an IP address that changes on every restart.
The default bridge network does not provide this name resolution, which is a common reason legacy --link setups exist. Mention that host network mode shares the host network stack, avoiding NAT but losing port isolation, and that none disables networking.
Q17.How does a HEALTHCHECK work, and why is a running container not necessarily healthy?
A running state only means the main process has not exited. The app could be deadlocked, still migrating, or unable to reach its database. HEALTHCHECK periodically runs a command inside the container, and Docker marks it healthy or unhealthy based on the exit code.
Tune interval, timeout, retries and start_period so slow startups are not marked unhealthy. Keep the check cheap and avoid tools missing from slim images, like curl. Note that Kubernetes ignores Docker HEALTHCHECK and uses its own probes.
Q18.How do you make one Compose service wait until another is actually ready?
Plain depends_on only controls start order, not readiness, so the API can boot before PostgreSQL accepts connections. Define a healthcheck on the database and use the long form depends_on with condition: service_healthy.
A strong answer adds that the app should still retry connections, because dependencies can restart later in production. condition: service_completed_successfully is useful for one-off migration or seed containers that must finish first.
services:
db:
image: postgres:17
environment:
POSTGRES_PASSWORD: example
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
retries: 10
api:
build: .
depends_on:
db:
condition: service_healthyQ19.What are Compose profiles and Compose watch used for?
Profiles let you mark optional services, such as a debugging UI, a mock mail server or a load generator, so they only start with docker compose --profile tools up. The default stack stays lean while everything lives in one file.
docker compose watch with a develop.watch section syncs changed files into running containers, rebuilds the image when files like package.json change, or restarts the service. It replaces fragile bind-mount setups that struggle with file permissions and platform-specific node_modules.
Q20.How do you view and manage container logs?
Docker captures whatever the main process writes to stdout and stderr. View it with docker logs -f --since 10m container or docker compose logs -f service. Apps should therefore log to stdout, ideally as structured JSON, not to files inside the container.
The default json-file driver grows unbounded unless you set max-size and max-file, which has filled many production disks. The local driver rotates by default. In production, ship logs to a central system such as Loki, CloudWatch or ELK.
Q21.How do you set CPU and memory limits on a container, and what happens when they are exceeded?
Use --memory 512m and --cpus 1.5 on docker run, or deploy.resources.limits in Compose. These map to cgroup settings. Exceeding the memory limit gets the process OOM-killed by the kernel, visible as exit code 137 and OOMKilled: true in docker inspect. Exceeding CPU only throttles the process.
Runtimes must be container-aware: modern JVMs and Node read cgroup limits, but heap sizes may still need tuning. A strong answer distinguishes limits from reservations.
Q22.What are the common restart policies, and when would you use each?
no is the default. on-failure[:max] restarts only on non-zero exit, useful for workers. always restarts even after a manual stop once the daemon restarts. unless-stopped behaves like always but respects a manual stop.
For single-host deployments with Compose, unless-stopped is the usual choice. Mention that restart policies are not a substitute for healthchecks: Docker alone does not restart an unhealthy container that is still running; orchestrators like Kubernetes or Swarm handle that.
Q23.How do you tag and push an image to a private registry?
Image references have the form registry/namespace/repository:tag. You authenticate with docker login (or a credential helper for ECR, GCR or ACR), tag the local image with the full registry path, and docker push it. Only layers missing from the registry are uploaded.
In CI, tag with the commit SHA plus a human-readable version, and record the pushed digest so deployments reference exactly what was tested. Configure registry retention policies so old tags do not grow storage costs indefinitely.
docker build -t api:1.4.2 .
docker tag api:1.4.2 registry.example.com/team/api:1.4.2
docker tag api:1.4.2 registry.example.com/team/api:git-3f9c2ab
docker push --all-tags registry.example.com/team/apiQ24.How do you pass configuration and secrets to a container at runtime?
Non-sensitive configuration goes in environment variables via -e, --env-file or Compose environment. For secrets, environment variables are convenient but leak through docker inspect, crash dumps and child processes.
Better options are Compose or Swarm secrets, mounted as files under /run/secrets, or a secret manager such as Vault or AWS Secrets Manager read at startup, or Kubernetes Secrets. Never bake secrets into images, and never commit .env files with real credentials.
Docker Interview Questions for Experienced (3+ Years)
11 questions
Q25.Explain PID 1 inside a container and why signal handling breaks.
The container's main process runs as PID 1, which the kernel treats specially: it does not get default signal handlers, so SIGTERM is ignored unless the app installs a handler. PID 1 must also reap zombie child processes. With shell-form CMD, /bin/sh becomes PID 1 and does not forward signals, so docker stop waits the full timeout and then SIGKILLs.
Fixes: use exec form, exec in entrypoint scripts, handle SIGTERM in the app, and add a minimal init like tini or docker run --init.
#!/bin/sh
set -e
# run migrations, then hand PID 1 to the app
node scripts/migrate.js
exec node server.jsQ26.Which BuildKit features do you use in production Dockerfiles?
Cache mounts (RUN --mount=type=cache) keep package manager caches across builds without bloating layers. Secret mounts (--mount=type=secret) expose tokens to a single RUN step without persisting them. SSH mounts forward an agent for private Git dependencies.
For CI, export cache to a registry or the GitHub Actions cache with --cache-to and --cache-from, since ephemeral runners start cold. BuildKit also parallelises independent stages and supports heredocs in RUN. A strong candidate can explain why secrets in ARG are unsafe.
# syntax=docker/dockerfile:1
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
--mount=type=secret,id=npmrc,target=/root/.npmrc \
npm ci --omit=dev
COPY . .Q27.How do you build multi-architecture images, and what problems have you hit?
Use docker buildx build --platform linux/amd64,linux/arm64 --push, which produces a manifest list so each host pulls the matching variant. Building is needed for Apple Silicon laptops, AWS Graviton and ARM CI runners alike.
Emulated builds through QEMU are slow, so for compiled languages use cross-compilation with --platform=$BUILDPLATFORM in the build stage and the TARGETOS/TARGETARCH args, or native builder nodes per architecture. Watch for native npm or Python wheels missing for one architecture and for 'exec format error' when the wrong variant runs.
Q28.How do you integrate image scanning and SBOMs into a delivery pipeline?
Generate an SBOM at build time (docker buildx build --sbom=true or Syft) and attach provenance attestations, then scan with Docker Scout or Trivy. Fail the pipeline on fixable critical or high CVEs, not every finding, or teams learn to ignore the gate.
Since new CVEs appear after deploy, rescan images already in the registry continuously. Triage by reachability and exploitability, fix mostly by updating the base image or dependency, and document accepted risks with VEX or an ignore file that has an expiry. Smaller bases reduce noise.
docker buildx build --sbom=true --provenance=mode=max \
-t registry.example.com/team/api:1.4.2 --push .
trivy image --severity CRITICAL,HIGH --ignore-unfixed \
--exit-code 1 registry.example.com/team/api:1.4.2Q29.How do you debug a container built from a distroless or scratch image that has no shell?
You cannot docker exec sh into it. Options: docker debug, which attaches a toolbox shell to a running container without modifying the image; run a sidecar such as docker run -it --pid=container:api --network=container:api busybox to share its process and network namespaces; or use nsenter from the host.
In Kubernetes the equivalent is kubectl debug with ephemeral containers. A weak answer is 'switch to a full base image'; strong candidates keep production images minimal and keep a debug variant for local use.
Q30.What security hardening do you apply to containers beyond running as non-root?
Drop all Linux capabilities and add back only what is needed (--cap-drop ALL), set --security-opt no-new-privileges, use a read-only root filesystem with tmpfs for scratch paths, and keep default seccomp and AppArmor profiles enabled.
Never use --privileged or mount /var/run/docker.sock into application containers; socket access is effectively root on the host. Add resource limits to contain denial of service, pin base images by digest, sign images (for example with Cosign) and verify signatures at deploy time.
Q31.What are rootless Docker and Podman, and when would you choose them?
Rootless mode runs the Docker daemon and containers as an unprivileged user using user namespaces, so a container escape lands in a normal user account rather than root. Podman is daemonless and rootless by default, CLI-compatible with Docker, and supports pods and systemd integration through Quadlet.
Trade-offs: rootless networking and some storage drivers have limits, binding ports below 1024 needs extra configuration, and some tooling expects the Docker socket. They suit shared CI runners, multi-tenant hosts and security-sensitive environments.
Q32.How would you explain the relationship between Docker and Kubernetes?
Docker builds images and runs containers on one host. Kubernetes orchestrates containers across a cluster: scheduling, self-healing, rolling updates, service discovery, autoscaling and config management. Since dockershim was removed in Kubernetes 1.24, clusters run containers through CRI runtimes such as containerd or CRI-O, but Docker-built images work unchanged because they follow the OCI spec.
A strong answer avoids 'Kubernetes replaced Docker'. Developers still use Docker for builds and local work; Kubernetes runs production workloads at scale.
Q33.How does the overlay filesystem work, and what are the performance implications of writing inside a container?
The overlay2 driver stacks read-only image layers with a writable upper layer. When a container modifies an existing file, the whole file is copied up into the writable layer first (copy-on-write), which is costly for large files and databases.
That is why write-heavy paths such as database data directories, upload folders and caches should use volumes, which bypass the overlay. Many small writes also bloat the container layer, visible with docker ps -s. On Docker Desktop, bind mounts add file-sharing overhead too.
Q34.How do you make Docker builds fast and reproducible in CI?
Order instructions so dependency installation is cached, keep the build context small with .dockerignore, use BuildKit cache mounts, and persist build cache across ephemeral runners with registry or CI cache backends via --cache-from and --cache-to.
For reproducibility, pin base images by digest, use lockfiles with npm ci or equivalent, avoid apt-get upgrade without pinned versions, and record the digest of what was built. Build once, then promote the same digest across environments instead of rebuilding per stage.
Q35.How do you design graceful shutdown for a containerised web service?
On SIGTERM, the service should stop accepting new connections, mark itself not ready so the load balancer drains it, finish in-flight requests, close database pools and flush telemetry, then exit with code 0 before the stop timeout, 10 seconds by default in Docker and 30 in Kubernetes.
This requires the app to be PID 1 via exec form or behind tini. Test it with docker stop and timing logs. Long-running jobs need checkpointing or a longer stop_grace_period, not just hope.
process.on('SIGTERM', () => {
console.log('SIGTERM received, draining')
server.close(async () => {
await db.end()
process.exit(0)
})
})Docker Scenario-Based Interview Questions
8 questions
Q36.A container starts and immediately exits. How do you troubleshoot it?
Check docker ps -a for the exit code and docker logs for output. Exit code 1 is usually an application error, 127 means the command was not found, 126 a permission or not-executable issue, and 137 a SIGKILL, often OOM. Use docker inspect to confirm the final Cmd, Entrypoint and State.
Then reproduce interactively with docker run -it --entrypoint sh image. Common causes: a missing environment variable, a script with Windows line endings, a binary built for the wrong architecture, or a foreground process that daemonises and exits.
Q37.docker stop takes 10 seconds every time and the app never logs a clean shutdown. What is wrong?
Almost always the app is not receiving SIGTERM. Either CMD is in shell form so /bin/sh is PID 1 and swallows the signal, an entrypoint script launches the app without exec, or the app runs as PID 1 without a signal handler. Docker waits the timeout and then sends SIGKILL.
Confirm with docker exec container ps to see what PID 1 is. Fix with exec form, exec in scripts, a SIGTERM handler and --init or tini. Then retest and verify in-flight requests complete.
Q38.Your image builds fine on your laptop but fails or behaves differently in CI. How do you approach it?
List the differences: architecture (Apple Silicon arm64 locally versus amd64 runners), a stale local cache hiding a broken step, a moving base image tag, files present locally but excluded or missing in the CI checkout, and different BuildKit or Docker versions.
Reproduce with docker buildx build --no-cache --platform linux/amd64 locally, pin the base image digest, check .dockerignore and Git LFS files, and print versions in CI. Usually it is the cache or architecture; prove which before changing the Dockerfile.
Q39.Your production image is 2.1 GB and deploys are slow. Walk me through cutting it down.
First measure: docker history or dive to find the heavy layers. Typical culprits are a full OS base, build toolchains, dev dependencies, package caches, test fixtures and a context that copied .git or node_modules.
Then fix in order of impact: multi-stage build with a slim or distroless runtime, production-only dependencies, a strict .dockerignore, and cleanup in the same RUN step. Re-measure after each change and run the test suite against the smaller image, since missing shared libraries or CA certificates often surface only at runtime.
Q40.The API container cannot connect to the database container in Docker Compose. How do you debug it?
Check the connection string first: inside Compose, the host is the service name (db), not localhost, which points back at the API container itself. The port is the container port, not the published host port. Then confirm both services share a network with docker network inspect.
Next, check readiness: is the database healthy, or did the API start first without retries? Test from inside with docker compose exec api using getent hosts db or nc -z db 5432. Finally check credentials and that the database listens on all interfaces.
Q41.A security scan reports 300 vulnerabilities in your image two days before release. What do you do?
Do not panic or blanket-ignore. Filter to critical and high severity with a fix available, then check which packages are actually used at runtime. Most findings usually come from the base OS, so rebuilding on an updated or smaller base like slim or distroless often removes the majority.
Update vulnerable application dependencies, rescan and compare. For what remains, assess exploitability, document accepted risks with an expiry, and agree with security on whether release proceeds. Afterwards, add scheduled base image updates so this does not pile up again.
Q42.A container on a production host keeps getting killed with exit code 137. How do you investigate?
137 means SIGKILL. Run docker inspect and check State.OOMKilled; if true, the container exceeded its memory limit. Check host logs with dmesg or journalctl -k for OOM killer entries, and docker stats to see memory over time.
Then decide whether it is a leak, a limit set too low, or a runtime ignoring the cgroup limit, for example a JVM or Node heap configured larger than the container. Capture a heap profile before raising limits. If OOMKilled is false, look for manual kills or a failed stop.
Q43.The production host ran out of disk space and Docker is the main culprit. How do you recover and prevent it?
Start with docker system df -v to see what is using space: images, stopped containers, volumes, build cache or container logs. Unbounded json-file logs and dangling images from frequent deploys are the usual cause. Clean carefully with docker image prune and docker builder prune; be cautious with volume pruning, which can delete data.
Prevent recurrence by configuring log rotation in daemon.json, pruning old images in the deploy script, monitoring disk usage with alerts, and keeping Docker's data root on a separately sized volume.