Kubernetes (K8s) Interview Questions
Kubernetes orchestrator architecture: control plane reconciliation loops, etcd Raft consensus, kube-proxy iptables/IPVS routing, CNI, and Pod disruption budgets.
Practice Kubernetes (K8s) Interview Questions
Showing 16 of 16 technical questions with engineering explanations
Why is a Pod the smallest deployable unit in Kubernetes instead of a single container?
Senior Engineering Answer
A Pod wraps one or more tightly coupled containers that must run on the same node, share a single network namespace (same IP and localhost port space), share IPC, and mount shared volumes. This co-location enables sidecar patterns—such as log shippers, service mesh proxies, or TLS terminators—without baking infrastructure tooling into the main application container image.
apiVersion: v1
kind: Pod
metadata:
name: api-with-sidecar
spec:
volumes:
- name: shared-logs
emptyDir: {}
containers:
- name: app
image: my-api:1.0
volumeMounts:
- name: shared-logs
mountPath: /var/log/app
- name: fluent-bit
image: fluent/fluent-bit:3.0
volumeMounts:
- name: shared-logs
mountPath: /var/log/appPutting unrelated services (such as a web server and its database) inside the same Pod prevents scaling them independently and ties their failure domains together.
How do Kubernetes Liveness, Readiness, and Startup probes differ, and what goes wrong when they are misconfigured?
Senior Engineering Answer
A Startup probe runs first for slow-booting apps, holding off liveness and readiness checks until startup succeeds. A Readiness probe determines whether the Pod is removed from Service EndpointSlices so it stops receiving traffic while warming caches or losing downstream connections. A Liveness probe detects deadlocked processes; failing it causes the kubelet to kill and restart the container.
readinessProbe:
httpGet:
path: /readyz
port: 8080
periodSeconds: 5
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 15Pointing a liveness probe at an endpoint that checks external database connectivity causes a cascading outage: if the database blips, Kubernetes restarts every healthy application Pod simultaneously.
What are the differences between ClusterIP, NodePort, LoadBalancer, and Headless Services in Kubernetes?
Senior Engineering Answer
ClusterIP allocates an internal virtual IP reachable only inside the cluster. NodePort opens a static port (30000-32767) on every worker node and forwards traffic to the ClusterIP. LoadBalancer provisions an external cloud load balancer pointing to NodePorts. A Headless Service (clusterIP: None) skips virtual IP load balancing and returns the individual Pod IPs directly via DNS A/AAAA records, which stateful clusters need for peer discovery.
apiVersion: v1
kind: Service
metadata:
name: postgres-headless
spec:
clusterIP: None
selector:
app: postgres
ports:
- port: 5432Using a standard ClusterIP Service in front of a Raft or gossip-based cluster hides individual Pod identities, preventing nodes from addressing specific peers like pod-0 or pod-1.
How do resource requests and limits affect Kubernetes scheduling and OOM/CPU throttling?
Senior Engineering Answer
Requests define the guaranteed capacity kube-scheduler uses to place Pods onto nodes and drive QoS classes (Guaranteed, Burstable, BestEffort). Limits cap maximum runtime consumption: exceeding memory limits triggers an immediate cgroup OOM kill (exit 137), whereas exceeding CPU limits does not kill the container—the Linux CFS bandwidth controller throttles its CPU slices during the remaining 100 ms quota period.
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "512Mi"Setting overly tight CPU limits on latency-sensitive services causes severe CFS CPU throttling even when the underlying node has plenty of idle CPU cores.
How does a Deployment execute zero-downtime rolling updates using maxSurge and maxUnavailable?
Senior Engineering Answer
A Deployment manages ReplicaSets. During a rolling update, it creates a new ReplicaSet with the updated Pod template and scales it up while scaling the old ReplicaSet down. maxSurge limits how many extra Pods above desired replicas may exist temporarily, and maxUnavailable limits how many Pods may be non-ready during rollout. Setting maxUnavailable: 0 and maxSurge: 1 guarantees full capacity throughout the rollout.
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25%
maxUnavailable: 0Neglecting a preStop sleep hook alongside readiness probes causes brief 502 errors during rolling updates because kubelet sends SIGTERM to the app concurrently with EndpointSlice removal propagation.
When should you use a StatefulSet instead of a Deployment, and how does StatefulSet handle volumes and ordering?
Senior Engineering Answer
Use a StatefulSet for stateful systems requiring deterministic ordinal hostnames (db-0, db-1), sequential startup/termination guarantees, and stable per-Pod storage. Each Pod receives its own PersistentVolumeClaim from volumeClaimTemplates; if db-1 is rescheduled to another node, it reattaches its original PVC rather than receiving blank storage. Scaling down a StatefulSet intentionally leaves PVCs intact to prevent accidental data loss.
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: gp3
resources:
requests:
storage: 50GiAssuming deleting a StatefulSet automatically deletes its PVCs; orphaned PVCs remain bound and continue accruing cloud block storage costs until explicitly cleaned up.
How does Horizontal Pod Autoscaler (HPA) compute target replicas and avoid thrashing?
Senior Engineering Answer
HPA periodically polls Metrics Server or Custom/External Metrics APIs (default every 15s) and computes desiredReplicas = ceil(currentReplicas * (currentMetricValue / desiredMetricValue)). To prevent oscillation, HPA enforces a default 10% tolerance deadband around the target value and applies configurable stabilizationWindowSeconds (default 300s for scale-down) via spec.behavior so transient traffic dips do not drop capacity prematurely.
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 25
periodSeconds: 60Combining HPA with Vertical Pod Autoscaler (VPA) both targeting CPU/memory on the same Deployment creates a feedback loop where VPA alters requests and causes HPA to scale wildly.
How do NetworkPolicies enforce zero-trust pod-to-pod traffic control, and what happens when no policy matches a Pod?
Senior Engineering Answer
By default, all Pods in a Kubernetes cluster can communicate freely across namespaces. Once at least one NetworkPolicy selects a Pod for Ingress or Egress, that Pod becomes isolated in that direction—denying all traffic not explicitly permitted by additive allow rules across matching policies. NetworkPolicies rely on a supporting CNI plugin (such as Cilium or Calico) to program eBPF or iptables rules.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: payments
spec:
podSelector: {}
policyTypes:
- IngressWriting an Egress NetworkPolicy without explicitly allowing UDP/TCP port 53 to kube-dns/CoreDNS breaks all outbound DNS resolution inside the isolated Pods.
How does etcd use the Raft consensus algorithm and resourceVersion to guarantee Kubernetes control-plane consistency?
Senior Engineering Answer
etcd stores the entire cluster state in a distributed key-value store using Raft consensus: a single elected leader appends writes to its log and commits only after a strict quorum of members (N/2 + 1) persists them, tolerating (N-1)/2 node failures. Kubernetes exposes etcd's monotonically increasing revision index as metadata.resourceVersion on every object, enabling optimistic concurrency control (rejecting stale writes with 409 Conflict) and efficient watch streams without polling.
# Watch changes cleanly from a known resourceVersion via API server kubectl get pods -n prod --watch --output-watch-events -o wide
Running an even number of etcd nodes (such as 2 or 4) provides zero extra fault tolerance over N-1 nodes while increasing quorum size and latency.
How does kube-scheduler decide which node runs a Pending Pod during its filtering and scoring phases?
Senior Engineering Answer
kube-scheduler watches for unscheduled Pods and runs a two-phase plugin pipeline. First, the Filtering (predicates) phase eliminates infeasible nodes based on NodeResourcesFit (available CPU/RAM), Taints/Tolerations, NodeAffinity, VolumeLimits, and PodTopologySpreadConstraints. Second, the Scoring phase ranks remaining nodes using weighted plugins such as LeastAllocated, ImageLocality, and InterPodAffinity, binding the Pod to the highest-scoring node via the API server.
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: checkout-apiUsing hard PodAntiAffinity (requiredDuringScheduling) across hostnames can leave Pods stuck in Pending if a Deployment's replicas exceed the number of nodes in the cluster.
How do PodDisruptionBudgets (PDBs) protect application availability during voluntary disruptions, and when can a misconfigured PDB block cluster upgrades?
Senior Engineering Answer
A PodDisruptionBudget specifies either minAvailable or maxUnavailable for a Pod selector. Voluntary disruptions—such as kubectl drain, cluster autoscaler scale-ins, or managed node-pool upgrades—must acquire permission from the Eviction API, which blocks eviction if removing a Pod would violate the PDB. Involuntary disruptions (hardware crashes or node OOMs) bypass PDB checks.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: apiSetting maxUnavailable: 0 or setting minAvailable equal to a Deployment's total replica count permanently blocks node drains and stalls automated cluster upgrades.
How do CNI plugins wire Pod networking, and why do eBPF-based CNIs like Cilium outperform kube-proxy iptables at scale?
Senior Engineering Answer
When kubelet creates a Pod sandbox, it invokes the CNI binary (via /etc/cni/net.d) to allocate an IP from IPAM, attach a veth pair into the Pod's network namespace, and wire routing on the host. Standard kube-proxy in iptables mode traverses O(N) sequential netfilter chains per packet, degrading significantly above a few thousand Services. eBPF-based CNIs like Cilium bypass host iptables entirely, using O(1) kernel hash maps directly on socket/TC hooks.
# Inspect EndpointSlices backing a Service (replaced legacy Endpoints for scale) kubectl get endpointslices -l kubernetes.io/service-name=checkout-api
Using overly small Pod CIDR blocks per node or cluster VPC subnets silently exhausts available IP addresses during autoscaling spikes, leaving new Pods stuck in ContainerCreating.
How does a Kubernetes Custom Controller / Operator implement a level-triggered reconciliation loop using Informers and Workqueues?
Senior Engineering Answer
Controllers follow level-triggered (state-based) rather than edge-triggered (event-based) reconciliation so missed events are naturally healed. A SharedInformer maintains a local thread-safe cache via List-and-Watch against kube-apiserver, enqueuing only object namespace/name keys into a rate-limiting Workqueue. Worker goroutines pop keys, compare desired spec against observed cluster or external cloud state, mutate idempotently, and update status subresources—using Finalizers to clean up external resources before deletion.
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var obj v1alpha1.Database
if err := r.Get(ctx, req.NamespacedName, &obj); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if !obj.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, &obj)
}
return r.reconcileNormal(ctx, &obj)
}Leaving a Finalizer on a resource whose controller Pod has been deleted causes the namespace or custom resource to hang indefinitely in Terminating state.
How do API Priority and Fairness (APF) and admission webhooks protect kube-apiserver stability in large multi-tenant clusters?
Senior Engineering Answer
API Priority and Fairness (APF) replaces global max-inflight throttling by classifying API requests via FlowSchemas into isolated PriorityLevels with dedicated concurrency shares and shuffle-sharded queues, ensuring noisy tenant watch/list floods cannot starve kubelet node heartbeats or leader-election leases. Admission control chains MutatingAdmissionWebhooks before schema validation and ValidatingAdmissionWebhooks (or native ValidatingAdmissionPolicy CEL expressions) afterward.
# Check APF priority level concurrency saturation metrics via raw API kubectl get --raw /metrics | grep apiserver_flowcontrol_rejected_requests_total
Deploying a synchronous Mutating or ValidatingAdmissionWebhook with failurePolicy: Fail on all Pods (including kube-system) can deadlock cluster recovery if the webhook Pods themselves need to restart.
How do you diagnose and resolve a Pod stuck in Terminating or a node flapping NotReady due to kubelet/PLEG issues?
Senior Engineering Answer
A Pod stuck in Terminating usually indicates an unfulfilled finalizer, an unresponsive container ignoring SIGTERM when terminationGracePeriodSeconds is huge, or a stalled CSI volume unmount on a dead node. Node flapping NotReady with PLEG (Pod Lifecycle Event Generator) errors ('PLEG is not healthy') occurs when the container runtime (containerd) stalls on disk I/O, hung CNI teardown, or overly high Pod density blocking relist calls past the 3-minute threshold.
kubectl describe node worker-07 | grep -A5 Conditions # On node: check kubelet PLEG latency & containerd responsiveness journalctl -u kubelet -n 100 --no-pager | grep -i pleg
Force-deleting a StatefulSet Pod with --grace-period=0 --force while its node is partitioned can cause split-brain corruption because two copies of the Pod mount or write simultaneously.
How do you architect multi-cluster Kubernetes resilience, etcd disaster recovery, and safe control-plane upgrades?
Senior Engineering Answer
Resilient Kubernetes architectures treat clusters as replaceable failure domains rather than stretching a single control plane across high-latency WAN regions (which breaks etcd Raft RTT limits). Multi-cluster setups use GitOps (Argo CD / Flux) to reconcile stateless workloads across regional clusters fronted by DNS/Anycast load balancing, while taking periodic etcd snapshots for single-cluster recovery and performing canary node-group upgrades one minor version at a time with API deprecation checks.
# Snapshot etcd cleanly and verify snapshot integrity before upgrade ETCDCTL_API=3 etcdctl snapshot save /backup/etcd-$(date +%F).db \ --endpoints=https://127.0.0.1:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt \ --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key ETCDCTL_API=3 etcdctl snapshot status /backup/etcd-$(date +%F).db --write-out=table
Restoring an old etcd snapshot into an existing cluster without accounting for external cloud LoadBalancers or dynamically provisioned CSI volumes created after the snapshot leaves orphaned cloud infrastructure and mismatched volume attachments.
Kubernetes (K8s) Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis Kubernetes (K8s) preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Cloud, DevOps & Systems.
Why is a Pod the smallest deployable unit in Kubernetes instead of a single container?
How do Kubernetes Liveness, Readiness, and Startup probes differ, and what goes wrong when they are misconfigured?
What are the differences between ClusterIP, NodePort, LoadBalancer, and Headless Services in Kubernetes?
How do resource requests and limits affect Kubernetes scheduling and OOM/CPU throttling?
How does a Deployment execute zero-downtime rolling updates using maxSurge and maxUnavailable?
When should you use a StatefulSet instead of a Deployment, and how does StatefulSet handle volumes and ordering?
Frequently Asked Technical Interview Questions (Kubernetes (K8s))
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
What is the difference between a Deployment, DaemonSet, and Job in Kubernetes?
How do ConfigMaps and Secrets differ in how Kubernetes stores and mounts them?
Why does a Kubernetes Ingress or Gateway API sit in front of ClusterIP Services?
What is a Graceful Shutdown sequence for a Pod receiving SIGTERM?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.