- Docker questions test whether you understand images as layered, cached filesystems and containers as processes isolated by namespaces and cgroups, not lightweight VMs.
- Kubernetes questions test the control loop (desired vs actual state), the Pod → ReplicaSet → Deployment chain, Service types, ingress, and probes plus resource limits.
- Most interviews end with troubleshooting: CrashLoopBackOff, ImagePullBackOff, Pending, OOMKilled (exit 137), and a Service with no endpoints. Have a command sequence ready.
- Liveness restarts, readiness removes from traffic. Memory over limit kills; CPU over limit throttles.
- Secrets are base64, not encrypted, unless the cluster enables encryption at rest.
Containers have become a baseline expectation for backend engineers at Indian product companies, not just a DevOps specialty. A Razorpay or Swiggy backend engineer is expected to read a Dockerfile, reason about why a pod is restarting, and set sensible probes and limits. This guide covers 50 Docker and Kubernetes interview questions, with answers, commands and YAML you can actually run on a local cluster.
If you want the conceptual tour before the Q&A, read Docker and Kubernetes for backend engineers first, then come back here to drill.
Who Gets Asked Docker and Kubernetes Questions, and How Deep
| Role | Typical depth | What decides the round |
|---|---|---|
| Backend SDE-1/SDE-2 | Dockerfile, multi-stage builds, pods, deployments, services, probes | Can you ship and debug your own service? |
| Senior backend | Plus resource tuning, rollouts, HPA, graceful shutdown, stateful workloads | Do you design for failure and scale? |
| DevOps / SRE / Platform | Plus control plane internals, networking (CNI, kube-proxy), RBAC, storage, upgrades | Can you run the cluster, not just deploy to it? |
Interviewers almost always end with a scenario: "Your pod is in CrashLoopBackOff, walk me through it." The final section is built around exactly those scenarios.
Docker Fundamentals Interview Questions (Q1-8)
Q1. What is a container, really?
A container is an ordinary Linux process (or group of processes) with isolation applied by the kernel. Namespaces control what the process can see: its own PID tree, network stack, mount table, hostname, IPC and users. cgroups control what it can use: CPU, memory, I/O, number of processes. A union filesystem gives it its own root filesystem from an image. There is no guest kernel.
Q2. Container vs virtual machine?
| Container | Virtual machine | |
|---|---|---|
| Kernel | Shares the host kernel | Own guest kernel on a hypervisor |
| Startup | Milliseconds to seconds | Tens of seconds to minutes |
| Size | MBs | GBs |
| Isolation | Process-level; weaker boundary | Hardware-level; stronger boundary |
| Can run a different OS kernel | No (Linux containers need a Linux kernel; Docker Desktop runs a small Linux VM on Mac/Windows) | Yes |
Q3. Image vs container?
An image is a read-only template: a stack of filesystem layers plus metadata (entrypoint, env, exposed ports). A container is a running (or stopped) instance of an image with a thin writable layer on top. One image, many containers, like a class and its objects.
Q4. What happens when you run docker run nginx?
- CLI to daemon. The docker CLI sends the request to dockerd over its API.
- Pull if missing. The image
nginx:latestis pulled from Docker Hub layer by layer; existing layers are reused. - Create. containerd sets up the container: a writable layer, namespaces, cgroups, a network interface on the default bridge.
- Start. runc (the OCI runtime) starts the entrypoint process inside those namespaces.
Q5. What is the Docker architecture?
The client (docker CLI) talks to the daemon (dockerd), which manages images, networks and volumes and delegates container lifecycle to containerd, which uses runc to create the actual processes. Images are stored in registries (Docker Hub, ECR, GCR, Harbor). Images follow the OCI standard, which is why Kubernetes can run them without Docker.
Q6. What are common docker commands you use daily?
docker build -t orders-api:1.4.2 .
docker run -d --name orders -p 8080:8080 -e SPRING_PROFILES_ACTIVE=dev orders-api:1.4.2
docker ps -a # running and stopped containers
docker logs -f --tail 100 orders # follow logs
docker exec -it orders sh # shell into a running container
docker inspect orders # full JSON: IPs, mounts, env, restart count
docker stats # live CPU / memory per container
docker system df # disk used by images, containers, volumes
docker image prune -a # remove unused images
Q7. What does exit code 137 mean? And 143?
Exit codes above 128 mean "killed by signal (code − 128)". 137 = SIGKILL (9), most often the OOM killer or a forced stop after a timeout. 143 = SIGTERM (15), a normal graceful stop. Check docker inspect --format '{{.State.OOMKilled}}' orders to confirm OOM.
Q8. Why does my container take 10 seconds to stop?
docker stop sends SIGTERM, waits 10 seconds, then SIGKILL. If it always takes the full 10 seconds, your app never receives or handles SIGTERM. Usual cause: the shell form CMD java -jar app.jar runs /bin/sh -c as PID 1, and the shell does not forward signals. Use the exec form CMD ["java", "-jar", "app.jar"], or add an init (docker run --init or tini) when your process spawns children it does not reap.
Dockerfile, Image Layers and Build Optimisation (Q9-17)
Q9. How do image layers and the build cache work?
Each filesystem-changing instruction (RUN, COPY, ADD) creates a layer. Layers are content-addressed and shared across images. During a build, Docker reuses a cached layer if the instruction and its inputs are unchanged. Once one layer misses the cache, every layer after it is rebuilt. So order instructions from least to most frequently changing.
Q10. Fix this slow Dockerfile.
FROM node:22
WORKDIR /app
COPY . .
RUN npm install
CMD npm start
# ---- build stage ----
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci # cached unless the lockfile changes
COPY . .
RUN npm run build && npm prune --omit=dev
# ---- runtime stage ----
FROM node:22-slim
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
Talk through each change: dependency manifests copied first so the install layer is cached; npm ci for reproducible installs; build tools stay in the build stage; runs as non-root; exec-form CMD for signals. Add a .dockerignore with node_modules, .git and .env so the build context is small and secrets never enter the image.
Q11. What is a multi-stage build and why use it?
Multiple FROM stages in one Dockerfile; later stages copy only artifacts from earlier ones. A Java service compiles with a full JDK and Maven in stage one, then ships only the jar on a JRE base. Images shrink from around a gigabyte to a couple of hundred MB, with fewer packages for attackers and vulnerability scanners to find.
Q12. CMD vs ENTRYPOINT?
ENTRYPOINT is the fixed executable; CMD provides default arguments, replaced by anything after the image name in docker run. Example: ENTRYPOINT ["python", "manage.py"] with CMD ["runserver", "0.0.0.0:8000"] lets docker run img migrate run migrations with the same image.
Q13. COPY vs ADD?
COPY copies local files. ADD additionally auto-extracts local tar archives and can fetch URLs. Prefer COPY for predictability; use ADD only for its tar extraction.
Q14. ARG vs ENV?
ARG exists only at build time (--build-arg). ENV persists into the image and running containers. Never pass secrets through either: build args are visible in docker history. Use BuildKit secret mounts (RUN --mount=type=secret,id=npmrc ...).
Q15. Alpine, slim or distroless?
Alpine is tiny but uses musl libc, which can break or slow native dependencies built for glibc (some Python wheels, Node native addons). Debian -slim images are a safe default. Distroless images contain only the runtime and your app, with no shell or package manager: excellent for security, harder to debug (use ephemeral debug containers in Kubernetes).
Q16. How do you tag images for production?
Never deploy :latest: it is mutable, so you cannot tell what is running or roll back reliably. Tag with an immutable version or Git SHA (orders-api:1.4.2 or orders-api:3f9c2ab), and for maximum safety deploy by digest (@sha256:...).
Q17. How do you secure container images?
- Minimal base images, rebuilt regularly for patches.
- Scan in CI (Trivy, Grype, ECR scanning) and fail builds on critical vulnerabilities.
- Run as non-root, with a read-only root filesystem where possible.
- No secrets in layers; deleting a file in a later layer does not remove it from earlier layers.
- Sign images (cosign) and only allow signed images into production clusters.
Docker Networking and Volumes Questions (Q18-23)
Q18. Explain Docker network drivers.
| Driver | What it does | When |
|---|---|---|
| bridge | Private virtual network on the host with NAT out; default | Single-host apps |
| host | Container shares the host's network stack; no isolation, no port mapping | Maximum network performance on Linux |
| none | No networking | Batch jobs that must be offline |
| overlay | Spans multiple hosts (Swarm) | Multi-host without Kubernetes |
| macvlan | Container gets its own MAC on the physical network | Legacy apps expecting to be on the LAN |
Q19. Why can't my two containers reach each other by name?
Containers on the default bridge network can only reach each other by IP. A user-defined bridge network has built-in DNS, so orders can call http://postgres:5432. Docker Compose creates a user-defined network per project automatically, which is why names work there.
docker network create shop
docker run -d --name postgres --network shop -e POSTGRES_PASSWORD=dev postgres:16
docker run -d --name orders --network shop -e DB_HOST=postgres orders-api:1.4.2
Q20. What does -p 8080:80 mean, and why does localhost not work inside a container?
It maps host port 8080 to container port 80. Inside a container, localhost is the container itself, not your laptop. To reach a service on the host, use host.docker.internal (Docker Desktop, or add it via --add-host=host.docker.internal:host-gateway on Linux). Also make sure your app binds to 0.0.0.0, not 127.0.0.1, or published ports will not reach it.
Q21. Volumes vs bind mounts vs tmpfs?
Named volumes are managed by Docker and the right default for persistent data (a dev Postgres). Bind mounts map a host path into the container, great for live-reloading source code in development, but tied to host paths and permissions. tmpfs mounts live in memory and vanish on stop, useful for scratch files or secrets you do not want on disk.
Q22. What happens to data written inside a container when it is removed?
Anything written to the container's writable layer is lost with docker rm. Containers should be disposable; state goes to volumes or, better in production, to managed services (RDS, S3).
Q23. What is Docker Compose for?
Defining multi-container apps in YAML: services, networks, volumes, env, dependencies. Ideal for local development and integration tests (app plus Postgres plus Redis plus Kafka with one docker compose up). depends_on controls start order but not readiness unless you use condition: service_healthy with a healthcheck.
Kubernetes Architecture and Workloads (Q24-30)
Q24. Describe Kubernetes architecture.
The API server is the only component that talks to etcd; everything else watches the API. The scheduler assigns pending pods to nodes based on resource requests, affinity and taints. The controller manager runs reconciliation loops (Deployment, ReplicaSet, Node, Job controllers). On each node, the kubelet makes sure the assigned pods' containers are running via the container runtime, and kube-proxy programs Service routing (iptables or IPVS rules).
Q25. What is the reconciliation loop?
You declare desired state ("3 replicas of orders-api:1.4.2"). Controllers continuously compare it with actual state and act to close the gap: a node dies, two pods vanish, the ReplicaSet controller creates two more. This is why Kubernetes is declarative: you edit YAML, not run step-by-step commands.
Q26. What is a Pod, and why not just containers?
The smallest deployable unit: one or more containers that share a network namespace (same IP, talk via localhost) and can share volumes, always scheduled together. Multi-container pods are for tightly coupled helpers: a log-shipping sidecar, a service-mesh proxy, an init container that runs migrations before the app starts.
Q27. Pod vs ReplicaSet vs Deployment?
A bare Pod is not recreated if its node dies. A ReplicaSet keeps N identical pods running. A Deployment manages ReplicaSets to give you rolling updates and rollbacks: a new image creates a new ReplicaSet that scales up while the old one scales down. You almost always create Deployments, never ReplicaSets directly.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 3
selector:
matchLabels: { app: orders-api }
strategy:
rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } # never drop below 3 ready
template:
metadata:
labels: { app: orders-api }
spec:
containers:
- name: app
image: registry.example.com/orders-api:1.4.2
ports: [{ containerPort: 8080 }]
resources:
requests: { cpu: "250m", memory: "512Mi" }
limits: { memory: "512Mi" }
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
periodSeconds: 5
livenessProbe:
httpGet: { path: /health/live, port: 8080 }
periodSeconds: 10
failureThreshold: 3
startupProbe:
httpGet: { path: /health/live, port: 8080 }
periodSeconds: 5
failureThreshold: 24 # up to 120 s to boot
terminationGracePeriodSeconds: 30
Q28. Deployment vs StatefulSet vs DaemonSet vs Job?
| Workload | Guarantees | Example |
|---|---|---|
| Deployment | Interchangeable replicas, random names | Stateless APIs |
| StatefulSet | Stable names (kafka-0, kafka-1), ordered start/stop, a persistent volume per replica | Kafka, Cassandra, Elasticsearch, ZooKeeper |
| DaemonSet | One pod per node (or per matching node) | Log collectors, node exporters, CNI agents |
| Job / CronJob | Run to completion, retry on failure; on a schedule | DB migrations, nightly reports, settlement files |
Q29. How do rolling updates and rollbacks work?
With maxSurge and maxUnavailable (default 25% each), the Deployment brings up new pods and removes old ones only after new pods pass readiness. A bad release that never becomes ready stalls the rollout instead of taking the service down, as long as readiness probes are meaningful. Commands: kubectl rollout status deploy/orders-api, kubectl rollout history, kubectl rollout undo deploy/orders-api. For canary or blue-green, teams use Argo Rollouts, Flagger or a service mesh.
Q30. ConfigMap vs Secret?
Both inject configuration as env vars or mounted files. Secrets are meant for sensitive data, are base64-encoded (not encrypted), can be encrypted at rest in etcd if the cluster enables it, and are access-controlled separately via RBAC. Mounted files update when the object changes; env vars do not, so a pod restart is needed. Many teams sync secrets from AWS Secrets Manager or Vault using the External Secrets Operator.
Kubernetes Services, DNS and Ingress (Q31-36)
Q31. Why do we need Services?
Pod IPs change every time a pod is recreated. A Service gives a stable virtual IP and DNS name (orders-api.shop.svc.cluster.local, or just orders-api from the same namespace) and load-balances across all ready pods matching its label selector.
Q32. Explain the Service types.
| Type | Reachable from | Use |
|---|---|---|
| ClusterIP (default) | Inside the cluster | Service-to-service calls |
| NodePort | Every node's IP on a port in 30000-32767 | Testing, or behind your own load balancer |
| LoadBalancer | A cloud load balancer's public or internal IP | Exposing one service directly (one LB per service, which costs money) |
| ExternalName | DNS CNAME to an external host | Point payments-db at an RDS endpoint |
Headless (clusterIP: None) | DNS returns individual pod IPs | StatefulSets, client-side load balancing |
Q33. How does traffic actually reach a pod through a ClusterIP?
The ClusterIP is virtual; no interface owns it. kube-proxy on every node watches Services and EndpointSlices and writes iptables or IPVS rules that DNAT packets destined for the ClusterIP to one of the backing pod IPs. Some CNIs (Cilium with eBPF) replace kube-proxy entirely. CoreDNS answers the name lookups.
Q34. What is an Ingress?
An Ingress is an L7 routing rule set: host and path based routing, TLS termination, one entry point for many services. It needs an Ingress controller (NGINX-based, Traefik, HAProxy, or a cloud one like the AWS Load Balancer Controller) to do anything.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop
spec:
ingressClassName: nginx
tls:
- hosts: [api.shop.example]
secretName: shop-tls
rules:
- host: api.shop.example
http:
paths:
- path: /orders
pathType: Prefix
backend: { service: { name: orders-api, port: { number: 80 } } }
- path: /payments
pathType: Prefix
backend: { service: { name: payments-api, port: { number: 80 } } }
Worth mentioning in 2026: the Gateway API (Gateway, HTTPRoute) is the more expressive successor to Ingress, with role separation between platform and app teams, and the community ingress-nginx controller announced its retirement in late 2025, so many teams are migrating. Confirm what your target company runs.
Q35. Ingress vs LoadBalancer Service?
A LoadBalancer Service is L4 and one cloud LB per service. An Ingress is L7 with one LB (in front of the controller) routing to many services by host and path, with TLS in one place. Ten public services means ten LBs versus one.
Q36. What are NetworkPolicies?
Firewall rules for pods. By default, every pod can talk to every pod. A NetworkPolicy can say "only pods labelled app: orders-api may reach Postgres on 5432". They need a CNI that enforces them (Calico, Cilium); on a CNI that does not, policies are silently ignored.
Probes, Resources, Autoscaling (Q37-43)
Q37. Liveness vs readiness vs startup probes?
| Probe | On failure | Should check |
|---|---|---|
| Liveness | kubelet restarts the container | Is the process stuck (deadlock, wedged event loop)? Keep it cheap and local. |
| Readiness | Pod removed from Service endpoints; no restart | Can I serve traffic now (warmed up, connected to required deps)? |
| Startup | Liveness and readiness wait until it succeeds; restart if it never does | Has the slow-booting app finished starting? |
Q38. What's wrong with checking the database in a liveness probe?
If the database has a blip, every pod's liveness fails at once and Kubernetes restarts the entire fleet, turning a dependency hiccup into a full outage and a reconnection storm when everything boots together. Dependency checks belong in readiness (and even there, carefully); liveness should only answer "is this process healthy".
Q39. Requests vs limits?
Requests are what the scheduler reserves; a pod is placed only on a node with that much unreserved capacity. Limits are the ceiling enforced at runtime. CPU over limit is throttled (latency goes up); memory over limit is OOMKilled. A common production practice is to set memory limit equal to memory request, and set CPU requests but be cautious with CPU limits, since throttling hurts latency-sensitive services.
Q40. What are QoS classes?
Guaranteed: every container has requests equal to limits for both CPU and memory. Burstable: at least one request or limit set, but not Guaranteed. BestEffort: nothing set. Under node memory pressure, the kubelet evicts BestEffort first, then Burstable pods using more than their requests, and Guaranteed last.
Q41. How does the Horizontal Pod Autoscaler work?
HPA periodically reads metrics (CPU or memory utilisation relative to requests, or custom metrics like queue lag or requests per second) and computes desired = ceil(current × currentMetric / targetMetric). Example: 4 pods at 90% CPU with a 60% target gives ceil(4 × 90/60) = 6 pods. It needs the metrics server, requests must be set, and scaling is bounded by minReplicas/maxReplicas. If nodes are full, the Cluster Autoscaler or Karpenter adds nodes.
Q42. How do you handle graceful shutdown in Kubernetes?
On deletion, the pod is removed from endpoints and simultaneously sent SIGTERM; these happen in parallel, so a few requests may still arrive after SIGTERM. Handle SIGTERM by finishing in-flight work, optionally add a short preStop sleep (5-10 seconds) so load balancers catch up, and keep total time under terminationGracePeriodSeconds (30 s by default) before SIGKILL.
Q43. How do PersistentVolumes work?
A PersistentVolumeClaim requests storage (size, access mode). A StorageClass dynamically provisions a matching PersistentVolume (an EBS volume on AWS, for example). Access modes matter: ReadWriteOnce volumes attach to one node at a time, which is why a pod using an EBS volume cannot move to a node in another availability zone.
Kubernetes Troubleshooting Interview Scenarios (Q44-50)
Have a default sequence and say it out loud. Interviewers grade the method more than the final answer.
kubectl get pods -o wide # status, restarts, node
kubectl describe pod orders-api-7d9f-x2k4p # events, last state, exit code, probe failures
kubectl logs orders-api-7d9f-x2k4p --previous # logs of the crashed container
kubectl get events --sort-by=.lastTimestamp # cluster-level story
kubectl exec -it orders-api-7d9f-x2k4p -- sh # inspect from inside
kubectl top pod # CPU / memory usage (needs metrics-server)
kubectl debug -it orders-api-7d9f-x2k4p --image=busybox --target=app # ephemeral debug container
Q44. Pod is in CrashLoopBackOff. Walk me through it.
The container starts, exits, and Kubernetes restarts it with exponential backoff (up to five minutes). Steps: describe for the last state's exit code and reason; logs --previous for the actual error. Typical causes by exit code: 1 (app error: missing env var, bad config, cannot reach DB at boot), 137 with OOMKilled (raise memory or fix the leak; for JVMs check heap vs container limit), 137 without OOM plus liveness failures in events (probe killing a slow starter; add a startup probe). Also check the command: a container whose main process exits immediately (a script that runs and returns) will loop forever.
Q45. ImagePullBackOff?
The kubelet cannot pull the image. describe shows why: wrong image name or tag (typo, tag never pushed), private registry without an imagePullSecret or node IAM permission (ECR), Docker Hub rate limits, or the node cannot reach the registry (no NAT for private subnets).
Q46. Pod stuck in Pending?
The scheduler cannot place it. Events say why: Insufficient cpu/memory (requests too large or cluster full; check autoscaler), untolerated taints, unsatisfiable node affinity, or an unbound PVC (no matching StorageClass, or a zonal volume in another zone).
Q47. The Service returns connection refused or 503. Pods look Running.
- Endpoints.
kubectl get endpointslices -l kubernetes.io/service-name=orders-api. Empty means the selector labels do not match the pod labels, or no pod is Ready. - Ports. Service
targetPortmust match the container's listening port. - Bind address. The app must listen on
0.0.0.0, not127.0.0.1. - Bypass layers.
kubectl port-forward pod/...to test the pod directly, then the Service, then the Ingress, narrowing down where it breaks. - Policies. A NetworkPolicy may be blocking the caller.
Q48. Latency spikes but CPU usage looks low. What do you suspect?
CPU throttling. Average usage can be under the limit while short bursts exceed the per-period quota (100 ms CFS periods), so the container is paused mid-request. Check the container_cpu_cfs_throttled_periods_total metric. Fixes: raise or remove the CPU limit, or reduce thread counts that burst (JVMs sizing thread pools from host cores rather than the container's quota is a classic).
Q49. A node goes NotReady. What happens to its pods?
The node controller marks it NotReady when the kubelet stops reporting. After a toleration period (by default about five minutes via the node.kubernetes.io/unreachable taint), pods are evicted and their controllers recreate them elsewhere. StatefulSet pods are not force-replaced automatically because two pods with the same identity could corrupt data; an operator must confirm the node is truly gone.
Q50. A deployment rollout is stuck. How do you investigate and recover?
kubectl rollout status shows it waiting. New pods are usually failing readiness (wrong config in the new version, a missing secret, a migration not run). Inspect a new pod with describe and logs. Recover with kubectl rollout undo, then fix forward. Setting progressDeadlineSeconds makes the Deployment report the failure so CI/CD can roll back automatically; see CI/CD interview questions for the pipeline side.
A Hands-On Practice Lab Before Your Interview
Run a local cluster with kind, minikube or k3d and break things on purpose. Each exercise maps to a question above:
Shrink an image
Take a single-stage Java or Node Dockerfile, convert it to multi-stage, measure the size before and after with docker images, and verify cache hits after a code-only change.
OOMKill on purpose
Deploy a pod with a 64Mi memory limit running something that allocates more. Read exit code 137 and OOMKilled in describe.
Break a Service
Change the Deployment's label so it no longer matches the Service selector. Watch endpoints empty out and requests fail.
Bad rollout
Deploy an image tag that does not exist, then one whose readiness never passes. Observe the stalled rollout and roll back.
Comfort with the command line matters as much as Kubernetes knowledge here, since most debugging ends up inside a container shell; brush up with our Linux and shell interview questions. And because most Indian companies run Kubernetes on EKS, it is worth reading the AWS interview questions for VPC, IAM and load balancer context.
Frequently Asked Questions
Get Interview-Ready for Backend and DevOps Roles
Prepflix's program combines containers, cloud and system design with DSA and mock interviews tuned to Indian product companies.
Explore the Prepflix Course →