Scenario Questions
Real-world Kubernetes situations: what you would do, why, and how to say it in an interview
Deployments and rollouts
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 You applied a new image tag and the rollout seems stuck at "1 out of 3 new replicas have been updated". What do you check first?
Beginner
Situation read โ The Deployment controller created one new pod and is waiting for it to become Ready before it continues. The problem is almost always that new pod.
What I'd do โ
kubectl rollout status deploy/webto confirm it is really stuckkubectl get pods -l app=weband find the pod with the newest agekubectl describe pod <new-pod>and read Events at the bottom (ImagePullBackOff, Unschedulable, failed probe)kubectl logs <new-pod> --previousif it is restarting- Fix the cause, or roll back with
kubectl rollout undo deploy/web
Why โ The rolling update honours maxUnavailable and maxSurge, so a broken new pod blocks the rollout while the old pods keep serving. Nothing is down, which buys you time to debug.
Interview tip โ Say that the old ReplicaSet is still serving traffic, so a stuck rollout is not an outage.
Q2 How do you roll back a bad release and verify you are back on the previous version?
Beginner
Situation read โ Production is showing errors right after a deploy and you need the last known-good version now.
What I'd do โ
kubectl rollout history deploy/webto see revisionskubectl rollout undo deploy/web(or--to-revision=3)kubectl rollout status deploy/webkubectl get deploy web -o jsonpath='{.spec.template.spec.containers[0].image}'to confirm the image- Annotate the revision with the reason using
kubectl annotate deploy/web kubernetes.io/change-cause="rollback to v1.4.2"
Why โ Rollback re-applies the pod template of an older ReplicaSet, so it is fast and uses the same rolling strategy. Only the pod template is rolled back, not replicas or other fields.
Interview tip โ Mention revisionHistoryLimit: if it is 0 there is nothing to roll back to.
Q3 A rollout must never reduce capacity below current replicas. How do you configure the strategy?
Intermediate
Situation read โ A latency-sensitive API with 10 replicas that cannot lose capacity during deploys.
What I'd do โ
- Set
strategy.rollingUpdate.maxUnavailable: 0andmaxSurge: 25%(or a number) - Make sure the cluster has headroom for the surge pods or the rollout will hang Pending
- Add a readinessProbe so a new pod only counts as available once it can serve
- Set
minReadySeconds: 10to avoid counting a pod that flaps right after start - Verify with
kubectl rollout statusand watchkubectl get rs -w
Why โ With maxUnavailable 0 the controller must bring up a new Ready pod before it terminates an old one, so serving capacity never drops.
Interview tip โ Point out the trade-off: you need spare capacity for surge, otherwise the rollout stalls.
Q4 You need a blue/green deployment without a service mesh. How do you do it with plain Kubernetes?
Intermediate
Situation read โ The team wants instant cutover and instant rollback for a payments service.
What I'd do โ
- Run two Deployments,
app-blueandapp-green, each with aversionlabel - Point the Service selector at
version: blue - Deploy and test green through a separate Service or port-forward
- Cut over with
kubectl patch svc app -p '{"spec":{"selector":{"app":"app","version":"green"}}}' - Keep blue running until you are confident, then scale it down
Why โ A Service selector is evaluated continuously, so changing it re-points endpoints within seconds and the change is trivially reversible.
Interview tip โ Mention the cost: you run double capacity during the window, and DB schema changes must be backward compatible.
Q5 How would you do a canary release with only Deployments and a Service?
Intermediate
Situation read โ You want 10% of traffic on the new version without Argo Rollouts or a mesh.
What I'd do โ
- Create
app-stablewith 9 replicas andapp-canarywith 1 replica, both carryingapp: web - The Service selects only
app: web, so traffic splits roughly by pod count - Watch error rate and latency of the canary pods in Prometheus
- Scale the canary up and the stable down in steps, or delete the canary on failure
- Finish by updating the stable image and removing the canary
Why โ kube-proxy balances across all ready endpoints, so replica ratio approximates traffic ratio. It is coarse, but needs no extra tooling.
Interview tip โ Say that for exact percentages or header routing you would use Argo Rollouts, Flagger, or Gateway API weights.
Q6 What is the difference between Recreate and RollingUpdate strategies and when would you pick Recreate?
Beginner
Situation read โ A legacy app holds an exclusive lock on a ReadWriteOnce volume and cannot run two versions together.
What I'd do โ
- Use
strategy.type: Recreatefor that Deployment - Expect downtime: all old pods are terminated before new ones start
- Schedule the change in a maintenance window
- Confirm with
kubectl get pods -wthat the old pods are gone before the new ones appear
Why โ RollingUpdate overlaps old and new pods. Apps that cannot tolerate two versions, or share a single-attach volume, need Recreate.
Interview tip โ Mention that a StatefulSet or a proper RWX volume is often the better long-term fix.
Q7 After a deploy, pods are Ready but users get 502s for a few seconds. What is happening and how do you fix it?
Intermediate
Situation read โ Old pods are removed from endpoints and killed while the ingress or load balancer still sends traffic to them.
What I'd do โ
- Add a
preStophook withsleep 10(or uselifecycle.preStop.sleep.secondson recent versions) - Make the app handle SIGTERM: stop accepting new connections, finish in-flight requests
- Set
terminationGracePeriodSecondslarger than preStop plus drain time - Check ingress controller and ALB deregistration delay are not longer than the grace period
- Test with
heyork6during a rollout
Why โ Endpoint removal and SIGTERM happen in parallel. Proxies and load balancers update asynchronously, so the pod must keep serving briefly after it is told to stop.
Interview tip โ This is a classic question; the key phrase is "endpoint propagation races SIGTERM".
Q8 You must deploy a database migration that runs once before the new app version starts. How?
Intermediate
Situation read โ Each release needs a schema migration, and running it from every app pod would race.
What I'd do โ
- Run the migration as a Job (or a Helm
pre-upgradehook) withbackoffLimitandactiveDeadlineSeconds - Use an expand-and-contract migration so the old version still works with the new schema
- Gate the Deployment update on Job completion in CI (
kubectl wait --for=condition=complete job/migrate --timeout=300s) - Avoid init containers for migrations, since every replica would run them
- Keep the migration idempotent and take a backup first
Why โ A Job runs to completion exactly once, and backward-compatible migrations make rollbacks safe.
Interview tip โ Interviewers like hearing "expand, deploy, contract" for zero-downtime schema changes.
Q9 How do you scale a Deployment and what happens if an HPA also manages it?
Beginner
Situation read โ Someone ran kubectl scale deploy web --replicas=2 but replicas keep returning to 6.
What I'd do โ
kubectl get hpato see whether an HPA targets the Deploymentkubectl describe hpa webto read min/max and current metrics- Change
minReplicas/maxReplicason the HPA instead of the Deployment - Remove
replicas:from the manifest in Git so GitOps does not fight the HPA
Why โ The HPA controller owns spec.replicas once attached and overwrites manual changes on its next sync.
Interview tip โ Mention that leaving replicas in the manifest causes a reset on every apply.
Q10 A Deployment rollout hits ProgressDeadlineExceeded. What does it mean and what do you do?
Advanced
ProgressDeadlineExceeded. What does it mean and what do you do?Situation read โ The Deployment condition Progressing=False with reason ProgressDeadlineExceeded after 600s by default.
What I'd do โ
kubectl describe deploy weband read Conditions- Find the blocking pods and read their events and logs
- Remember the controller does not roll back by itself; run
kubectl rollout undoif needed - Tune
progressDeadlineSecondsif the app genuinely needs longer to start - In CI use
kubectl rollout status --timeout=5mto fail the pipeline
Why โ The deadline only marks the rollout as failed for tooling; Kubernetes keeps trying and leaves the half-rolled state in place.
Interview tip โ Distinguish "marked failed" from "rolled back": Kubernetes does neither automatically.
Q11 How do you pause a rollout, make multiple changes, and resume it?
Beginner
Situation read โ You need to change the image, env vars and resources together without triggering three rollouts.
What I'd do โ
kubectl rollout pause deploy/web- Apply
kubectl set image,kubectl set env,kubectl set resources - Confirm no new ReplicaSet was created with
kubectl get rs kubectl rollout resume deploy/web- Watch
kubectl rollout status deploy/web
Why โ Pausing stops the controller from reconciling template changes, so all edits land in a single revision.
Interview tip โ In GitOps you would simply commit one change, but pause is useful during manual incident work.
Q12 What is a ReplicaSet and why do you rarely create one directly?
Beginner
Situation read โ A new teammate asks why kubectl get rs shows several ReplicaSets for one Deployment.
What I'd do โ
kubectl get rs -l app=webto list them- Note that old ReplicaSets are scaled to 0 and kept for rollback
kubectl describe rs <name>shows the owner Deployment- Limit the clutter with
revisionHistoryLimit: 5
Why โ A Deployment owns one ReplicaSet per pod-template revision. Rolling updates are just scaling one up and another down.
Interview tip โ Say you always create Deployments, which add rollout and rollback on top of ReplicaSets.
Q13 You want a rolling update to wait until a new pod has been healthy for 30 seconds. What setting do you use?
Intermediate
Situation read โ Pods pass readiness quickly but crash 15 seconds later because of a lazy-loaded dependency.
What I'd do โ
- Set
minReadySeconds: 30on the Deployment - Keep a realistic readinessProbe that checks dependencies the app needs to serve
- Consider a
startupProbefor slow boots - Watch
kubectl rollout statusto see that availability is delayed
Why โ minReadySeconds tells the controller how long a pod must be Ready, without any container crashing, before it counts as available and the rollout can advance.
Interview tip โ Contrast with readiness: readiness says "can serve now", minReadySeconds says "has stayed healthy".
Q14 Deploys by kubectl apply in CI sometimes revert a hot-fix someone made with kubectl edit. How do you stop this drift?
Intermediate
kubectl apply in CI sometimes revert a hot-fix someone made with kubectl edit. How do you stop this drift?Situation read โ Manual edits in prod are lost at the next pipeline run, and nobody knows why.
What I'd do โ
- Detect drift with
kubectl diff -f manifests/in CI - Adopt GitOps with Argo CD or Flux and enable self-heal/prune so Git is the source of truth
- Restrict
editandpatchfor humans through RBAC, with break-glass access that is audited - Use server-side apply with field managers so ownership is explicit
- Alert when the live state differs from Git
Why โ Client-side apply only merges the fields it knows about from the last-applied annotation, so out-of-band changes either persist silently or get overwritten.
Interview tip โ Say "Git is the source of truth, and humans get read-only in prod".
Q15 How do you make a deployment of 200 pods safe against a bad image without waiting for full rollout?
Advanced
Situation read โ A bad version has taken down services before because you only noticed after the rollout finished.
What I'd do โ
- Use a progressive delivery tool such as Argo Rollouts with canary steps (5%, 25%, 50%, 100%) and pauses
- Define an AnalysisTemplate querying Prometheus for error rate and p99 latency
- Auto-abort and roll back when the analysis fails
- Keep
maxUnavailable: 0and PodDisruptionBudgets in place - Run smoke tests as a pre-promotion analysis step
Why โ Automated analysis between steps limits the blast radius to a small share of traffic and removes the human from the critical path of detection.
Interview tip โ Mention SLO-based gates: promote only if the error budget burn is acceptable.
Q16 How do you ensure a rolling update does not violate availability during node drains at the same time?
Intermediate
Situation read โ The platform team is upgrading nodes while an app team deploys, and the service dipped.
What I'd do โ
- Create a PodDisruptionBudget, for example
minAvailable: 80%ormaxUnavailable: 1 - Run at least 3 replicas spread over zones with
topologySpreadConstraints - Remember PDBs apply to evictions (drain), not to rolling-update deletions
- Coordinate by using
maxUnavailable: 0on the Deployment - Check with
kubectl get pdbthatALLOWED DISRUPTIONSis above 0
Why โ A PDB limits voluntary evictions from drains, while the Deployment strategy limits its own rollout. You need both to be safe in parallel.
Interview tip โ Many candidates think PDB protects against rolling updates; it does not.
Q17 What does kubectl rollout restart do and when do you use it?
Beginner
kubectl rollout restart do and when do you use it?Situation read โ A ConfigMap changed and the app only reads it at startup.
What I'd do โ
kubectl rollout restart deploy/webkubectl rollout status deploy/web- Verify new pods have newer AGE with
kubectl get pods - Prefer a checksum annotation in the pod template (Helm
sha256sum) so config changes trigger rollouts automatically
Why โ The command adds a kubectl.kubernetes.io/restartedAt annotation to the pod template, which creates a new ReplicaSet and a normal rolling update.
Interview tip โ Note it is zero-downtime when probes and strategy are correct, unlike deleting pods by hand.
Q18 You have to run a one-off task and a nightly job. Which workload objects do you use and what settings matter?
Intermediate
Situation read โ Ops wants a nightly report and a one-time data fix in the cluster.
What I'd do โ
- Use a Job for one-off work and a CronJob for scheduled work
- Set
backoffLimit,activeDeadlineSecondsandttlSecondsAfterFinished - On CronJob set
concurrencyPolicy: Forbidto avoid overlapping runs andsuccessfulJobsHistoryLimit - Use
restartPolicy: OnFailureorNever, neverAlways - Test by
kubectl create job --from=cronjob/report manual-1
Why โ Jobs track completions, retries and cleanup, which Deployments do not.
Interview tip โ Mention timeZone field on CronJob (stable since 1.27) to avoid UTC surprises.
Q19 A StatefulSet update does not progress. Pod db-2 is stuck and db-1 and db-0 are old. What is going on?
Intermediate
db-2 is stuck and db-1 and db-0 are old. What is going on?Situation read โ StatefulSets update in reverse ordinal order and wait for each pod to be Running and Ready.
What I'd do โ
kubectl get pods -l app=dbto see which ordinal is blockingkubectl describe pod db-2for events- Check
updateStrategy(RollingUpdate vs OnDelete) andpartition - Fix the pod (probe, image, PVC) because the controller will not skip it
- If the pod is broken by the new template, revert the template and delete the stuck pod
Why โ With the default OrderedReady policy, a StatefulSet halts when one pod is not Ready to protect quorum-based systems.
Interview tip โ Mention partition for staged canary updates of StatefulSets.
Q20 Your team needs one pod on every node for log collection. Which object and what do you watch for?
Beginner
Situation read โ You must ship node logs, including from tainted nodes.
What I'd do โ
- Use a DaemonSet
- Add tolerations for control-plane and other taints the agent must run on
- Set resource requests and a
priorityClassName: system-node-criticalwhere justified - Use
updateStrategy.rollingUpdate.maxUnavailableto control rollout speed - Verify
kubectl get dsshows DESIRED equals READY
Why โ DaemonSet pods are scheduled one per matching node, and taints silently exclude nodes unless tolerated.
Interview tip โ Mention that agents without requests can get evicted first under pressure.
Q21 A Deployment shows READY 0/3 but the image is fine. What are the quick checks?
Beginner
Situation read โ The pods are Running but not Ready.
What I'd do โ
kubectl describe podand look forReadiness probe failedeventskubectl logsto see whether the app started and on what port- Check the probe path and port against the container
containerPort kubectl execandcurl localhost:8080/healthzfrom inside- Fix the probe or the app, then re-apply
Why โ Running means the container process is alive; Ready means the readiness probe passes. Services only send traffic to Ready pods.
Interview tip โ Describe the difference between liveness, readiness and startup probes clearly.
Q22 You need to move a stateless service from one cluster to another with zero downtime. How?
Advanced
Situation read โ A cluster is being retired and traffic must shift gradually.
What I'd do โ
- Deploy the same manifests to the new cluster through GitOps and verify with smoke tests
- Put both clusters behind a shared entry point such as Route 53 weighted records, a global load balancer or a CDN
- Start at 5% to the new cluster and watch error rates
- Increase in steps, keeping DNS TTL low (30-60s)
- Decommission the old cluster only after traffic is zero and connections drain
Why โ Weighted DNS or global load balancing decouples cutover from the clusters themselves and makes rollback a weight change.
Interview tip โ Mention external dependencies: secrets, databases, allowlists, and egress IPs.
Q23 How do you prevent a Deployment from being scheduled all on one node or one zone?
Intermediate
Situation read โ All replicas of a critical service landed on a single node and an outage took them out together.
What I'd do โ
- Add
topologySpreadConstraintswithtopologyKey: topology.kubernetes.io/zoneandmaxSkew: 1 - Add a second constraint on
kubernetes.io/hostname - Choose
whenUnsatisfiable: ScheduleAnywayfor soft,DoNotSchedulefor hard - Verify with
kubectl get pods -o wide - Alternative is
podAntiAffinity
Why โ Spread constraints give even distribution across failure domains and scale better than anti-affinity for large replica counts.
Interview tip โ Mention that spread is evaluated at scheduling time only; a descheduler can rebalance later.
Q24 What is the difference between kubectl apply and kubectl create, and which do you use in pipelines?
Beginner
kubectl apply and kubectl create, and which do you use in pipelines?Situation read โ A pipeline step failed with "AlreadyExists".
What I'd do โ
- Use
kubectl apply -f(declarative) in pipelines - Use
createonly for imperative one-offs, which errors if the object exists - Use
kubectl diffbefore apply to preview - Prefer server-side apply with
--server-sidefor large objects such as CRDs
Why โ apply stores the desired state and merges changes, so it is idempotent. create is a single imperative action.
Interview tip โ Mention annotation size limits (262144 bytes) that break client-side apply on large CRDs.
Q25 A rolling update leaves the Deployment with two ReplicaSets both having pods, and it never converges. Why?
Advanced
Situation read โ Old pods keep getting recreated while new pods fail readiness, and an HPA is also scaling.
What I'd do โ
kubectl get rs -o wideand compare DESIRED, CURRENT, READY per ReplicaSetkubectl describe deployto read events and the scaling messages- Check that the new pods fail readiness and that HPA is not fighting the controller during surge
- Check ResourceQuota for pod count or CPU that blocks the new pods
- Resolve the readiness or quota issue, or roll back
Why โ The Deployment controller will not scale the old RS down below what keeps availability, so a new RS that never becomes Ready freezes the rollout in a mixed state.
Interview tip โ Mention kubectl get events --sort-by=.lastTimestamp as your first move.
Services, Ingress and DNS
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 A Service has no endpoints. How do you find out why?
Beginner
Situation read โ kubectl get endpoints web shows <none> and clients get connection refused or timeouts.
What I'd do โ
kubectl get svc web -o yamland notespec.selectorkubectl get pods --show-labelsand compare labels exactlykubectl get pods -l app=webwith the selector to see if any match- Check the pods are Ready, since only Ready pods become endpoints
- Fix the selector or labels, then
kubectl get endpointslices -l kubernetes.io/service-name=web
Why โ Endpoints are built from pods that match the selector and pass readiness. A typo in one label is the most common cause.
Interview tip โ Mention the Service targetPort mismatch as the second most common cause.
Q27 When do you use ClusterIP, NodePort, LoadBalancer and ExternalName?
Beginner
Situation read โ A developer asks how to expose a new internal API and a public website.
What I'd do โ
- ClusterIP for in-cluster traffic, the default
- NodePort mostly for debugging or when a load balancer sits in front
- LoadBalancer to get a cloud LB per Service, such as an NLB on EKS
- Ingress or Gateway API in front of many HTTP services to share one LB
- ExternalName to alias an external DNS name through a cluster DNS CNAME
Why โ Each type builds on the previous: LoadBalancer includes NodePort, which includes ClusterIP.
Interview tip โ Say that you rarely give every service its own LB in production because of cost.
Q28 Traffic to a Service works from some pods but times out from others. How do you debug it?
Advanced
Situation read โ Only pods on certain nodes fail to reach the ClusterIP.
What I'd do โ
- Run
kubectl run tmp --rm -it --image=nicolaka/netshoot -- bashon the failing node usingnodeName curl -v <clusterIP>:<port>andcurl <podIP>:<targetPort>to separate Service from pod networking- Check kube-proxy on that node with
kubectl -n kube-system logs ds/kube-proxy - On the node inspect
iptables-save | grep <svc>oripvsadm -Ln - Check the CNI pod health and node security groups or firewall
Why โ If pod IP works but ClusterIP does not, the issue is kube-proxy rules. If pod IP fails too, it is the CNI or network policy.
Interview tip โ Separate the layers: pod to pod, pod to Service, external to Service.
Q29 You want to expose three HTTP services under one hostname with different paths. How?
Intermediate
Situation read โ /api, /web and /admin must share app.example.com and one load balancer.
What I'd do โ
- Install an ingress controller such as ingress-nginx or the AWS Load Balancer Controller
- Create an Ingress with
rules.hostand threepathswithpathType: Prefix - Add TLS using a cert-manager Certificate and
tls.secretName - Use annotations only for controller-specific behaviour
- Test with
curl -H 'Host: app.example.com' http://<lb>/api
Why โ One L7 entry point routes by host and path, saving LBs and centralising TLS.
Interview tip โ Mention Gateway API (GA) as the successor with HTTPRoute and role separation.
Q30 ingress-nginx returns 404 for a new host. What do you check?
Intermediate
Situation read โ The Ingress object exists and has an address, but requests return the default backend 404.
What I'd do โ
kubectl describe ingress appand check Rules and Events- Verify
ingressClassNamematches the controller class (kubectl get ingressclass) - Check the backend Service name, port and that it has endpoints
- Curl with the correct Host header, because a 404 usually means no matching host rule
kubectl -n ingress-nginx logs deploy/ingress-nginx-controllerfor config reload errors
Why โ An Ingress with the wrong or missing class is simply ignored by the controller, and a Host mismatch falls through to the default backend.
Interview tip โ Mention the removal of the old kubernetes.io/ingress.class annotation habit in favour of ingressClassName.
Q31 ingress-nginx returns 502 or 503 intermittently. What are the likely reasons?
Intermediate
Situation read โ Errors appear during deploys and under load.
What I'd do โ
- 503 means no ready endpoints for the backend, 502 means the upstream closed or refused
kubectl get endpointsto see readiness gaps- Check pod restarts and OOMKills with
kubectl get pods - Raise
proxy-read-timeoutor fix slow upstreams if you see 504 - Add preStop sleep and graceful shutdown for deploy-time errors
Why โ Ingress sends traffic to pod IPs directly, so any pod that is shutting down or unready can cause 5xx.
Interview tip โ Memorise the mapping: 502 bad upstream, 503 no upstream, 504 upstream timeout.
Q32 A pod cannot resolve my-svc but can reach the pod IP. What do you test first?
Beginner
my-svc but can reach the pod IP. What do you test first?Situation read โ DNS lookups fail inside the cluster.
What I'd do โ
kubectl exec -it app -- nslookup my-svcandcat /etc/resolv.confkubectl get pods -n kube-system -l k8s-app=kube-dnskubectl logs -n kube-system -l k8s-app=kube-dns- Try the FQDN
my-svc.default.svc.cluster.local - Test from a different namespace, since short names only resolve within the same namespace
Why โ The resolv.conf search path includes the pod namespace, so cross-namespace calls need svc.namespace.
Interview tip โ Mention ndots:5 and its effect on lookup volume.
Q33 CoreDNS is slow and the cluster makes thousands of external lookups. How do you reduce the load?
Advanced
Situation read โ Latency spikes and CoreDNS CPU is high, and many queries are for external names with long search-path expansions.
What I'd do โ
- Lower
ndotsin poddnsConfigto 2 for apps that call external hosts, or use trailing-dot FQDNs - Deploy NodeLocal DNSCache as a DaemonSet
- Scale CoreDNS with the cluster-proportional-autoscaler
- Enable the
cacheplugin with a sensible TTL in the Corefile - Watch
coredns_dns_request_duration_secondsin Prometheus
Why โ With ndots:5, an external name like api.stripe.com is tried against four search domains first, multiplying queries.
Interview tip โ Also mention conntrack races on UDP DNS that NodeLocal DNSCache avoids.
Q34 You need a Service reachable from inside a VPC but not the internet on EKS. How?
Intermediate
Situation read โ An internal gRPC service needs a private load balancer.
What I'd do โ
- Set annotation
service.beta.kubernetes.io/aws-load-balancer-scheme: internal - Use
aws-load-balancer-type: externalwithnlb-target-type: ipand the AWS Load Balancer Controller - Ensure private subnets are tagged
kubernetes.io/role/internal-elb=1 - Restrict with security groups
- Verify with
kubectl get svcthat the hostname resolves to private IPs
Why โ The controller reads the subnet tags and annotations to place the LB in the right subnets and scheme.
Interview tip โ Mention that instance target type goes via NodePort, IP mode goes straight to pods.
Q35 How do you route traffic to an external database through a Kubernetes name?
Intermediate
Situation read โ Apps use db.prod.svc and you want to switch between an RDS endpoint and an in-cluster DB without code changes.
What I'd do โ
- Create a Service of
type: ExternalNamewithexternalName: mydb.abc.ap-south-1.rds.amazonaws.com - Apps keep using
db.prod.svc.cluster.local - For IPs, use a Service without selector plus a manual EndpointSlice
- Remember ExternalName does not work well with TLS SNI hostname checks
- Change only the Service to cut over
Why โ The cluster DNS returns a CNAME, which decouples app configuration from the backend location.
Interview tip โ Mention that ExternalName does no proxying and no health checks.
Q36 Session stickiness is required for a legacy app. What are the options?
Intermediate
Situation read โ A stateful web app breaks when requests bounce between pods.
What I'd do โ
- Use
sessionAffinity: ClientIPon the Service withsessionAffinityConfig.clientIP.timeoutSeconds - Prefer ingress cookie affinity such as
nginx.ingress.kubernetes.io/affinity: cookie - With ALB use target group stickiness annotations
- Plan to externalise the session to Redis, which is the real fix
- Test with several clients behind NAT
Why โ ClientIP affinity is weak behind NAT or proxies, because many users share one source IP.
Interview tip โ Say you treat stickiness as a stop-gap and push for stateless sessions.
Q37 You must restrict an app so that only the frontend can call it. Services alone do not do that. What do you add?
Advanced
Situation read โ Any pod in the cluster can call the backend today.
What I'd do โ
- Confirm the CNI enforces NetworkPolicy (Calico, Cilium, or VPC CNI network policy mode)
- Create a default-deny ingress policy in the namespace
- Add an allow policy selecting backend pods and the frontend pod labels (plus namespaceSelector if cross-namespace)
- Allow DNS egress to kube-dns if you also restrict egress
- Test with
kubectl execfrom allowed and denied pods
Why โ Services only provide discovery and load balancing. Isolation requires NetworkPolicy enforced by the CNI.
Interview tip โ Mention that NetworkPolicy objects are silently ignored if the CNI does not implement them.
Q38 What is a headless Service and where do you use it?
Beginner
Situation read โ A StatefulSet needs stable DNS names for each pod.
What I'd do โ
- Set
clusterIP: Noneon the Service - Reference it as
serviceNamein the StatefulSet - Each pod gets
pod-0.svc.ns.svc.cluster.local - Verify with
nslookup svcwhich returns pod IPs rather than a virtual IP - Use for databases, Kafka, and clients that do their own load balancing
Why โ A headless Service skips the virtual IP and returns DNS A records of the pods, giving stable identities.
Interview tip โ Mention that gRPC clients need headless or a mesh because ClusterIP balances per connection.
Q39 gRPC traffic goes to only one pod behind a ClusterIP Service. Why and how do you fix it?
Intermediate
Situation read โ Long-lived HTTP/2 connections get pinned to one backend.
What I'd do โ
- Explain that kube-proxy balances per TCP connection, not per request
- Use a headless Service with client-side load balancing in the gRPC client
- Or put an L7 proxy such as Envoy or a mesh (Linkerd, Istio) in front
- Or use the ALB or ingress with gRPC support
- Set max connection age on servers to force reconnects
Why โ HTTP/2 multiplexes many requests on one connection, so connection-level balancing yields skew.
Interview tip โ Name the concept: L4 vs L7 load balancing.
Q40 You need to expose a non-HTTP TCP service such as Postgres or Kafka externally. What do you do?
Intermediate
Situation read โ Ingress only handles HTTP, but a partner needs TCP access.
What I'd do โ
- Create a
type: LoadBalancerService (NLB on AWS) on the TCP port - Restrict with
loadBalancerSourceRangesand security groups - Use TLS at the app layer
- Or use ingress-nginx TCP services ConfigMap, or a Gateway API TCPRoute
- Prefer PrivateLink or VPN for partners rather than the open internet
Why โ L4 passes bytes through, and needs one LB or one port per service.
Interview tip โ Mention the security angle: never expose a database publicly.
Q41 A new Ingress with TLS serves the controller's default certificate. What is wrong?
Intermediate
Situation read โ Browsers show "Kubernetes Ingress Controller Fake Certificate".
What I'd do โ
kubectl describe ingressto see the TLS section and secret name- Check the secret exists in the same namespace as the Ingress (
kubectl get secret app-tls) and hastls.crtandtls.key - Check the
hostsundertlsmatch the rule host - If using cert-manager,
kubectl describe certificateandkubectl describe challenge - Check controller logs for secret load errors
Why โ The controller falls back to a self-signed default when it cannot find or parse the referenced secret or SNI host.
Interview tip โ Mention that secrets must be in the Ingress namespace.
Q42 How do you test a Service quickly without exposing it?
Beginner
Situation read โ A developer wants to hit an internal service from a laptop.
What I'd do โ
kubectl port-forward svc/web 8080:80curl localhost:8080- For a pod use
kubectl port-forward pod/web-abc 8080:8080 - Use
kubectl execto curl from inside when the issue is in-cluster only - Stop with Ctrl+C
Why โ port-forward tunnels through the API server to a pod, so no Service or LB changes are needed.
Interview tip โ Mention that port-forward to a Service picks one pod and does not load balance.
Q43 NodePort traffic works on one node but not others. What could be wrong?
Intermediate
Situation read โ Service of type NodePort answers on node A's IP but times out on node B.
What I'd do โ
- Check
externalTrafficPolicy(Local only answers on nodes that host a pod) - Check the node security group or firewall allows the 30000-32767 range
kubectl get pods -o wideto see which nodes host pods- Check kube-proxy health on node B
- Use
externalTrafficPolicy: Clusterif you want any node to answer
Why โ With Local, nodes without a local endpoint drop traffic to preserve the client IP.
Interview tip โ Mention health checks used by cloud LBs rely on this behaviour.
Q44 A cloud LB Service is stuck in <pending> for EXTERNAL-IP. What do you check?
Advanced
<pending> for EXTERNAL-IP. What do you check?Situation read โ A LoadBalancer Service never receives an address on EKS.
What I'd do โ
kubectl describe svcand read Events for controller errors- Check the AWS Load Balancer Controller logs:
kubectl -n kube-system logs deploy/aws-load-balancer-controller - Verify IAM permissions via IRSA or Pod Identity
- Verify subnet tags (
kubernetes.io/role/elb) and cluster tag - Check service quotas for NLBs or Elastic IPs
Why โ Something outside Kubernetes (IAM, subnets, quota) is almost always the blocker, and the event on the Service tells you which.
Interview tip โ Mention testing on bare metal: you need MetalLB for LoadBalancer.
Q45 How do you do path-based rewrite for an app that expects to be served from /?
Intermediate
/?Situation read โ You expose /shop but the app serves assets from /.
What I'd do โ
- With ingress-nginx use
nginx.ingress.kubernetes.io/rewrite-target: /$2and path/shop(/|$)(.*)withpathType: ImplementationSpecific - Better, configure the app base path
- Check redirects and absolute asset URLs
- Test with
curl -I - Consider a subdomain instead of paths
Why โ Rewriting handles incoming paths but not links generated by the app, so base-path support in the app is cleaner.
Interview tip โ Say you prefer subdomains to avoid path rewriting complexity.
Q46 Explain how you would migrate from ingress-nginx to Gateway API with no downtime.
Advanced
Situation read โ The community ingress-nginx project is being retired and the platform team wants to move on.
What I'd do โ
- Install a Gateway API implementation (Envoy Gateway, Cilium, or a cloud controller) alongside ingress-nginx
- Translate Ingress resources to Gateway and HTTPRoute objects (tools like ingress2gateway help)
- Create the new Gateway with its own LB and test with Host headers
- Shift DNS weight gradually from the old LB to the new one
- Remove ingress-nginx after traffic is drained and rollback window passes
Why โ Running both in parallel with separate load balancers turns the cutover into a DNS change that can be reversed.
Interview tip โ Show awareness that annotations do not translate one-to-one and need review.
Q47 You want to rate limit and add basic auth at the ingress. How?
Intermediate
Situation read โ A staging site must be protected and API abuse limited.
What I'd do โ
- For ingress-nginx use annotations
nginx.ingress.kubernetes.io/limit-rpsandauth-type: basicwithauth-secret - Create the htpasswd secret with
htpasswd -c auth userandkubectl create secret generic basic-auth --from-file=auth - Use OAuth2 Proxy for real SSO
- Apply WAF at the CDN or ALB layer for serious protection
- Verify with
curl -u user:pass
Why โ Cheap controls at the edge protect the backend before traffic reaches the app.
Interview tip โ Say basic auth is for staging, SSO for production.
Q48 Why does a pod's IP change and how do apps cope?
Beginner
Situation read โ A developer hard-coded a pod IP in config.
What I'd do โ
- Explain pods are ephemeral and get a new IP on recreation
- Use a Service DNS name instead
- For StatefulSets use the stable pod DNS name from the headless Service
- Check with
kubectl get pods -o widebefore and after deleting a pod
Why โ Services provide a stable virtual IP and name over a changing set of pod IPs.
Interview tip โ Short answer: "never address pods directly".
Q49 Two namespaces need to call each other's services but you must keep them isolated otherwise. How?
Intermediate
Situation read โ team-a needs the API in team-b.
What I'd do โ
- Use the FQDN
api.team-b.svc.cluster.local - Add a NetworkPolicy in team-b that allows ingress from namespaces with label
team: ausingnamespaceSelector - Ensure the default deny stays in place
- Allow DNS egress
- Test using a debug pod in team-a
Why โ DNS is global across the cluster, so isolation must be enforced by policy, not naming.
Interview tip โ Mention that namespace selectors rely on the automatic label kubernetes.io/metadata.name.
Q50 Clients see the real source IP as a node IP, not the client IP. How do you preserve it?
Intermediate
Situation read โ An allowlist in the app breaks because every request appears to come from inside the cluster.
What I'd do โ
- For a LoadBalancer or NodePort Service set
externalTrafficPolicy: Local - Or use NLB with proxy protocol and configure the app or ingress to read it
- For ALB read
X-Forwarded-Forand trust only the LB ranges - Make sure the pods are spread so every LB target node has a pod
- Verify with an echo service that prints headers
Why โ Cluster policy SNATs traffic to balance across nodes, which hides the original address.
Interview tip โ Mention the trade-off: Local can create uneven load.
Configuration, Secrets and storage
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 How do you inject configuration into pods and what are the options?
Beginner
Situation read โ A team asks how to pass settings to an app without baking them into the image.
What I'd do โ
- Create a ConfigMap with
kubectl create configmap app-config --from-file=app.properties - Consume it as env vars with
envFromorvalueFrom.configMapKeyRef - Or mount it as files under
volumesandvolumeMounts - Remember env vars need a pod restart, while mounted files update eventually
- Keep secrets in Secret objects, not ConfigMaps
Why โ ConfigMaps decouple config from images, so one image runs in every environment.
Interview tip โ Mention that subPath mounts do not receive updates.
Q52 A ConfigMap was updated but the pod still shows old values. Why?
Intermediate
Situation read โ The change was applied but the app behaves as before.
What I'd do โ
- Check how it is consumed: env vars are fixed at container start
- For mounted files wait for the kubelet sync (up to about a minute) and check with
kubectl exec -- cat /etc/app/config - Check whether
subPathis used, which never updates - Check the app reloads files, since many only read at startup
- Trigger
kubectl rollout restartor use a config checksum annotation
Why โ Kubernetes updates the projected files, but it cannot make a process re-read them.
Interview tip โ Say Reloader or a checksum annotation makes it automatic.
Q53 How do you store a database password safely in Kubernetes?
Beginner
Situation read โ A repo contains a plain-text password in a manifest.
What I'd do โ
- Rotate the exposed password immediately
- Store it with
kubectl create secret generic db --from-literal=password=...or better through an external manager - Use External Secrets Operator or the Secrets Store CSI driver with AWS Secrets Manager
- Mount as a file or env var in the pod
- Enable encryption at rest for etcd and restrict Secret RBAC
Why โ Secrets are base64 encoded, not encrypted, so the real protection is encryption at rest, RBAC, and keeping values out of Git.
Interview tip โ Say "base64 is not encryption" early.
Q54 How do you manage secrets in GitOps without committing them in plain text?
Intermediate
Situation read โ Argo CD syncs from Git but the secrets must not be in the repo.
What I'd do โ
- Use External Secrets Operator: a
SecretStorepoints to AWS Secrets Manager and anExternalSecretcreates the Secret - Or use Sealed Secrets: encrypt with
kubesealand commit the SealedSecret - Or SOPS with KMS and the Argo CD or Flux integration
- Restrict who can read the resulting Secret
- Plan rotation: ESO refreshes on
refreshInterval
Why โ References or encrypted payloads are safe in Git, and the cluster resolves them at runtime.
Interview tip โ Mention the trade-off: ESO needs access to the secret store, Sealed Secrets keeps the key in the cluster.
Q55 A pod fails with CreateContainerConfigError and a missing key. What happened?
Beginner
CreateContainerConfigError and a missing key. What happened?Situation read โ Event says couldn't find key DB_HOST in ConfigMap default/app-config.
What I'd do โ
kubectl describe podand read the messagekubectl get cm app-config -o yamlto see actual keys- Fix the key name or add the key
- Use
optional: trueonly if the value is truly optional - Re-create the pod or let the Deployment retry
Why โ The kubelet cannot build the container environment when a referenced key or object is missing.
Interview tip โ Same error appears for missing Secrets.
Q56 What is the difference between emptyDir, hostPath, PV/PVC and when do you use each?
Beginner
Situation read โ A developer wants scratch space and persistent storage.
What I'd do โ
- emptyDir for scratch data shared across containers in a pod, lost with the pod
- hostPath mounts a node directory; avoid it except for node agents
- PVC through a StorageClass for durable data
- For memory-backed scratch use
emptyDir.medium: Memorywith asizeLimit - Choose by durability and portability needs
Why โ Storage lifetime differs: pod, node, or independent of both.
Interview tip โ Mention hostPath as a security risk and a PSA baseline violation.
Q57 A StatefulSet's PVC stays Pending. How do you debug?
Intermediate
Situation read โ kubectl get pvc shows Pending for data-db-0.
What I'd do โ
kubectl describe pvc data-db-0and read Eventskubectl get storageclassto confirm a default class or the named class exists- Check
volumeBindingMode: WaitForFirstConsumer, which keeps PVCs Pending until a pod is scheduled - Check the CSI driver pods and IAM permissions on EKS
- Check zone and capacity constraints
Why โ A PVC is bound only when a PV exists or can be provisioned, and the binding mode may delay that on purpose.
Interview tip โ Mention WaitForFirstConsumer prevents zone mismatch on EBS.
Q58 A pod on EKS cannot attach an EBS volume: Multi-Attach error or volume in a different zone. Explain.
Advanced
Multi-Attach error or volume in a different zone. Explain.Situation read โ A rescheduled pod is stuck ContainerCreating with a volume error.
What I'd do โ
kubectl describe podand read the AttachVolume events- EBS is zonal and ReadWriteOnce, so the pod must be in the same AZ as the volume
- Multi-Attach means the old node still holds the volume, so wait for detach or check the old pod is gone
- Use
topologySpreadConstraintsor nodeAffinity for the zone - Consider EFS for shared RWX
Why โ EBS volumes attach to one instance in one AZ, so scheduling must respect that.
Interview tip โ Mention WaitForFirstConsumer and zone-aware node groups.
Q59 You need to resize a PVC. How?
Beginner
Situation read โ A database volume is 90% full.
What I'd do โ
- Verify the StorageClass has
allowVolumeExpansion: true kubectl patch pvc data -p '{"spec":{"resources":{"requests":{"storage":"200Gi"}}}}'- Watch
kubectl get pvcand the conditionFileSystemResizePending - Online expansion works for most CSI drivers without restarting the pod
- Remember you cannot shrink a PVC
Why โ The CSI driver expands the backing volume and the kubelet grows the filesystem.
Interview tip โ Mention EBS limit: one modification per volume every 6 hours.
Q60 How do you take backups and restore stateful workloads on Kubernetes?
Advanced
Situation read โ The business needs RPO below 1 hour for a database on Kubernetes.
What I'd do โ
- Use database-native backups (pg_dump, pgBackRest, WAL archiving to S3) as the primary method
- Use CSI VolumeSnapshots for crash-consistent snapshots with a
VolumeSnapshotClass - Use Velero for namespace-level backups of objects and PV snapshots
- Test restores regularly into a scratch cluster
- Store backups in a separate account and region
Why โ Snapshots alone can be inconsistent for databases, and untested backups are not backups.
Interview tip โ Mention an operator such as CloudNativePG which automates this.
Q61 A pod needs a read-only config file and a writable temp dir, with readOnlyRootFilesystem: true. How?
Intermediate
readOnlyRootFilesystem: true. How?Situation read โ The security team requires an immutable container filesystem.
What I'd do โ
- Set
securityContext.readOnlyRootFilesystem: true - Mount ConfigMap files with
readOnly: true - Add
emptyDirvolumes for/tmpand any cache directories the app writes - Check logs for "Read-only file system" errors and add paths accordingly
- Verify with
kubectl exec -- touch /x
Why โ Immutable roots limit what an attacker can persist, and emptyDir gives the app the few writable paths it needs.
Interview tip โ Good place to mention runAsNonRoot and dropping capabilities too.
Q62 What is the difference between a PV, a PVC, and a StorageClass?
Beginner
Situation read โ A newcomer is confused by three storage objects.
What I'd do โ
- PV is the actual storage resource
- PVC is a request for storage by a user
- StorageClass defines how to dynamically provision PVs (provisioner, parameters, reclaim policy)
- Check with
kubectl get pv,pvc,sc - In practice you create PVCs and dynamic provisioning creates PVs
Why โ The split separates admin concerns from developer requests.
Interview tip โ Draw the binding relationship if there is a whiteboard.
Q63 You deleted a StatefulSet and its PVCs remain. Is this expected, and how do you control it?
Intermediate
Situation read โ Storage costs are growing from orphaned volumes.
What I'd do โ
- Yes, StatefulSet PVCs are retained by default
- Use
persistentVolumeClaimRetentionPolicywithwhenDeleted: DeleteandwhenScaled: Retainwhere appropriate - Check PV
reclaimPolicy(Delete or Retain) on the StorageClass - List orphaned volumes with
kubectl get pvc -Aand cloud tags - Clean up deliberately
Why โ The default favours data safety over cost.
Interview tip โ Say you tag volumes by cluster to find orphans.
Q64 How do you share a volume between multiple pods across nodes?
Intermediate
Situation read โ Several web pods need the same uploads directory.
What I'd do โ
- Use a ReadWriteMany capable backend such as EFS, NFS or CephFS
- On EKS install the EFS CSI driver and create a StorageClass with
provisioningMode: efs-ap - Create a PVC with
accessModes: ReadWriteMany - Better, move uploads to S3 object storage
- Test concurrent writes and locking behaviour
Why โ EBS is RWO only, so cross-node sharing needs a network filesystem or object storage.
Interview tip โ Mention that object storage is usually the cleaner design.
Q65 A node is lost and a StatefulSet pod with an EBS volume does not reschedule for 6 minutes or more. Why?
Advanced
Situation read โ Data pod is stuck Terminating on a NotReady node and the replacement pod waits.
What I'd do โ
- The node controller marks the pod for deletion but the kubelet cannot confirm termination
- StatefulSets guarantee at-most-one pod with that identity, so they will not start the replacement until the old one is gone
- Check the volume attachment with
kubectl get volumeattachment - If the node is confirmed dead,
kubectl delete pod --force --grace-period=0or use the out-of-service taintnode.kubernetes.io/out-of-service=nodeshutdown:NoExecute - Fix node health detection and use shorter tolerations
Why โ At-most-one semantics protect against two writers on the same data, so Kubernetes waits for proof the old one is dead.
Interview tip โ Explain the out-of-service taint, it shows depth.
Q66 Your app needs files from S3 mounted like a filesystem. What are the options?
Intermediate
Situation read โ A legacy tool expects local paths for large datasets.
What I'd do โ
- Use the Mountpoint for Amazon S3 CSI driver for read-heavy workloads
- Or sync with an init container using
aws s3 sync - Use IRSA or Pod Identity for access, not static keys
- Know that S3 is not POSIX: no random writes
- Prefer SDK access in new applications
Why โ Mountpoint gives file-like reads without copying, but semantics differ from a real filesystem.
Interview tip โ Call out the POSIX limitation.
Q67 How can you see which pods use a PVC before deleting it?
Beginner
Situation read โ A PVC stuck in Terminating after delete.
What I'd do โ
kubectl describe pvc datashowsUsed Bykubectl get pods -A -o json | jqfor claimName matching- Delete or scale down the pods using it
- The
kubernetes.io/pvc-protectionfinalizer clears once no pod uses it - Verify with
kubectl get pvc
Why โ Storage protection finalizers stop in-use claims from being deleted.
Interview tip โ Do not patch finalizers off before checking for users.
Q68 How do you inject a Secret as a file with strict permissions?
Intermediate
Situation read โ An app needs a TLS key file readable only by its user.
What I'd do โ
- Mount the Secret as a volume with
defaultMode: 0400 - Set
securityContext.fsGroupandrunAsUserso the file is readable by the process - Prefer files over env vars, since env vars leak in
/procand crash dumps - Verify with
kubectl exec -- ls -l /etc/tls - Rotate by updating the Secret; mounted files refresh
Why โ File mounts have permissions and are updated automatically, env vars have neither.
Interview tip โ Mention that mode in YAML is octal in YAML 1.1 but decimal in JSON.
Q69 You want immutable ConfigMaps and Secrets. Why and how?
Intermediate
Situation read โ Accidental config edits keep causing incidents and kubelet watch load is high.
What I'd do โ
- Set
immutable: trueon the ConfigMap or Secret - Version names like
app-config-v7and update the Deployment reference - Roll out and roll back through Deployment revisions
- Helm and Kustomize
configMapGeneratoradd hashes automatically - Delete old versions later
Why โ Immutability prevents accidental change and reduces API server watches.
Interview tip โ Mention Kustomize hash suffix as the easy route.
Q70 How do you encrypt Secrets at rest in etcd and rotate the key?
Advanced
Situation read โ The audit requires encrypted Secret data in etcd.
What I'd do โ
- Create an
EncryptionConfigurationwith akmsprovider (AWS KMS v2) first andidentitylast - Pass it with
--encryption-provider-configon kube-apiserver (on EKS enable envelope encryption in the cluster) - Re-encrypt existing data:
kubectl get secrets -A -o json | kubectl replace -f - - Rotate by adding the new key first, restart apiservers, re-encrypt, then remove the old key
- Verify with
etcdctl getshowing thek8s:enc:prefix
Why โ The order of providers decides which encrypts, and all providers listed can decrypt, which makes rotation safe.
Interview tip โ Say that on EKS this is a cluster setting backed by a KMS key.
Q71 How do you pass a different config per environment with one set of manifests?
Intermediate
Situation read โ Dev, staging and prod differ only in replicas, hostnames and limits.
What I'd do โ
- Use Kustomize with
base/andoverlays/dev|staging|prod - Patch values with
patchesandconfigMapGenerator - Or Helm with one
values-<env>.yamlper environment - Render with
kustomize build overlays/prodorhelm templatein CI - Validate with
kubeconform
Why โ Base plus overlays keeps duplication low and differences reviewable.
Interview tip โ Say you never copy-paste manifests per environment.
Q72 What happens to data in an emptyDir when a container crashes versus when the pod is deleted?
Beginner
Situation read โ A teammate expects emptyDir data to survive restarts.
What I'd do โ
- Container restart: data survives because the volume belongs to the pod
- Pod deleted or rescheduled: data is gone
- Verify with
kubectl execwriting a file, killing the process, and reading again - Use a PVC for durable data
Why โ emptyDir lifetime equals pod lifetime.
Interview tip โ Short and precise answers score well here.
Q73 A pod mounting an NFS or EFS volume hangs on startup in ContainerCreating. What do you check?
Intermediate
Situation read โ MountVolume.SetUp failed ... mount.nfs: Connection timed out.
What I'd do โ
- Check the security group on the EFS mount targets allows port 2049 from the nodes
- Check mount targets exist in each AZ used by nodes
- Check the CSI driver pods and the node has
nfs-utilsor the driver - Check DNS resolution of the filesystem ID from the node
- Test
nc -zv <mount-target-ip> 2049from the node
Why โ A mount timeout is nearly always network reachability on port 2049.
Interview tip โ Mention that stuck NFS mounts can also hang node shutdown.
Resources, autoscaling and scheduling
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q74 How do you choose requests and limits for a new service?
Beginner
Situation read โ A new API goes live next week and nobody knows its footprint.
What I'd do โ
- Load test in staging and record usage with
kubectl top podand Prometheus - Set requests near p90 usage and memory limit with 20-30% headroom
- Be cautious with CPU limits, since they cause throttling
- Use the Vertical Pod Autoscaler in recommendation mode to refine
- Review after two weeks of production data
Why โ Requests drive scheduling and QoS, limits cap usage. Wrong values cause either waste or evictions.
Interview tip โ Say you start from measurements, not guesses.
Q75 Pods are Pending with 0/6 nodes are available: 6 Insufficient cpu. What do you do?
Intermediate
0/6 nodes are available: 6 Insufficient cpu. What do you do?Situation read โ A new Deployment cannot schedule though nodes look idle in the dashboard.
What I'd do โ
kubectl describe podto read the scheduling messagekubectl describe nodes | grep -A8 "Allocated resources"to see requested versus allocatable- Compare to actual use with
kubectl top nodes - Right-size inflated requests, or add nodes (Cluster Autoscaler or Karpenter)
- Check that quotas and LimitRanges are not injecting large defaults
Why โ The scheduler works on requests, not live usage, so a cluster can look idle yet be full.
Interview tip โ This distinction is asked constantly.
Q76 Explain QoS classes and which pods get evicted first.
Intermediate
Situation read โ Under node memory pressure, important pods got killed before batch jobs.
What I'd do โ
- Guaranteed: requests equal limits for CPU and memory in every container
- Burstable: at least one request or limit set
- BestEffort: none set
- Eviction order is BestEffort, then Burstable exceeding requests, then Guaranteed last
- Check with
kubectl get pod -o jsonpath='{.status.qosClass}'
Why โ The kubelet ranks pods by QoS and usage over requests, and OOM scores follow the same ordering.
Interview tip โ Mention system-node-critical priority for agents.
Q77 CPU limits cause latency spikes though average usage is low. Why and what is the fix?
Intermediate
Situation read โ p99 latency is bad while CPU usage graphs look fine.
What I'd do โ
- Check
container_cpu_cfs_throttled_periods_totalin Prometheus - CFS quota throttles in 100ms periods, so bursts hit the limit even at low average
- Remove or raise CPU limits and keep accurate requests
- Keep memory limits
- Re-measure p99 after the change
Why โ Throttling is per period, not per average, so spiky services are hurt.
Interview tip โ Say many teams run CPU requests without limits.
Q78 How do you configure an HPA on CPU?
Beginner
Situation read โ Traffic varies during the day and you want automatic scaling.
What I'd do โ
- Ensure metrics-server runs:
kubectl top pods - Set CPU requests on the Deployment, since utilisation is relative to requests
kubectl autoscale deploy web --cpu-percent=70 --min=3 --max=20- Check with
kubectl get hpaandkubectl describe hpa web - Load test and watch scaling events
Why โ HPA computes desired replicas from current metric divided by target.
Interview tip โ Remember: no requests means HPA shows <unknown>.
Q79 HPA shows <unknown>/70% for CPU. What do you do?
Intermediate
<unknown>/70% for CPU. What do you do?Situation read โ The HPA never scales and TARGETS is unknown.
What I'd do โ
kubectl describe hpaand read the conditions (FailedGetResourceMetric)kubectl top podsto test metrics-server- Confirm the pods define
resources.requests.cpu - Check
kubectl get apiservice v1beta1.metrics.k8s.iois Available - On EKS check that metrics-server is installed and security groups allow its port
Why โ HPA needs both a working Metrics API and requests to compute utilisation.
Interview tip โ Name the three failure points: metrics-server, requests, APIService.
Q80 You need to scale on queue length or requests per second, not CPU. How?
Intermediate
Situation read โ A worker Deployment should scale on SQS depth.
What I'd do โ
- Install KEDA
- Create a
ScaledObjectwith an SQS trigger andqueueLength - Use IRSA for access
- Allow scale to zero with
minReplicaCount: 0where acceptable - Check
kubectl get hpasince KEDA creates an HPA behind the scenes
Why โ External metrics reflect real load for async workers better than CPU.
Interview tip โ Mention Prometheus Adapter as the other route for custom metrics.
Q81 Your HPA flaps between 5 and 20 replicas every few minutes. How do you stabilise it?
Advanced
Situation read โ Oscillating replicas cause cold starts and cost.
What I'd do โ
- Set
behavior.scaleDown.stabilizationWindowSeconds: 300 - Limit rate with
policies(for example 2 pods per 60s on scale down) - Use a more stable metric, for example averaged requests per second
- Fix slow startup with startup probes so new pods count correctly
- Review target utilisation
Why โ Stabilisation windows make the HPA use the highest recommendation in the window, so it scales down slowly.
Interview tip โ Mention autoscaling/v2 behavior field.
Q82 Pods are Pending, the Cluster Autoscaler does not add nodes. Why?
Intermediate
Situation read โ The ASG has capacity but no scale-up happens.
What I'd do โ
kubectl -n kube-system logs deploy/cluster-autoscalerand look for "didn't trigger scale-up" reasons- Check the pod can fit on any node group (nodeSelector, taints, zone or PVC constraints)
- Check max size of the node group and service quotas
- Check the ASG tags
k8s.io/cluster-autoscaler/enabled - Check IAM permissions
Why โ The autoscaler simulates scheduling against node group templates, and any mismatch stops scale-up.
Interview tip โ Mention Karpenter's different model of picking instance types directly.
Q83 Why choose Karpenter over Cluster Autoscaler and what must you configure?
Advanced
Situation read โ Node costs are high and scale-up takes minutes with fixed instance types.
What I'd do โ
- Install Karpenter with IAM roles and an interruption queue
- Define a
NodePoolwith requirements (capacity types spot and on-demand, instance families, zones) and limits - Define an
EC2NodeClassfor AMI, subnets and security groups - Set
disruption.consolidationPolicyand budgets - Observe with
kubectl get nodeclaims
Why โ Karpenter provisions right-sized instances directly for pending pods and consolidates underused ones.
Interview tip โ Say you set NodePool limits to cap runaway cost.
Q84 How do you run workloads on spot instances safely?
Intermediate
Situation read โ Compute cost must drop by 50% for stateless services.
What I'd do โ
- Run multiple instance types and AZs in the node group or NodePool
- Taint spot nodes and tolerate them only in interruption-tolerant workloads
- Handle SIGTERM with a graceful shutdown (spot gives two minutes)
- Use PDBs and enough replicas
- Keep a baseline on on-demand capacity
Why โ Spot is reclaimed with short notice, so the design must tolerate loss.
Interview tip โ Mention the AWS Node Termination Handler or Karpenter's interruption handling.
Q85 How do you force a pod onto GPU nodes only?
Beginner
Situation read โ ML pods keep landing on regular nodes.
What I'd do โ
- Label and taint GPU nodes, for example
kubectl taint nodes gpu-1 nvidia.com/gpu=present:NoSchedule - Request
resources.limits.nvidia.com/gpu: 1 - Add a toleration and a nodeSelector or affinity
- Install the NVIDIA device plugin
- Check with
kubectl describe node | grep nvidia
Why โ Taints repel normal pods, tolerations plus selectors attract the intended ones.
Interview tip โ Remember a toleration alone does not attract pods.
Q86 Explain node affinity, pod affinity and anti-affinity with a real use.
Intermediate
Situation read โ A cache should sit close to its app, while replicas must not share a node.
What I'd do โ
- Use
nodeAffinityto target node labels such as instance type - Use
podAffinitywithtopologyKey: kubernetes.io/hostnameto co-locate app and cache - Use
podAntiAffinityto spread replicas - Prefer
preferredDuringSchedulingIgnoredDuringExecutionfor soft rules - Verify with
kubectl get pods -o wide
Why โ Required rules can block scheduling, preferred rules only bias it.
Interview tip โ Note the cost of anti-affinity at large scale.
Q87 A namespace hits its ResourceQuota and new pods fail. What do you see and do?
Intermediate
Situation read โ Deployments cannot create pods, with exceeded quota errors.
What I'd do โ
kubectl describe quota -n team-ato see used versus hardkubectl describe rs <name>events showforbidden: exceeded quota- Right-size workloads or raise the quota through the platform process
- Note that quotas on requests require every pod to declare requests
- Add a LimitRange for defaults
Why โ Quota failures appear on the ReplicaSet, not on the Deployment, which confuses people.
Interview tip โ Mention that quota also limits object counts, such as services of type LoadBalancer.
Q88 What does a LimitRange do and why combine it with ResourceQuota?
Beginner
Situation read โ A namespace has pods without requests and the quota rejects them.
What I'd do โ
- Create a
LimitRangewithdefault,defaultRequest,minandmax - Apply with
kubectl apply -fin the namespace - Check an unconfigured pod gets defaults via
kubectl get pod -o yaml - Keep ResourceQuota for the namespace total
- Document the defaults for developers
Why โ LimitRange sets per-pod defaults and bounds, quota sets the total.
Interview tip โ Say it prevents both unbounded pods and huge single pods.
Q89 Explain pod priority and preemption. When did you use it?
Advanced
Situation read โ An important payment service could not schedule because batch jobs filled the cluster.
What I'd do โ
- Create
PriorityClassobjects, for examplecriticalat 100000 andbatchat 100 - Reference with
priorityClassName - The scheduler preempts lower-priority pods to fit higher ones
- Set
preemptionPolicy: Neverfor pods that should queue but not evict - Protect with PDBs, although preemption tries but may violate them
Why โ Priority gives deterministic behaviour under scarcity.
Interview tip โ Warn that overusing high priority makes everything critical.
Q90 A DaemonSet pod stays Pending on one node. Why?
Intermediate
Situation read โ One node has no log agent.
What I'd do โ
kubectl describe podand read the scheduling reason- Check node taints versus tolerations
- Check node allocatable resources, since DaemonSet pods still need room
- Check the nodeSelector against node labels
- Free space or add the toleration
Why โ DaemonSet pods use normal scheduling constraints through node affinity.
Interview tip โ Mention priority classes for agents.
Q91 Memory usage of a Java service in a pod is much higher than the heap. How do you size it?
Advanced
Situation read โ The pod is OOMKilled although -Xmx is 2g and the limit is 2.5g.
What I'd do โ
- Remember JVM memory includes metaspace, thread stacks, direct buffers and code cache
- Set
-XX:MaxRAMPercentage=70instead of a fixed Xmx - Set the limit with 30% headroom
- Check usage with
kubectl topand JVM NMT - Use
kubectl describe podto confirmReason: OOMKilled, exit code 137
Why โ Container limits include all process memory, not just heap.
Interview tip โ Mention container-aware JVMs since version 10.
Q92 How would you right-size a cluster that runs at 15% real CPU utilisation?
Intermediate
Situation read โ Finance asks why the cluster is expensive.
What I'd do โ
- Compare requests to usage per workload with Prometheus or Kubecost
- Apply VPA recommendations or reduce requests
- Enable bin-packing with Karpenter consolidation or Cluster Autoscaler scale-down
- Move batch to spot
- Review quotas and idle namespaces
Why โ Waste comes mostly from over-requested resources, not from missing nodes.
Interview tip โ Quote a saving you achieved and how you measured it.
Q93 What is the Vertical Pod Autoscaler and when do you not use it with HPA?
Beginner
Situation read โ A team wants automatic resource tuning.
What I'd do โ
- Install VPA and create a
VerticalPodAutoscalerwithupdateMode: "Off"to get recommendations - Read them with
kubectl describe vpa - Use
Autoonly for workloads that tolerate restarts - Do not let VPA and HPA both act on CPU for the same Deployment
- Consider in-place resize in recent Kubernetes versions
Why โ VPA changes requests, which would feed back into HPA's utilisation maths.
Interview tip โ Start with recommendation mode.
Q94 How do you drain a node safely for maintenance?
Beginner
Situation read โ A node needs kernel patching.
What I'd do โ
kubectl cordon node-1kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data- Watch for PDB-blocked evictions and fix them
- Patch and reboot
kubectl uncordon node-1
Why โ Drain evicts pods through the Eviction API, honouring PDBs and grace periods.
Interview tip โ Mention that bare pods are not rescheduled.
Q95 A drain hangs forever on Cannot evict pod as it would violate the pod's disruption budget. What now?
Advanced
Cannot evict pod as it would violate the pod's disruption budget. What now?Situation read โ A PDB with minAvailable equal to replicas blocks every eviction.
What I'd do โ
kubectl get pdb -Aand check ALLOWED DISRUPTIONS equals 0- Check the workload has too few replicas or unhealthy pods
- Fix the PDB (use
maxUnavailable: 1) or scale up first - Never force-delete as a habit
- As a last resort use
--disable-evictionknowing it bypasses PDBs
Why โ A PDB that allows zero disruptions makes the workload undrainable.
Interview tip โ Say PDBs need to be reviewed in platform onboarding.
Q96 Pods land unevenly: some nodes are overloaded, others idle. What can you do?
Intermediate
Situation read โ The scheduler placed pods well initially but nodes drifted.
What I'd do โ
- Check requests vs real usage per node
- Add
topologySpreadConstraints - Run the Descheduler to evict pods violating policies
- Ensure every pod has realistic requests
- Consider the scheduler profile
MostAllocatedorLeastAllocateddepending on goals
Why โ The scheduler decides only at scheduling time and never moves running pods.
Interview tip โ Mention descheduler as the rebalancer.
Security, RBAC and policy
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q97 A developer needs read-only access to one namespace. How do you grant it?
Beginner
Situation read โ A new joiner should view pods and logs in staging only.
What I'd do โ
- Use the built-in
viewClusterRole bound with a RoleBinding:kubectl create rolebinding dev-view --clusterrole=view [email protected] -n staging - Bind groups rather than users when using SSO
- Test with
kubectl auth can-i list pods -n staging --as [email protected] - Confirm secrets are not readable:
can-i get secrets - On EKS map IAM identities with access entries
Why โ A RoleBinding scopes a ClusterRole to a single namespace.
Interview tip โ Say least privilege and group-based bindings.
Q98 Explain the difference between Role, ClusterRole, RoleBinding and ClusterRoleBinding.
Intermediate
Situation read โ An audit finds a ClusterRoleBinding where a RoleBinding was intended.
What I'd do โ
- Role grants permissions inside a namespace
- ClusterRole grants cluster-wide or can be reused across namespaces
- RoleBinding grants a Role or ClusterRole within one namespace
- ClusterRoleBinding grants cluster-wide
- Audit with
kubectl get clusterrolebindings -o wideandkubectl who-can/rbac-tool
Why โ Binding scope decides how far the permissions reach, not the role kind.
Interview tip โ Mention aggregated ClusterRoles.
Q99 A CI pipeline needs to deploy to one namespace. What identity do you give it?
Intermediate
Situation read โ The pipeline currently uses a cluster-admin kubeconfig.
What I'd do โ
- Create a ServiceAccount
ci-deployerin the namespace - Grant a Role limited to deployments, services, configmaps with verbs get, list, create, update, patch
- Use short-lived tokens through OIDC federation (GitHub Actions to IAM to EKS) rather than long-lived secrets
- Verify with
kubectl auth can-i --list --as system:serviceaccount:app:ci-deployer -n app - Rotate and audit
Why โ Short-lived, scoped credentials limit damage when a pipeline is compromised.
Interview tip โ Say never cluster-admin in CI.
Q100 What does a ServiceAccount do and why should you disable the token automount?
Beginner
Situation read โ Pods do not call the API but carry a token.
What I'd do โ
- Set
automountServiceAccountToken: falseon pods or ServiceAccounts that do not need the API - Create dedicated ServiceAccounts per workload
- Check with
kubectl exec -- ls /var/run/secrets/kubernetes.io/serviceaccount - Use bound, projected tokens (default now)
- Do not use the
defaultServiceAccount for anything
Why โ A token in a compromised pod is a foothold into the API server.
Interview tip โ Mention bound tokens expire.
Q101 How do you let pods on EKS access S3 without static keys?
Intermediate
Situation read โ Developers put AWS keys in Secrets.
What I'd do โ
- Use IRSA: associate an OIDC provider with the cluster and create an IAM role trusted by the ServiceAccount
- Annotate the ServiceAccount with
eks.amazonaws.com/role-arn - Or use EKS Pod Identity with
aws eks create-pod-identity-association - Scope the IAM policy to the bucket
- Verify with
aws sts get-caller-identityinside the pod
Why โ The pod receives temporary credentials via web identity, no secrets to rotate.
Interview tip โ Pod Identity is simpler across clusters.
Q102 A pod has access to the node's IAM role through IMDS. How do you prevent credential theft?
Advanced
Situation read โ A compromised pod can query 169.254.169.254 and use node permissions.
What I'd do โ
- Enforce IMDSv2 with hop limit 1 on node launch templates
- Use IRSA or Pod Identity for workload permissions
- Block
169.254.169.254with a NetworkPolicy for pods that do not need it - Keep the node role minimal
- Detect with GuardDuty EKS protection
Why โ Hop limit 1 stops containers from reaching IMDS through the extra network hop.
Interview tip โ Credential theft via IMDS is a classic cloud breach path.
Q103 How do you enforce a default-deny network posture in a namespace?
Intermediate
Situation read โ Compliance requires that pods only talk to what they need.
What I'd do โ
- Apply a policy with
podSelector: {}andpolicyTypes: [Ingress, Egress] - Add explicit allows for DNS (UDP/TCP 53 to kube-dns)
- Add allows per app (frontend to backend, backend to DB)
- Test with
kubectl exec ... -- nc -zv - Use Cilium or Calico flow logs to find missing rules
Why โ Default deny turns the model from allow-all to allow-listed.
Interview tip โ Say DNS egress is the thing everyone forgets.
Q104 How do you stop privileged containers and hostPath mounts cluster-wide?
Intermediate
Situation read โ A team tried to run a privileged pod in prod.
What I'd do โ
- Use Pod Security Admission by labelling namespaces:
kubectl label ns prod pod-security.kubernetes.io/enforce=restricted - Roll out with
warnandauditmodes first - For finer rules use Kyverno or OPA Gatekeeper
- Exempt only system namespaces
- Test with a dry run:
kubectl label --dry-run=server --overwrite ns prod pod-security.kubernetes.io/enforce=baseline
Why โ PSA gives three profiles (privileged, baseline, restricted) that replace PodSecurityPolicy.
Interview tip โ Know that PSP was removed in 1.25.
Q105 What is the difference between PSA and Kyverno or Gatekeeper?
Intermediate
Situation read โ The security team asks whether PSA is enough.
What I'd do โ
- PSA is built in with fixed profiles per namespace
- Kyverno and Gatekeeper add custom policies such as required labels, allowed registries, mandatory limits
- Kyverno also mutates and generates resources
- Use ValidatingAdmissionPolicy (CEL) for lightweight in-tree rules
- Run policies in audit mode before enforce
Why โ Different layers: PSA for baseline pod hardening, policy engines for organisation rules.
Interview tip โ Mention ValidatingAdmissionPolicy GA.
Q106 You must allow only images from your private registry and signed by your pipeline. How?
Advanced
Situation read โ Developers can pull anything from the internet today.
What I'd do โ
- Use a Kyverno
verifyImagespolicy with cosign keys or keyless OIDC identities - Or use Sigstore policy-controller
- Restrict registries with a validating policy on
spec.containers[*].image - Sign in CI with
cosign sign - Reference digests rather than tags
Why โ Admission-time verification makes the supply-chain rule enforceable.
Interview tip โ Mention SBOMs and attestations.
Q107 How do you check who can do what in a cluster?
Beginner
Situation read โ Someone asks whether a ServiceAccount can delete pods.
What I'd do โ
kubectl auth can-i delete pods -n app --as system:serviceaccount:app:builderkubectl auth can-i --list -n appkubectl get rolebindings,clusterrolebindings -A -o wide- Use
kubectl-who-canorrbac-lookupplugins - Review regularly
Why โ can-i evaluates the real authorizer, including aggregated roles.
Interview tip โ Mention impersonation permissions.
Q108 A pod can create other pods in its namespace. Why is that dangerous?
Advanced
Situation read โ Reviewing RBAC shows create pods for a CI ServiceAccount.
What I'd do โ
- Explain that creating pods allows mounting any Secret or ServiceAccount in the namespace and running arbitrary images
- Treat
create pods,exec,get secretsandimpersonateas privilege escalation paths - Constrain with PSA restricted and admission policy
- Split CI per namespace
- Audit with
kubectl auth can-i --list
Why โ Pod creation lets the actor assume the identities and data available in the namespace.
Interview tip โ Mention RBAC escalation prevention (bind and escalate verbs).
Q109 How do you limit which namespaces teams can see in a multi-tenant cluster?
Intermediate
Situation read โ Teams share one EKS cluster.
What I'd do โ
- One namespace per team with RoleBindings to team groups
- ResourceQuota and LimitRange per namespace
- Default-deny NetworkPolicy
- PSA restricted
- Separate node pools via taints for sensitive tenants
Why โ Namespaces are a soft boundary and need quota, network and RBAC controls.
Interview tip โ Say hard isolation needs separate clusters.
Q110 What would you do after finding a compromised pod in production?
Advanced
Situation read โ A crypto miner is running in a container.
What I'd do โ
- Isolate: apply a deny-all NetworkPolicy or label to quarantine the pod
- Keep evidence:
kubectl logs,kubectl get pod -o yaml, node-level forensics, and snapshot the volume - Cordon the node and review other pods on it
- Rotate Secrets, ServiceAccount tokens and IAM roles it could reach
- Find the entry point (image, exposed dashboard, RBAC), fix, then rebuild from clean images
Why โ Containing first preserves evidence and stops lateral movement.
Interview tip โ Say "isolate, preserve, eradicate, rotate".
Q111 How do you secure access to the API server on EKS?
Intermediate
Situation read โ The cluster endpoint is open to the world.
What I'd do โ
- Set the endpoint to private or restrict
publicAccessCidrs - Use IAM authentication with access entries and least-privilege groups
- Enable control plane logging (api, audit, authenticator)
- Remove the creator admin where possible
- Use SSO and short-lived tokens for humans
Why โ Reducing exposure and authenticating through IAM covers most risk.
Interview tip โ Mention aws eks update-cluster-config.
Q112 How do you scan for vulnerabilities in a running cluster and in CI?
Intermediate
Situation read โ Leadership wants continuous scanning.
What I'd do โ
- In CI scan images with Trivy or Grype and fail on critical issues
- In cluster run the Trivy Operator for continuous reports
- Scan manifests with kubescape, kube-linter or Checkov
- Check CIS benchmarks with kube-bench
- Track fixes by SLA
Why โ Shift left to catch issues early and scan runtime for newly published CVEs.
Interview tip โ Mention that results need triage, not just reports.
Q113 What is a securityContext and what do you set by default?
Beginner
Situation read โ A security review lists the defaults to enforce.
What I'd do โ
runAsNonRoot: trueand a numericrunAsUserallowPrivilegeEscalation: falsecapabilities.drop: ["ALL"]readOnlyRootFilesystem: trueseccompProfile.type: RuntimeDefault
Why โ These settings satisfy the restricted PSA profile.
Interview tip โ Recite the five settings fast.
Q114 How do you handle multi-cluster RBAC and audit at scale?
Advanced
Situation read โ Twelve clusters, each with hand-made bindings.
What I'd do โ
- Manage RBAC as code through GitOps and a shared base
- Bind IdP groups instead of users
- Ship audit logs to a central store
- Use policy to forbid ad hoc ClusterRoleBindings
- Review access quarterly with automated reports
Why โ Consistency across clusters removes drift and makes audits cheap.
Interview tip โ Say you treat RBAC as code reviewed in PRs.
Q115 How do you rotate a leaked ServiceAccount token?
Intermediate
Situation read โ A token appeared in a public log.
What I'd do โ
- Delete the affected Secret (legacy) or the ServiceAccount and recreate it
- Bound tokens expire, and you can restart pods to get new ones
- Check audit logs for use of the token
- Reduce its permissions
- Move to short-lived tokens with TokenRequest
Why โ Revocation means invalidating the identity, not just removing the file.
Interview tip โ Mention audit log queries by user.username.
Q116 How do you prevent a pod from reaching the internet but allow internal calls?
Intermediate
Situation read โ Compliance forbids egress to the public internet for a batch job.
What I'd do โ
- Create an egress NetworkPolicy allowing DNS and in-cluster CIDRs (
ipBlock) - Or use a private subnet without NAT route for those nodes
- Use VPC endpoints for AWS services
- Test with
curlto a public IP - Use FQDN policies with Cilium if needed
Why โ Without egress policy every pod can reach anything its node can.
Interview tip โ Standard NetworkPolicy cannot filter by hostname.
Q117 You find that kubectl exec is used in production by many people. How do you control it?
Advanced
kubectl exec is used in production by many people. How do you control it?Situation read โ Auditors flagged uncontrolled shell access to production pods.
What I'd do โ
- Restrict
pods/execandpods/attachin RBAC - Offer break-glass roles with approval and time limit
- Enable audit policy at RequestResponse level for exec
- Use ephemeral debug containers (
kubectl debug) under controlled roles - Alert on exec events in prod namespaces
Why โ Exec bypasses application controls and leaves little trace without audit logs.
Interview tip โ Say exec in prod should be exceptional and logged.
Q118 What is OPA Gatekeeper's ConstraintTemplate and how does it differ from Kyverno policy?
Intermediate
Situation read โ The team must choose a policy engine.
What I'd do โ
- Gatekeeper uses Rego in a ConstraintTemplate plus Constraint instances
- Kyverno policies are YAML with match and validate blocks, no new language
- Kyverno supports mutate, generate, verifyImages natively
- Gatekeeper suits teams already using OPA
- Pilot both in audit mode
Why โ The choice is mostly about language and capabilities.
Interview tip โ Say you pick by team skills and use case.
Q119 Why is running containers as root a problem?
Beginner
Situation read โ A scan flags many containers running as UID 0.
What I'd do โ
- Root in the container is root on the shared kernel if an escape occurs
- Set
runAsNonRootand build images with a non-rootUSER - Fix file ownership with
fsGroup - Verify with
kubectl exec -- id - Enforce with PSA
Why โ Least privilege reduces the effect of a container escape.
Interview tip โ Mention user namespaces as an extra layer.
Helm, operators and GitOps
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q120 A helm upgrade failed halfway. How do you see state and recover?
Beginner
helm upgrade failed halfway. How do you see state and recover?Situation read โ The release shows failed status after a timeout.
What I'd do โ
helm status web -n appandhelm history web -n appkubectl get podsto see what is brokenhelm rollback web 3 -n app --waitto the last good revision- Fix the chart or values and retry with
helm upgrade --install --atomic --timeout 5m - Use
helm get manifestto compare
Why โ Helm keeps revisions as Secrets, so rollback is a re-apply of an older manifest.
Interview tip โ Mention --atomic auto-rolls back on failure.
Q121 Helm says cannot re-use a name that is still in use or another operation is in progress. What now?
Intermediate
cannot re-use a name that is still in use or another operation is in progress. What now?Situation read โ The pipeline is blocked on a pending release state.
What I'd do โ
helm list -a -n appto see pending-install or pending-upgrade- Check no helm process is still running
helm rollbackto the last deployed revision, orhelm uninstallfor a failed first install- As a last resort delete the stuck release Secret
sh.helm.release.v1.web.vN - Add timeouts to CI jobs
Why โ A killed Helm client leaves the release in a pending state that blocks new operations.
Interview tip โ Say you avoid deleting release Secrets unless necessary.
Q122 How do you review what a Helm upgrade will change before running it?
Intermediate
Situation read โ Production upgrades need a change review.
What I'd do โ
helm diff upgrade web ./chart -f values-prod.yamlusing the helm-diff pluginhelm templateandkubeconformin CIhelm upgrade --dry-run --debug- Post the diff into the pull request
- Gate on approval
Why โ A diff shows the real manifest changes rather than only values changes.
Interview tip โ Mention that values changes can hide big rendered diffs.
Q123 Where do you keep chart values for multiple environments?
Beginner
Situation read โ Teams copy whole charts per environment.
What I'd do โ
- Keep one chart and
values.yamldefaults - Add
values-dev.yaml,values-prod.yaml - Pass with multiple
-fflags, later ones override - Keep secrets out of values files
- Pin chart versions with
--version
Why โ One chart plus small overrides keeps environments consistent.
Interview tip โ Say you pin chart versions in production.
Q124 What does helm template do and how is it different from helm install?
Beginner
helm template do and how is it different from helm install?Situation read โ Someone wants to see manifests without touching the cluster.
What I'd do โ
helm template web ./chart -f values.yamlrenders manifests locally- Pipe to
kubectl apply --dry-run=server -f -for server-side validation helm installrenders and applies, and tracks a release- Use template in GitOps tools such as Argo CD which render themselves
Why โ template is rendering only, no release is created.
Interview tip โ Mention --validate against a live cluster.
Q125 A Helm chart upgrade changed an immutable field and failed. How do you proceed?
Advanced
Situation read โ Error: field is immutable for a Deployment selector or a Job template.
What I'd do โ
- Identify the field in the error (
spec.selector,spec.templateof Job, PVC size, Service clusterIP) - For Jobs delete the old Job first or use
ttlSecondsAfterFinished - For selectors, plan a migration: create a new Deployment name and shift traffic
- Avoid changing selector labels in chart updates
- Use hooks to delete and recreate where acceptable
Why โ Kubernetes forbids changing certain fields, so the object must be recreated.
Interview tip โ Mention that selector labels should never include chart version.
Q126 How would you structure Helm charts for 30 microservices?
Intermediate
Situation read โ Each team copies a similar chart.
What I'd do โ
- Build a common library chart (
type: library) with shared templates - Each service chart contains a small
values.yamland depends on the library - Publish charts to an OCI registry (ECR)
- Version and test with
helm lintandct lint-and-install - Or use one generic chart parametrised by values
Why โ Shared templates reduce drift and let platform changes roll out uniformly.
Interview tip โ Say you keep chart logic simple.
Q127 What is an operator and when would you use one?
Beginner
Situation read โ A team wants to run PostgreSQL on Kubernetes.
What I'd do โ
- An operator is a controller plus CRDs that encodes operational knowledge
- Install the operator (for example CloudNativePG) with Helm
- Create a
Clustercustom resource declaring instances and backups - Check with
kubectl get clusterand operator logs - Weigh managed RDS versus self-run
Why โ Operators automate day-2 tasks such as failover, backups and upgrades.
Interview tip โ Say you evaluate operator maturity before trusting it.
Q128 A CRD was deleted and all custom resources disappeared. How do you prevent that?
Advanced
Situation read โ Someone uninstalled an operator chart and the data objects vanished.
What I'd do โ
- Explain that deleting a CRD deletes all its objects
- Helm does not manage CRDs in
crds/on upgrade or uninstall - Install CRDs separately and protect with RBAC
- Back up with Velero or GitOps
- Add admission policy blocking CRD deletion
Why โ CRD deletion is cascading and immediate.
Interview tip โ Memorise this as a favourite gotcha.
Q129 How would you design a GitOps repo layout and promotion flow for dev, staging and prod?
Advanced
Situation read โ Several teams deploy to three environments through Argo CD.
What I'd do โ
- Separate app source repos from a config repo
- Use Kustomize bases with env overlays, or ApplicationSets with a cluster generator
- Promote by pull request changing the image tag in the next environment
- Automate dev, require approval for prod
- Protect branches and use CODEOWNERS
Why โ Git history becomes the audit trail for every change.
Interview tip โ Say promotion is a PR, not a pipeline push.
Q130 Argo CD shows an app as OutOfSync constantly though nothing changed. Why?
Intermediate
OutOfSync constantly though nothing changed. Why?Situation read โ A Deployment is always out of sync with Git.
What I'd do โ
argocd app diff webto see the differing fields- Typical causes: HPA changing replicas, mutating webhooks adding fields, controllers adding defaults
- Add
ignoreDifferenceswith jsonPointers - Remove
replicasfrom Git when using HPA - Use
ServerSideApply=truesync option
Why โ Fields written by other controllers show as drift unless ignored.
Interview tip โ Mention managedFieldsManagers.
Q131 Argo CD sync fails with one or more objects failed to apply. How do you debug?
Intermediate
one or more objects failed to apply. How do you debug?Situation read โ A sync runs, then fails with a validation error.
What I'd do โ
argocd app get webandargocd app sync web --dry-run- Read the resource-level message in the UI or CLI
- Common causes: CRD not yet installed, namespace missing, immutable field changes, admission denial
- Use sync waves and
CreateNamespace=true - Check controller logs:
kubectl -n argocd logs deploy/argocd-application-controller
Why โ Ordering and validation errors are the usual reasons, and waves control order.
Interview tip โ Mention SkipDryRunOnMissingResource.
Q132 How do you handle Helm chart or operator upgrades safely in GitOps across many clusters?
Advanced
Situation read โ A new operator version needs a CRD change.
What I'd do โ
- Read release notes for breaking changes and CRD updates
- Upgrade CRDs first as a separate Argo Application with sync wave 0
- Roll the operator to a canary cluster, validate, then widen
- Keep the previous version ready for rollback
- Test on a copy of production data
Why โ CRDs are cluster-wide and not rolled back by Helm, so they get special care.
Interview tip โ Say you stagger by cluster ring.
Q133 Explain init containers and sidecars with a real use.
Intermediate
Situation read โ An app must wait for a DB, and logs must be shipped.
What I'd do โ
- Init containers run to completion in order before the app, for waiting or migrations
- Sidecars run alongside, for log shipping or proxies
- Native sidecars (init containers with
restartPolicy: Always) start before and stop after the app - Check
kubectl get podforInit:0/1 - Read init logs with
kubectl logs pod -c init
Why โ Native sidecars fix ordering problems, such as Jobs that never finish because of a sidecar.
Interview tip โ Mention native sidecars GA in 1.33.
Q134 How do you view and edit a running resource, and why is that risky?
Beginner
Situation read โ A developer edited a Deployment live.
What I'd do โ
kubectl edit deploy webopens the live object- The change is not in Git and will be reverted or lost
- Use
kubectl diffto compare - Make the change in Git
- Use RBAC to limit edits in production
Why โ Live edits create drift.
Interview tip โ Mention ArgoCD self-heal.
Q135 How do you write a minimal controller or choose between operator frameworks?
Advanced
Situation read โ The team needs a custom operator for an internal resource.
What I'd do โ
- Consider if a Helm chart or a CronJob is enough first
- Use Kubebuilder or Operator SDK (Go) for full control, or Kopf (Python) for simple needs
- Define the CRD schema with validation and a status subresource
- Make reconciliation idempotent
- Add finalizers for cleanup, metrics and leader election
Why โ Reconcile loops must be level-triggered and idempotent.
Interview tip โ Mention status conditions.
Q136 A custom resource is stuck in Terminating. Why?
Advanced
Situation read โ kubectl delete hangs on a custom resource.
What I'd do โ
kubectl get cr x -o yamland inspectmetadata.finalizersanddeletionTimestamp- The operator is expected to remove the finalizer after cleanup
- Check whether the operator is running:
kubectl get pods -n operators - Fix the operator and let it finish cleanup
- Last resort:
kubectl patch cr x --type=merge -p '{"metadata":{"finalizers":[]}}'knowing external resources may leak
Why โ A finalizer holds the object until its controller completes cleanup.
Interview tip โ Say you patch finalizers only after confirming what cleanup is skipped.
Q137 How do you template Kubernetes manifests without Helm?
Intermediate
Situation read โ A team dislikes Go templates.
What I'd do โ
- Use Kustomize overlays with patches
- Use
cdk8s, Jsonnet or CUE for generating manifests - Check output with
kustomize build - Keep logic out of manifests when possible
- Pick one tool per repo
Why โ Different tools suit different teams, consistency matters most.
Interview tip โ Show you know trade-offs, not just one tool.
Q138 What are Helm hooks and give an example.
Beginner
Situation read โ A DB migration must run before upgrade.
What I'd do โ
- Add annotation
"helm.sh/hook": pre-upgradeto a Job - Add
"helm.sh/hook-delete-policy": before-hook-creation - Set weights for ordering
- Watch the hook with
kubectl get jobs - Remember hooks are not part of the release manifest
Why โ Hooks run at lifecycle points like pre-install and post-upgrade.
Interview tip โ Mention test hooks with helm test.
Q139 How would you migrate workloads from kubectl apply scripts to Argo CD without downtime?
Advanced
kubectl apply scripts to Argo CD without downtime?Situation read โ Many resources already exist, deployed manually.
What I'd do โ
- Commit current live manifests to Git (
kubectl get -o yamlcleaned) - Create the Argo Application with automated sync off
- Use
argocd app diffuntil it is clean - Enable sync without prune first
- Then enable prune and self-heal
Why โ Adoption is safe when Argo sees no difference before taking control.
Interview tip โ Say you do the first sync manually.
Q140 How do you version and promote container images?
Intermediate
Situation read โ Teams use latest tags.
What I'd do โ
- Tag images with the Git SHA and a semantic version
- Never deploy
latest - Prefer digests in production manifests
- Scan before promotion
- Automate bumps with Argo CD Image Updater or Renovate
Why โ Immutable references make deployments reproducible and rollbacks real.
Interview tip โ Mention imagePullPolicy defaults.
Q141 What is Kustomize configMapGenerator and why is it useful?
Intermediate
configMapGenerator and why is it useful?Situation read โ Config changes must trigger rollouts.
What I'd do โ
- Define
configMapGeneratorin kustomization.yaml - Kustomize appends a hash to the name
- References in Deployments are rewritten
- A content change creates a new name, so pods roll
- Old ConfigMaps can be pruned
Why โ Hash suffixes tie pod revisions to config versions.
Interview tip โ Cheap and neat approach for rollbacks.
Q142 You want to uninstall a Helm release but keep the PVCs. How?
Beginner
Situation read โ Data must survive an uninstall.
What I'd do โ
- Check how PVCs were created (chart template versus StatefulSet volumeClaimTemplates)
- StatefulSet PVCs survive
helm uninstall - Annotate chart-managed PVCs with
helm.sh/resource-policy: keep - Verify with
kubectl get pvcafter uninstall - Back up first
Why โ The keep policy tells Helm not to delete a resource on uninstall.
Interview tip โ Always back up before uninstall.
EKS and cluster operations
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q143 How do you create a production-ready EKS cluster and what do you decide up front?
Beginner
Situation read โ You are asked to stand up the first EKS cluster for a team.
What I'd do โ
- Decide VPC layout: private subnets for nodes across three AZs, public only for load balancers
- Create the cluster with Terraform or
eksctl create cluster -f cluster.yaml - Choose managed node groups, Karpenter or Fargate
- Enable control plane logs, secrets encryption and OIDC
- Install add-ons: VPC CNI, CoreDNS, kube-proxy, EBS CSI, metrics-server
Why โ Cluster shape is hard to change later, so network and identity choices come first.
Interview tip โ Say infrastructure is code, never console-built.
Q144 Pods on EKS run out of IP addresses. What happened and how do you fix it?
Intermediate
Situation read โ New pods fail with failed to assign an IP address to container.
What I'd do โ
- Understand the VPC CNI gives each pod a VPC IP from the node's ENIs, limited by instance type
kubectl -n kube-system logs ds/aws-nodeand check subnet free IPs- Enable prefix delegation (
ENABLE_PREFIX_DELEGATION=true) - Add secondary CIDR with custom networking
- Use larger instances or more subnets
Why โ Pod density equals ENIs times IPs per ENI, and subnet size is the second ceiling.
Interview tip โ Mention /16 VPC planning.
Q145 How do you give a new engineer access to an EKS cluster?
Intermediate
Situation read โ Old method used the aws-auth ConfigMap.
What I'd do โ
- Use EKS access entries:
aws eks create-access-entry --cluster-name prod --principal-arn <role-arn> - Associate an access policy such as
AmazonEKSViewPolicywith scope namespace or cluster - Or map to a Kubernetes group and use RBAC
- Test with
aws eks update-kubeconfigthenkubectl auth whoami - Remove the ConfigMap path over time
Why โ Access entries are API-managed and avoid lockouts caused by editing aws-auth.
Interview tip โ Mention the aws-auth lockout risk.
Q146 Compare managed node groups, self-managed nodes, Fargate and Karpenter.
Intermediate
Situation read โ The team needs to choose a compute model.
What I'd do โ
- Managed node groups: AWS handles AMI updates and draining, simple and common
- Self-managed: full control, more work
- Fargate: no nodes, per-pod pricing, no DaemonSets or privileged pods
- Karpenter: dynamic, cost-aware, fast scale
- Mix: a small managed group for system add-ons plus Karpenter for workloads
Why โ Trade control against operational effort.
Interview tip โ Say you run system pods on a stable group.
Q147 How do you upgrade an EKS cluster from 1.31 to 1.32 with minimal risk?
Advanced
Situation read โ Quarterly upgrade of a production cluster.
What I'd do โ
- Read release notes and check deprecated APIs with
kubectl get --raw /metrics | grep apiserver_requested_deprecated_apisor Pluto/kubent - Check EKS upgrade insights
- Test in staging
- Upgrade the control plane (
aws eks update-cluster-version) - Upgrade add-ons, then node groups (one minor at a time, nodes within skew), verifying PDBs and workloads
Why โ The control plane moves first and nodes must stay within the supported version skew.
Interview tip โ Say you never skip minors.
Q148 A node group upgrade is slow or stuck on EKS. What do you look at?
Intermediate
Situation read โ Rolling update has been running for an hour.
What I'd do โ
aws eks describe-updatefor errorskubectl get nodesfor NotReady or SchedulingDisabled- Look for PDBs blocking drains
- Adjust
updateConfig.maxUnavailable - Check that new nodes can join (IAM, security groups, subnets, AMI)
Why โ The most common blocker is a PDB with zero allowed disruptions.
Interview tip โ Mention surge upgrades.
Q149 How do you connect to a node for debugging without SSH?
Beginner
Situation read โ Nodes have no SSH keys.
What I'd do โ
kubectl debug node/ip-10-0-1-5 -it --image=ubuntuwhich mounts the host at/host- Or use AWS SSM Session Manager
- Inspect with
chroot /host - Use journalctl for kubelet
- Delete the debug pod after
Why โ Debug pods avoid opening SSH and leave an audit trail.
Interview tip โ Mention SSM as the standard.
Q150 What add-ons do you install on EKS first and why?
Intermediate
Situation read โ A fresh cluster has only the defaults.
What I'd do โ
- VPC CNI, CoreDNS, kube-proxy as managed add-ons
- EBS CSI driver for volumes
- AWS Load Balancer Controller for ingress and NLB
- metrics-server, then Prometheus stack
- Karpenter or Cluster Autoscaler, and external-dns plus cert-manager
Why โ These cover networking, storage, traffic, observability and scaling.
Interview tip โ Manage add-ons through IaC.
Q151 How do you design multi-AZ resilience for a service on EKS?
Advanced
Situation read โ The business wants to survive an AZ outage.
What I'd do โ
- Run nodes in at least three AZs
- Use
topologySpreadConstraintson zone withmaxSkew: 1 - Set PDBs and enough replicas to absorb one AZ loss
- Use a regional database (Aurora Multi-AZ)
- Test with a zone drain or AWS FIS experiment
Why โ Spreading plus headroom means the loss of a zone leaves capacity.
Interview tip โ Mention cross-AZ data transfer cost.
Q152 Your EKS cluster endpoint is private. How does CI reach it?
Intermediate
Situation read โ GitHub-hosted runners cannot connect.
What I'd do โ
- Use self-hosted runners inside the VPC
- Or run CI in AWS CodeBuild with VPC config
- Or GitOps pull model, so the cluster pulls from Git
- Or temporarily allow specific CIDRs
- Verify with
kubectl get nsfrom the runner
Why โ Pull-based deployment removes the need for inbound access.
Interview tip โ Say GitOps solves this elegantly.
Q153 Explain EKS Pod Identity vs IRSA.
Intermediate
Situation read โ Choosing between workload IAM methods.
What I'd do โ
- IRSA uses the cluster OIDC provider and a role trust policy per cluster
- Pod Identity uses an agent and
CreatePodIdentityAssociationwith no OIDC setup - Pod Identity roles can be reused across clusters
- Both give temporary credentials
- Check SDK versions for support
Why โ Pod Identity removes per-cluster trust policy edits.
Interview tip โ Know both.
Q154 How do you control cost on a large EKS estate?
Advanced
Situation read โ EKS spend doubled in a quarter.
What I'd do โ
- Tag and attribute cost with Kubecost or OpenCost
- Right-size requests
- Use Karpenter consolidation and Spot for stateless
- Use Graviton instances
- Reduce cross-AZ traffic and idle environments (scale dev to zero at night)
Why โ Most savings come from requests, instance choice and idle capacity.
Interview tip โ Quote percentages.
Q155 What do you do when a node is NotReady?
Beginner
Situation read โ A node flipped to NotReady.
What I'd do โ
kubectl describe nodeand read Conditions- Check kubelet and container runtime on the node
- Check disk, memory, PID pressure
- Check network to the API server
- Cordon, drain if possible, replace the node
Why โ NotReady means the kubelet stopped reporting healthy status.
Interview tip โ Cattle not pets: replace nodes.
Q156 How do you view logs and metrics on EKS?
Beginner
Situation read โ No observability yet.
What I'd do โ
- Enable control plane logs to CloudWatch
- Run Fluent Bit as DaemonSet or use CloudWatch Observability add-on
- Install kube-prometheus-stack or Amazon Managed Prometheus
- Grafana dashboards
- Alerts for restarts, pending pods, node pressure
Why โ Visibility into control plane, nodes and workloads is required.
Interview tip โ Say you alert on symptoms.
Q157 How do you restrict an EKS node group to private subnets but pull images from ECR?
Intermediate
Situation read โ Nodes have no internet path.
What I'd do โ
- Create VPC endpoints for ECR API, ECR DKR and S3 gateway endpoint
- Add endpoints for STS, EC2 and logs as needed
- Check endpoint security groups allow 443
- Verify with
crictl pull - Use pull-through cache for public images
Why โ Private endpoints keep traffic inside AWS.
Interview tip โ Don't forget the S3 gateway endpoint.
Q158 How do you handle a bad AMI or add-on rollout across 40 nodes?
Advanced
Situation read โ Nodes boot but pods fail.
What I'd do โ
- Pause the node group update
- Roll back launch template version
- Cordon bad nodes
- Move workloads using drain
- Test AMI in canary node group first
Why โ Canary node groups limit blast radius.
Interview tip โ Say AMIs are versioned and canaried.
Q159 Explain how DNS and certificates are automated on EKS.
Intermediate
Situation read โ Teams request hostnames by hand.
What I'd do โ
- Install external-dns with IAM for Route 53
- Add
external-dns.alpha.kubernetes.io/hostnameannotations or use Ingress hosts - Install cert-manager with a ClusterIssuer (Let's Encrypt DNS-01 via Route 53)
- Request certificates through Ingress annotations or Certificate objects
- Verify with
kubectl get certificate
Why โ Automation removes manual tickets and expiring certificates.
Interview tip โ Know DNS-01 vs HTTP-01.
Q160 You need to run Windows or ARM workloads. What changes?
Intermediate
Situation read โ New Graviton nodes are added.
What I'd do โ
- Build multi-arch images with
docker buildx --platform linux/amd64,linux/arm64 - Label and taint ARM nodes
- Use nodeSelector
kubernetes.io/arch - Check add-ons support ARM
- Test performance
Why โ Image architecture must match the node.
Interview tip โ Name exec format error.
Q161 What is the control plane responsible for and who manages it on EKS?
Beginner
Situation read โ A manager asks what AWS handles.
What I'd do โ
- AWS manages API servers, etcd, scheduler and controllers
- You manage nodes, add-ons, workloads and IAM
- Control plane logging is optional
- Versions need upgrades by you
- Pay per cluster hour
Why โ It is a shared responsibility model.
Interview tip โ Mention extended support costs.
Q162 How would you set up multi-cluster management for 10 EKS clusters?
Advanced
Situation read โ Many clusters drift.
What I'd do โ
- Define clusters with Terraform modules
- Use Argo CD ApplicationSets targeting a cluster list
- Standardise add-ons via a platform repo
- Centralise logs, metrics and policy
- Roll changes by rings
Why โ Fleet consistency needs code and staged rollouts.
Interview tip โ Say rings: dev, staging, prod-1, prod-rest.
Q163 kubectl on a laptop shows You must be logged in to the server (Unauthorized). What do you do on EKS?
Intermediate
You must be logged in to the server (Unauthorized). What do you do on EKS?Situation read โ Access broke after a role change.
What I'd do โ
aws sts get-caller-identityto check identityaws eks update-kubeconfig --name prod- Check the identity has an access entry or aws-auth mapping
- Check token expiry and clock skew
- Check the assumed role ARN versus the mapped one
Why โ Authentication maps an IAM principal to a Kubernetes user.
Interview tip โ Role ARNs in mappings must not include the path.
Q164 How do you run batch jobs at scale cheaply?
Intermediate
Situation read โ Nightly ETL with 500 pods.
What I'd do โ
- Use Jobs with
parallelismandcompletions - Run on Spot via Karpenter NodePool
- Use indexed Jobs
- Set resource requests accurately
- Use
ttlSecondsAfterFinished
Why โ Batch tolerates interruption, so spot saves cost.
Interview tip โ Consider Argo Workflows or Volcano.
Q165 How do you check which Kubernetes version a cluster and its nodes run?
Beginner
Situation read โ Version skew question.
What I'd do โ
kubectl versionkubectl get nodes -o wideaws eks describe-cluster --name prod --query cluster.version- Compare kubelet versions
- Keep nodes within skew
Why โ Skew policy limits kubelet to the control plane version minus a few minors.
Interview tip โ Say supported skew is N-3 for kubelet.
Q166 Describe your approach when API server latency rises in EKS.
Advanced
Situation read โ kubectl is slow and controllers time out.
What I'd do โ
- Check API server metrics
apiserver_request_duration_seconds - Find heavy clients: list calls without limits in audit logs
- Look for webhook latency
- Check etcd size and object counts
- Enable API Priority and Fairness tuning and fix noisy controllers
Why โ Slow admission webhooks and expensive lists are frequent causes.
Interview tip โ Say you look at webhook latency first.
Q167 How do you roll out a cluster-wide change such as new log agent config safely?
Intermediate
Situation read โ A DaemonSet config affects every node.
What I'd do โ
- Test on a staging cluster
- Use
updateStrategy.rollingUpdate.maxUnavailable - Canary on one node group using nodeSelector
- Watch resource usage
- Roll back by reverting Git
Why โ Cluster-wide agents are high blast radius.
Interview tip โ Mention canary nodes.
Q168 What is a namespace and how do you organise them?
Beginner
Situation read โ Teams mix everything in default.
What I'd do โ
- One namespace per team or app and environment
- Apply quotas, RBAC, network policies per namespace
- Never use
default - Label namespaces
- Use
kubectl config set-context --current --namespace=app
Why โ Namespaces scope names and policies.
Interview tip โ Namespaces are not security boundaries alone.
Upgrades, etcd, disaster recovery and incidents
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q169 How do you back up etcd on a self-managed cluster?
Beginner
Situation read โ A kubeadm cluster has no backup.
What I'd do โ
ETCDCTL_API=3 etcdctl snapshot save /backup/etcd.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- Verify with
etcdutl snapshot status /backup/etcd.db - Copy offsite to S3
- Schedule with a CronJob or systemd timer
- Test restore regularly
Why โ A snapshot captures all cluster state, and restoring is the only proof of a good backup.
Interview tip โ Say on EKS you do not own etcd, use Velero or GitOps.
Q170 How do you restore a cluster from an etcd snapshot?
Advanced
Situation read โ Control plane data is corrupted.
What I'd do โ
- Stop kube-apiserver and etcd static pods by moving manifests out of
/etc/kubernetes/manifests etcdutl snapshot restore /backup/etcd.db --data-dir /var/lib/etcd-restore- Point the etcd manifest data dir to the restored directory
- For multi-node, restore each member with
--initial-clusterflags - Start components and verify with
kubectl get nodes
Why โ Restore creates a new cluster identity, so all members must be restored consistently.
Interview tip โ Rehearse this at least once.
Q171 etcd database space exceeded: mvcc: database space exceeded. What now?
Advanced
mvcc: database space exceeded. What now?Situation read โ API writes fail.
What I'd do โ
etcdctl endpoint status -w tableto see DB sizeetcdctl alarm list- Compact: get revision and
etcdctl compact <rev> etcdctl defragone member at a timeetcdctl alarm disarm, then find noisy writers (events, CRDs) and raise--quota-backend-bytesif justified
Why โ Compaction removes old revisions, defrag returns space to disk.
Interview tip โ Mention default 2 GiB quota.
Q172 Walk through a kubeadm minor version upgrade.
Advanced
Situation read โ Move from 1.31 to 1.32 on a self-managed cluster.
What I'd do โ
- Upgrade kubeadm on the first control plane node and
kubeadm upgrade plan kubeadm upgrade apply v1.32.x- Upgrade kubelet and kubectl, restart kubelet
- On other control plane nodes
kubeadm upgrade node - For workers cordon and drain,
kubeadm upgrade node, upgrade kubelet, uncordon
Why โ Control plane first, then workers one by one.
Interview tip โ Say take an etcd snapshot before.
Q173 How do you find deprecated or removed APIs before an upgrade?
Intermediate
Situation read โ Manifests use policy/v1beta1.
What I'd do โ
- Run Pluto:
pluto detect-files -d manifests/andpluto detect-helm - Or kubent against the cluster
- Check API server metric
apiserver_requested_deprecated_apis - Update manifests and Helm charts
- Test in staging
Why โ Removed APIs break applies and controllers after upgrade.
Interview tip โ Show you check before, not after.
Q174 A cluster upgrade broke an operator because its CRD API version was removed. How do you recover?
Advanced
Situation read โ After the upgrade, custom resources cannot be served.
What I'd do โ
- Check
kubectl get crd x -o yamlforstoredVersions - Re-install the operator version that supports the cluster
- Migrate stored objects to the new version (storage version migration)
- Update manifests to the served version
- Roll forward rather than back, since control plane downgrade is unsupported
Why โ Stored versions must be migrated before an old version is dropped.
Interview tip โ Control plane rollback is not supported.
Q175 What are the main control plane components and what does each do?
Beginner
Situation read โ Interview warm-up.
What I'd do โ
- kube-apiserver: front door and validation
- etcd: stores state
- kube-scheduler: assigns pods to nodes
- kube-controller-manager: runs control loops
- cloud-controller-manager: talks to cloud APIs
Why โ Everything flows through the API server.
Interview tip โ Add kubelet and kube-proxy on nodes.
Q176 What happens when you run kubectl apply -f deploy.yaml?
Beginner
kubectl apply -f deploy.yaml?Situation read โ Walk through the flow.
What I'd do โ
- kubectl sends the object to the API server after authentication and authorization
- Admission controllers mutate and validate
- The object is persisted in etcd
- Deployment controller creates a ReplicaSet, which creates pods
- Scheduler binds pods, kubelet starts containers via CRI
Why โ It is a chain of watch-driven controllers.
Interview tip โ Mention the watch mechanism.
Q177 The whole control plane is down on a self-managed cluster. Do running workloads keep working?
Advanced
Situation read โ API servers are unreachable.
What I'd do โ
- Pods already running keep running since the kubelet acts independently
- Services and kube-proxy rules stay in place
- No new scheduling, scaling or rollouts
- Node failures are not detected
- Restore the control plane from static pod manifests or snapshot
Why โ The data plane is decoupled from the control plane for steady state.
Interview tip โ Highlights why control plane HA matters.
Q178 How do you set up a highly available control plane?
Intermediate
Situation read โ Single master is a risk.
What I'd do โ
- Run three or five control plane nodes across AZs
- Put a load balancer in front of API servers
- Use stacked or external etcd with odd members
- Back up etcd
- Use
kubeadm init --control-plane-endpoint
Why โ etcd needs quorum, so odd members and spread matter.
Interview tip โ Know quorum maths: 3 tolerates 1, 5 tolerates 2.
Q179 You get paged: API latency high and pods failing. Describe your incident approach.
Advanced
Situation read โ A general production incident.
What I'd do โ
- Declare the incident and assign roles
- Check recent changes (deploys, upgrades) and roll back if correlated
- Check cluster health: nodes, control plane, DNS, ingress
- Use
kubectl get events -A --sort-by=.lastTimestamp - Communicate status, then write a blameless postmortem
Why โ Stabilise first, understand later.
Interview tip โ Say you roll back before root-causing.
Q180 Velero restore into a new cluster: what do you verify?
Intermediate
Situation read โ DR drill.
What I'd do โ
- Install Velero with the same bucket
velero restore create --from-backup daily-1- Check namespaces, PVs, secrets
- Check storage class mapping
- Run smoke tests
Why โ Restores are complete only when workloads function.
Interview tip โ Mention restore time objectives.
Q181 Define RTO and RPO and how they shape a Kubernetes DR plan.
Intermediate
Situation read โ Business asks for a DR design.
What I'd do โ
- RPO is how much data you can lose, RTO is how long you can be down
- Low RPO needs continuous data replication
- Low RTO needs warm standby cluster
- Keep manifests in Git for quick rebuild
- Practise failover quarterly
Why โ Targets determine cost and architecture.
Interview tip โ Name active-active versus pilot light.
Q182 How do you check the health of cluster components?
Beginner
Situation read โ Quick triage.
What I'd do โ
kubectl get nodeskubectl get pods -n kube-systemkubectl get --raw='/readyz?verbose'kubectl get events -Akubectl top nodes
Why โ These cover the main failure areas.
Interview tip โ Mention /livez and /readyz.
Q183 Certificates on a kubeadm cluster expire. What happens and how do you fix it?
Advanced
Situation read โ kubectl returns x509: certificate has expired.
What I'd do โ
kubeadm certs check-expirationkubeadm certs renew all- Restart control plane static pods by moving manifests out and back
- Update admin kubeconfig
- Monitor expiry going forward
Why โ kubeadm certs last one year unless renewed by upgrade.
Interview tip โ Upgrading renews certs.
Q184 How do you debug a pod that has no shell in its image?
Intermediate
Situation read โ Distroless images.
What I'd do โ
kubectl debug -it pod/app --image=busybox --target=app- Use
--copy-toto clone the pod with a debug image - Inspect shared process namespace
- Check network from the same netns
- Remove debug pods
Why โ Ephemeral containers attach tooling without rebuilding the image.
Interview tip โ Say you do not bake debug tools into prod images.
Q185 How would you perform a zero-downtime migration of a stateful database from a VM into Kubernetes?
Advanced
Situation read โ Move PostgreSQL to a CloudNativePG cluster.
What I'd do โ
- Set up the operator and a replica cluster
- Configure logical or physical replication from the VM
- Verify lag and consistency
- Cut over during a short write freeze: promote and switch app connection strings
- Keep the VM as fallback until validated
Why โ Replication allows a small controlled cutover window.
Interview tip โ Say you rehearse and have a rollback plan.
Q186 How do you test that your workloads survive failures?
Intermediate
Situation read โ Leadership wants resilience proof.
What I'd do โ
- Use chaos tools such as Chaos Mesh, LitmusChaos or AWS FIS
- Start with pod kills, then node drains, then AZ failure
- Define steady-state metrics
- Run in staging first, then in prod with guardrails
- Fix findings and repeat
Why โ Failure drills expose missing PDBs, probes, and capacity.
Interview tip โ Mention game days.
Q187 What is the role of kubelet and what happens if it stops?
Beginner
Situation read โ Node basics.
What I'd do โ
- Kubelet registers the node, runs pods through the container runtime and reports status
- If it stops the node becomes NotReady after about 40 seconds
- Running containers keep running
- Pods are evicted after the toleration period (300s default)
- Restart with
systemctl restart kubelet
Why โ Kubelet is the node agent.
Interview tip โ Mention node-monitor-grace-period.
Q188 Explain how you would upgrade to a new CNI or switch from one CNI to another.
Advanced
Situation read โ Moving from VPC CNI to Cilium.
What I'd do โ
- Test in a new cluster first
- Prefer building a new node group or cluster
- Plan IP ranges and network policies mapping
- Migrate workloads gradually
- Have rollback of node group
Why โ CNI swaps in place are risky since pod networking breaks.
Interview tip โ Prefer blue/green clusters.
Q189 How do you handle rapid growth to 5000 pods in a cluster?
Advanced
Situation read โ Capacity planning.
What I'd do โ
- Check API server and etcd limits
- Scale CoreDNS and monitoring
- Use IPAM prefix delegation
- Watch scheduler throughput and Events
- Consider splitting into multiple clusters
Why โ Control plane scaling limits appear before node limits.
Interview tip โ Mention cell-based architecture.
Q190 A namespace is stuck Terminating. What are the causes and the proper fix?
Advanced
Situation read โ kubectl delete ns app never finishes.
What I'd do โ
kubectl get ns app -o yamland checkstatus.conditionsfor what remainskubectl api-resources --verbs=list --namespaced -o name | xargs -n1 kubectl get -n appto find leftover objects- Common blockers: finalizers on custom resources, unavailable aggregated API like metrics
- Fix the owner (operator or APIService)
- Only then remove finalizers
Why โ Namespaces cannot finish deletion while any object or APIService still blocks.
Interview tip โ Do not use the raw finalize API without checking.
Q191 How do you migrate workloads between namespaces?
Intermediate
Situation read โ Reorganising.
What I'd do โ
- Export YAML and clean namespace and uid fields
- Re-apply in the new namespace
- Copy Secrets and ConfigMaps
- Move data with a snapshot-restored PVC
- Shift traffic and delete old
Why โ There is no rename, only recreate.
Interview tip โ Mention Velero namespace mapping.
Q192 How do you read a Kubernetes event and why do events disappear?
Beginner
Situation read โ Events are missing.
What I'd do โ
kubectl get events --sort-by=.lastTimestampkubectl describeincludes events for that object- Events live about one hour by default
- Ship events to logs with an exporter
- Use
-Afor all namespaces
Why โ Events are short-lived objects in etcd.
Interview tip โ Export them for history.
Q193 Explain leader election and why controllers use it.
Advanced
Situation read โ Multiple replicas of a controller.
What I'd do โ
- Replicas compete for a Lease object
- One is leader, others standby
- Leader renews the lease regularly
- On failure another takes over
- Check
kubectl get lease -n kube-system
Why โ Only one active reconciler prevents conflicting actions.
Interview tip โ Mention scheduler and controller-manager use leases.
Q194 How do you troubleshoot slow kubectl commands?
Intermediate
kubectl commands?Situation read โ Every command takes 10 seconds.
What I'd do โ
kubectl get pods -v=8to see request timing- Check the kubeconfig exec plugin (aws token) latency
- Check API server latency and discovery cache
- Check network and VPN
- Clear
~/.kube/cache
Why โ Often the credential plugin or discovery is slow, not the cluster.
Interview tip โ Use -v verbosity.
Q195 What is the difference between a Deployment, StatefulSet and DaemonSet?
Beginner
Situation read โ Fundamentals.
What I'd do โ
- Deployment: stateless, interchangeable replicas
- StatefulSet: stable identity and storage, ordered operations
- DaemonSet: one pod per node
- Pick by state and placement needs
- Verify with
kubectl get deploy,sts,ds
Why โ Each controller encodes a different guarantee.
Interview tip โ Give an example for each.
Q196 Your team asks for in-place pod resize and sidecar features. How do you handle feature gates and version adoption?
Advanced
Situation read โ A new Kubernetes feature is attractive.
What I'd do โ
- Check the feature stage (alpha, beta, GA) in the release notes
- Alpha is off by default and unsupported on EKS
- Pilot on a test cluster
- Adopt GA features in production
- Track the deprecation policy
Why โ Production should rely on GA or well-proven beta features.
Interview tip โ Say alpha features do not go to prod.
Q197 How do you list everything running in a namespace and see what is unhealthy?
Beginner
Situation read โ You are handed an unfamiliar namespace during an incident.
What I'd do โ
kubectl get all -n appfor the main workload objectskubectl get pods -n app -o wideto see nodes and restartskubectl get events -n app --sort-by=.lastTimestampkubectl top pods -n appfor resource usagekubectl describeon anything not Running or Ready
Why โ A few commands give you state, placement, events and usage within a minute.
Interview tip โ Note that get all does not include ConfigMaps, Secrets, Ingress or PVCs.
Q198 How do you stop and start a workload for the night without deleting it?
Beginner
Situation read โ A dev environment costs money overnight.
What I'd do โ
kubectl scale deploy --all --replicas=0 -n dev- Record the original counts first (
kubectl get deploy -n dev -o custom-columns=NAME:.metadata.name,REPLICAS:.spec.replicas) - Scale back up in the morning
- Automate with a CronJob and a scoped ServiceAccount, or KEDA cron scaler
- Keep PVCs, which are not deleted by scaling
Why โ Scaling to zero keeps all objects and data while releasing compute.
Interview tip โ Mention that GitOps will undo manual scaling unless paused.
Q199 How do you copy files in and out of a pod?
Beginner
Situation read โ You need to grab a heap dump from a pod.
What I'd do โ
kubectl cp app-pod:/tmp/heap.hprof ./heap.hprof -c app -n prod- For large files use
kubectl exec ... -- tar cf - /tmp | tar xf - - Check the image has
tarsince cp relies on it - Clean up the file in the pod afterwards
- Prefer shipping dumps to S3 automatically for production
Why โ kubectl cp streams a tar archive through the API server.
Interview tip โ Say distroless images need an ephemeral debug container instead.
Q200 What labels and annotations should every workload carry, and why?
Beginner
Situation read โ The platform team wants consistent metadata for cost and ownership.
What I'd do โ
- Use recommended labels such as
app.kubernetes.io/name,app.kubernetes.io/instance,app.kubernetes.io/version - Add
team,envandcost-centerlabels - Use annotations for non-identifying metadata such as runbook links
- Enforce with Kyverno or ValidatingAdmissionPolicy
- Query with
kubectl get pods -l team=payments
Why โ Labels drive selectors, cost allocation and policy, so they must be consistent.
Interview tip โ Remember labels select, annotations describe.