Skip to content
Tech Interview Prep
Technical interview guide

Containerization & Orchestration

Packaging an app with its dependencies via containers, and how Kubernetes schedules and manages them at scale.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Docker, OCI Image and Runtime specifications, and Kubernetes guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Decide whether two processes belong in one Pod.

Answer

The rule

Put two processes in one Pod only when they must share a network namespace, a volume, or a lifecycle. If they can talk over a Service and be deployed, scaled and owned separately, they are two workloads.

What a Pod actually shares

Containers in a Pod share a network namespace (one IP, one port space) plus IPC, any volumes you mount, and the ServiceAccount token. shareProcessNamespace: true adds a shared PID namespace. restartPolicy is a Pod-level field, not per container. That sharing is the reason to co-schedule, and it is also the risk.

Why shared fate bites

Readiness is the sharpest case. The kubelet ANDs every container's readiness into the Pod's Ready condition, and the endpoints controller gates Service endpoints on that condition. A sidecar whose readiness probe fails takes the healthy app container out of rotation. Liveness is different: a failing liveness probe restarts only its own container.

Resources are summed. The Pod's QoS class comes from the requests and limits of all its containers, so one sidecar with no requests drops the Pod from Guaranteed to Burstable and moves it earlier in node eviction order. Ports collide because the netns is shared. Identity is shared because every container mounts the same token by default.

Termination is the one place Kubernetes now helps: a native sidecar. An initContainers entry with restartPolicy: Always, beta since 1.29. Starts before the app containers and is terminated after them. Ordinary containers all receive SIGTERM in parallel, so a log shipper can die before it flushes.

CouplingMechanismSymptom
Networkone netns, one port spacesidecar binds 8080, app already holds it, CrashLoopBackOff
ReadinessPod Ready = AND of container readinessapp healthy, 0 endpoints, 503s
ResourcesQoS class from summed requests/limitssidecar with no requests → Burstable → evicted first
Identityone ServiceAccount token in every containersidecar inherits the app's RBAC
Terminationparallel SIGTERM unless native sidecarshipper killed mid-flush, logs lost

Trace: a sidecar readiness failure

  1. The sidecar's /ready probe fails three times; the kubelet marks that container Ready=false.
  2. The kubelet sets the Pod condition Ready=False. The app container is still running and still passing its own probe.
  3. The endpoints controller removes the Pod IP from the EndpointSlice.
  4. kube-proxy stops sending traffic there. Clients get 503s from the remaining Pods, or connection refused if this was the only replica.
  5. kubectl get pod shows READY 1/2; kubectl get endpointslice no longer lists the IP.

What to do instead

Use an init container for finite prerequisite work: it runs to completion, in order, before the app containers start. Use a native sidecar for continuous support whose lifecycle must bracket the app's. Keep anything independently deployed, scaled or owned in its own Deployment behind a Service: you pay a network hop and lose localhost, and you gain independent rollouts, an HPA per process, and a blast radius of one.

Before merging, test the couplings: kill the app container and watch the sidecar, kill the sidecar and watch the app, then check the Pod's QoS class and its endpoint membership after each.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design startup, readiness, and liveness probes.

Answer

The 90-second answer

Three probes answer three different questions, and the design rule is that each maps to exactly one control decision the kubelet can take.

  • startupProbe: "has this process finished booting?" While it runs, liveness and readiness are suspended. It succeeds once and never runs again. Its only job is to stop a slow boot from being mistaken for a hang.
  • readinessProbe: "should this pod be in the Service's EndpointSlice?" Failure removes the pod from endpoints and kube-proxy stops sending it new connections. It runs forever, so it must be cheap, local and bounded.
  • livenessProbe: "is this process wedged in a way only a restart fixes?" Failure makes the kubelet kill the container and restart it per restartPolicy. It must not depend on anything outside the process.

The failure mode that decides most designs: a liveness probe that checks a downstream dependency. When the database blips, every replica fails liveness at once, the kubelet kills them all, and a 5-second dependency hiccup becomes a fleet-wide restart storm with cold caches and a reconnect stampede. Readiness is the probe that should react to dependency loss; liveness should not.

Concrete configuration

YAML
startupProbe:
  httpGet: { path: /healthz/startup, port: 8081 }
  periodSeconds: 5
  failureThreshold: 30        # budget = 5s x 30 = 150s > 90s p99 boot
livenessProbe:
  httpGet: { path: /healthz/live, port: 8081 }
  periodSeconds: 10
  timeoutSeconds: 1
  failureThreshold: 3         # 30s of consecutive failure before restart
readinessProbe:
  httpGet: { path: /healthz/ready, port: 8081 }
  periodSeconds: 5
  timeoutSeconds: 1
  failureThreshold: 2         # out of endpoints within ~10s
  successThreshold: 1

Defaults worth knowing: periodSeconds 10, timeoutSeconds 1, failureThreshold 3, successThreshold 1, initialDelaySeconds 0. successThreshold must be 1 for liveness and startup; only readiness may be higher. HTTP probes treat 200–399 as success. grpc probes (GA in 1.27) call grpc.health.v1.Health/Check.

Sizing the budgets

probedecision it drivesbudget arithmeticwhat breaks if wrong
startuprestart a container that never bootedperiodSeconds × failureThreshold = 150stoo small → restart loop on a slow node; too large → a genuinely hung boot sits for minutes
livenessrestart a wedged processperiodSeconds × failureThreshold + timeoutSeconds = 31sbudget below worst-case GC pause → restarts under load, each dropping in-flight requests
readinessadd/remove from EndpointSlice~10s to removetoo aggressive → flapping endpoints, 502s at the load balancer

The liveness budget must exceed the longest legitimate pause: a stop-the-world GC, a long fsync, a CPU-throttled node. Measure it. If p99 GC pause is 12s, failureThreshold: 3 at periodSeconds: 10 is fine; at periodSeconds: 3 it is not.

Failure modes and how you see them

  • Restart storm from a shared dependency. All replicas fail liveness together. Detect with kubectl get events --field-selector reason=Unhealthy and kubelet's prober_probe_total{result="failed"}. Cost: each restart drops in-flight requests after terminationGracePeriodSeconds (default 30s) and empties warm caches.
  • Readiness flapping. A dependency that is slow rather than down makes readiness oscillate; endpoints churn and clients see connection resets. Detect via the readiness rate of prober_probe_total against endpoint count over time.
  • Probe endpoint is itself expensive. A readiness handler that queries the database adds load proportional to replica count every periodSeconds. Detect: prober_probe_duration_seconds climbing with pod count.
  • Probe port shares the saturated listener. Under overload the accept queue fills, the probe times out, liveness restarts the pod: the opposite of what you want. Serving probes on a separate port (8081 above) avoids it.

Trade-offs and when this design is wrong

  • Readiness that includes a hard dependency gives fast failover but couples your availability to that dependency's. If the dependency is shared, prefer a degraded mode: stay ready, serve stale or partial results, let it recover.
  • Liveness probes are optional. For a stateless service behind a load balancer that already removes unhealthy pods, a liveness probe mostly adds a way to make things worse. Use it when the process can genuinely deadlock (a single-threaded event loop, a lock-ordering bug) and you have no other way out.
  • initialDelaySeconds is a smell once you have a startup probe: a fixed guess where the startup probe is a measured budget.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Diagnose a CrashLoopBackOff after release.

Answer

First 90 seconds

Freeze the rollout, kubectl rollout pause deploy/<name>, so the deployment stops pushing the new revision to more replicas and you keep a stable set of failing pods to inspect. Pin the exact revision and image digest: kubectl rollout history deploy/<name> and kubectl get pod <pod> -o jsonpath='{.spec.containers[*].image}'. Digest, not tag: a mutable tag is how "the same image" behaves differently across nodes.

Then read the crash itself, not the symptom. CrashLoopBackOff is not an error; it is the kubelet's restart policy. The container exits, the kubelet restarts it, and after repeated failures it backs off exponentially: 10s, 20s, 40s, … capped at 5 minutes. A pod failing for ten minutes therefore shows only a handful of restarts: the widening gap is the backoff, not recovery.

Read the exit

kubectl describe pod <pod> gives Last State: Terminated with Reason, Exit Code, Signal. That triple discriminates the cause:

ExitSignalReasonMeans
137SIGKILLOOMKilledmemory limit hit
137SIGKILL(none)liveness probe killed it
143SIGTERM(none)graceful shutdown: probe or node drain
1—Errorapp-level failure, read the logs
0—Completedprocess exited cleanly; restartPolicy: Always keeps restarting it

137 is ambiguous: an OOM kill and a liveness kill both produce it. The Reason field separates them. If Reason: OOMKilled, compare kubectl top pod against the limit; a release that raised concurrency or cache size is the usual culprit.

Get the logs before they are gone

The current container's logs are from the new attempt. The crash output is in the previous instance: kubectl logs <pod> --previous. That holds only one prior instance and disappears once the container is recreated, so capture it now. Anything written to the container's writable layer is also lost on restart; only emptyDir volumes survive within the pod's lifetime.

Events and mounts

kubectl get events --field-selector involvedObject.name=<pod> --sort-by=.lastTimestamp surfaces FailedMount, Unhealthy, BackOff. A FailedMount on a ConfigMap or Secret means the release referenced a key that does not exist: the container never starts, so logs are empty and the exit code misleads.

Mitigate

kubectl rollout undo deploy/<name> is the fast path, but only if the release did not run a forward-only migration. Rolling the old image back against a migrated schema often crashes differently: check whether the release included a schema change before undoing. Otherwise fix forward: correct the probe, raise the limit, or add the missing key.

Failure modes

  • Rollback against a migrated database: old code, new schema, a new crash.
  • Aggressive liveness probe (initialDelaySeconds shorter than app boot) restarting a healthy app: looks like a crash loop, is not one.
  • Node-level eviction (disk or memory pressure) killing pods across deployments: check kubectl describe node before blaming the release.
  • Evidence loss: --previous overwritten, events aged out (default 1h TTL), logs rotated.

Then fix the pipeline that let it through: the test that missed the config key, the probe never validated against real boot time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How do you configure and enforce SecurityContext restrictions like runAsNonRoot, readOnlyRootFilesystem, and Linux capabilities across Kubernetes Pods?

Answer

Core answer

Set securityContext in two places: at the Pod level for identity and filesystem ownership (runAsNonRoot, runAsUser, runAsGroup, fsGroup, seccompProfile), and at the container level for kernel-level restrictions (allowPrivilegeEscalation, readOnlyRootFilesystem, capabilities). Container fields override Pod defaults for that container.

Configuration alone is not enforcement: anyone can submit a Pod without it. Bind it to admission with Pod Security Standards (PSS), the built-in admission controller driven by namespace labels. The restricted profile validates allowPrivilegeEscalation: false, capabilities.drop: [ALL], runAsNonRoot: true, a seccompProfile of RuntimeDefault or Localhost, and a restricted volume set. It does not validate readOnlyRootFilesystem: a Pod with a writable rootfs passes restricted. Enforce that field separately with a policy engine or a CI check.

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: secure-api
  namespace: payments
spec:
  replicas: 3
  selector:
    matchLabels: { app: secure-api }
  template:
    metadata:
      labels: { app: secure-api }
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        fsGroup: 10001
        fsGroupChangePolicy: OnRootMismatch
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: api
        image: internal-registry.io/payments/api:v1.4.2
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]
        volumeMounts:
        - { name: tmp, mountPath: /tmp }
      volumes:
      - name: tmp
        emptyDir:
          medium: Memory
          sizeLimit: 64Mi

What each control actually does

SettingScopeMechanismFailure mode
runAsNonRoot: truePod & containerKubelet resolves the effective UID (runAsUser if set, otherwise the image's USER) and refuses to create the container if it is 0.CreateContainerConfigError. A non-numeric USER (e.g. USER app) also fails, because the kubelet cannot prove it is non-root. Set runAsUser explicitly.
readOnlyRootFilesystem: trueContainerRuntime mounts the container rootfs read-only.EROFS on any write. nginx needs /var/cache/nginx and /var/run writable; mount emptyDir there. Not checked by restricted.
capabilities.drop: [ALL]ContainerClears the capability bounding, permitted and effective sets for the container process.App dies if it needs a capability. Under restricted the only one you may add back is NET_BIND_SERVICE; otherwise bind to a port above 1024.
allowPrivilegeEscalation: falseContainerSets no_new_privs via prctl(), so setuid/setgid binaries cannot gain privileges.Blocks sudo and setuid helpers. Required by restricted.
seccompProfile: RuntimeDefaultPod & containerApplies the container runtime's default syscall filter.Required by restricted; without it the Pod is rejected.

emptyDir with medium: Memory is tmpfs and counts against the Pod's memory cgroup: sizeLimit: 64Mi caps it, but the container still needs headroom in its memory limit.

Enforcement

YAML
apiVersion: v1
kind: Namespace
metadata:
  name: payments
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: v1.29
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted

When a Pod violates the enforced profile, the API server rejects the Pod object at admission with 403 Forbidden. The Deployment and ReplicaSet objects are accepted; the ReplicaSet controller logs the rejection and the Deployment reports no available replicas. So a manifest that omits allowPrivilegeEscalation: false, fails to drop ALL, or leaves runAsNonRoot unset never produces a running Pod, but one that only omits readOnlyRootFilesystem does.

Two operational points: PSS is evaluated only when a Pod is created, so tightening the label does not evict running Pods; and changing the enforce label makes the API server return a warning listing the Pods in the namespace that violate the new profile, which is the fastest way to see your blast radius before rolling it out. Pin enforce-version rather than using latest so a cluster upgrade does not silently change what is rejected. For rules PSS does not cover (readOnlyRootFilesystem, image registries, resource limits) use Kyverno or Gatekeeper, or fail the manifest in CI.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Size container requests and limits.

Answer

Assumptions: Linux nodes on cgroup v2, kubelet eviction defaults unchanged, and a service whose traffic swings about 2x across the day. Under those, my default is that memory request equals memory limit and equals the measured p99 working set plus headroom, the CPU request sits near the p95, and there is no CPU limit unless a platform policy forces one.

The two resources fail differently, so the defaults differ.

A request is a scheduling and eviction input, not a cap. The scheduler fits pods by summing requests against node allocatable. The kubelet turns CPU requests into relative weight (cpu.weight on cgroup v2, cpu.shares on v1), so under contention a pod with twice the request gets roughly twice the CPU; memory requests rank eviction victims.

A CPU limit is a CFS quota. cpu.max reads 'quota period', and the period defaults to 100000 microseconds, so limit 1 becomes '100000 100000'. The quota refills each period, which caps the burst inside a period rather than the average. A pod that wants 1.2 cores spends its 100 ms of quota 83 ms into the period and stalls for the remaining 17 ms, every period. Its 10-second average still reads under 1 core, so the CPU dashboard looks fine while p99 latency jumps.

A memory limit is memory.max, a hard wall. Cross it and the kernel OOM killer takes a process in that cgroup; the container exits 137 and restarts on backoff. No throttle, no warning.

Sizing on real-ish numbers. Go service, seven days of data: CPU p95 0.55 cores, p99 0.9, with bursts to 1.6 for about 40 ms; working set p99 480 MiB. Freeze:

resources:
  requests:
    cpu: 600m
    memory: 768Mi
  limits:
    memory: 768Mi

768Mi gives about 1.6x the p99 working set, which covers page cache and heap drift. Omitting the CPU limit keeps the pod Burstable; if something requires Guaranteed, raise the CPU request to match the limit, because request equal to limit is also what ranks a pod last when the kubelet evicts under node pressure. If a policy forces a CPU limit, put it at 1.5-2x the request. A JVM needs the same care in reverse: it is container-aware from JDK 10 and defaults MaxRAMPercentage to 25, so a 1Gi limit with a 1Gi heap gets OOM-killed by its own metaspace and thread stacks.

SignalWhere to lookAct when
CFS throttlingrate(container_cpu_cfs_throttled_periods_total[5m]) / rate(container_cpu_cfs_periods_total[5m])above 0.05 and p99 latency moved with it
OOM killpod last terminated reason OOMKilled, exit 137twice in a week, or once on a user-visible path
Node pressurekubelet eviction-hard default memory.available < 100Mipods show reason Evicted, Burstable pods over request go first
Request driftsum(requests) against sum(container_memory_working_set_bytes) per noderatio above 1.3 strands capacity, below 1.0 means the scheduler is oversubscribing

Read the table literally: throttling above 0.05 with a latency move means the CPU limit is too tight. A repeat OOMKilled means the limit is under the real working set, and if working set also climbs day over day, 15 MiB/day is a leak and not a sizing problem. Reason Evicted instead of OOMKilled means the node ran out, not the container. Exit 137 on its own proves none of those, so read the terminated reason field.

Finally, set LimitRange defaultRequest and maxLimitRequestRatio so nobody ships a pod with no requests, and use VPA in recommendation mode for a starting number, remembering that Auto mode restarts pods to apply a change. Re-run the exercise after any shift in the dependency mix or traffic shape.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Respond to node memory pressure and evictions.

Answer

Clarify first. "Node memory pressure" covers two events that look identical on a dashboard: the kernel OOM-killing a container, and the kubelet evicting a pod. Different triggers, different fixes, so I separate them before touching anything.

Assumptions: kubelet defaults, cgroup v2, metrics-server available, and I can read node events.

Core answer. Check kubectl describe node <n> for the MemoryPressure condition and the node.kubernetes.io/memory-pressure:NoSchedule taint, then kubectl get events --field-selector reason=Evicted and each pod's lastState.terminated.reason. OOMKilled means a container hit its own cgroup limit. Evicted with phase Failed means the node ran out of allocatable memory. Then look at QoS class and requests per pod. Immediate mitigation: pause rollouts, add capacity, or shed low-priority work. Raising limits is the wrong first move: it converts a contained OOM into node-wide eviction.

Mechanism. The kubelet computes memory.available = capacity - working set, where working set is usage minus inactive file cache, so page cache doesn't count. Defaults: --eviction-hard memory.available<100Mi, --eviction-soft memory.available<1.5Gi with a 1m30s grace period. Crossing hard evicts immediately; soft starts the grace clock. Ranking: pods using more than their requests go first, then lower priority, then larger usage relative to requests. BestEffort first, Guaranteed last. Eviction is graceful (SIGTERM, terminationGracePeriodSeconds, then SIGKILL) and the pod ends Failed/Evicted. --eviction-minimum-reclaim defaults to 0, so the kubelet reclaims only to the threshold and can sit right at the boundary.

OOM is different: the container's cgroup memory.max is its limit, and the kernel OOM killer picks a process inside it. The container restarts in place, restartCount increments, and the pod stays on the node. oom_score_adj comes from QoS: Guaranteed -997, BestEffort 1000, Burstable between 2 and 999 scaled by request size. Priority does not change this: a high-priority Burstable pod can still be OOM-killed.

QoSHow it's setEviction orderoom_score_adj
Guaranteedrequests == limits for CPU and memory on every containerlast-997
Burstableat least one request or limit set, not all equalmiddle2..999
BestEffortno requests or limits anywherefirst1000

Worked trace. 16 GiB node, --kube-reserved=memory=1Gi, --system-reserved=memory=1Gi, default eviction-hard memory.available<100Mi. Allocatable ≈ 16 − 1 − 1 − 0.1 = 13.9 GiB. Pod A: request 512Mi, limit 1Gi, working set 900Mi. Burstable, over request, so it sits near the front of the eviction queue. Pod B: request 1Gi, limit 1Gi, working set 700Mi. Guaranteed, evicted last. If Pod A's working set instead reaches 1Gi, the kernel OOM-kills it and Pod B is untouched.

Failure modes and how I'd catch them.

  • Raising the limit to stop OOMKilled: the container grows into the new headroom, node pressure returns, and other pods get evicted. Detect: MemoryPressure true plus Evicted events on pods that didn't change.
  • Pods with no requests: they're BestEffort, evicted first, and the scheduler can't bin-pack them. Detect: kubectl get pod -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].resources}{"\n"}{end}' showing empty resources.
  • Eviction thrash: the pod is rescheduled to the same node and evicted again. Detect: repeated Evicted events for one workload, and the MemoryPressure condition flapping around --eviction-pressure-transition-period (default 5m).
  • system-reserved=0: the kernel OOM killer can pick kubelet or containerd and the node goes NotReady. Detect: kubelet restart count, dmesg oom-kill lines naming kubelet.
  • Alerting on free -m: page cache inflates usage and pages you for nothing. Detect: compare free against container_memory_working_set_bytes.

Prevention. Set requests on everything, use Guaranteed for workloads that must survive, reserve with kube-reserved/system-reserved, give critical pods a PriorityClass, and verify the numbers with a drain or a memory hog on a staging node before trusting them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Use PodDisruptionBudgets correctly.

Answer

Core answer (say this first)

A PodDisruptionBudget is a gate on the eviction API, nothing more. It stops voluntary disruptions (kubectl drain, cluster-autoscaler scale-down, node upgrades) from taking out more pods than you can afford at once. It does not protect against node crashes, kubelet failures, OOM kills, or kubectl delete pod; those never touch the eviction API. So I'd open by naming what it does not cover, then how I set it.

Set exactly one of minAvailable or maxUnavailable, derived from the application's quorum or capacity, not from the replica count. A 3-replica stateless service that tolerates one loss gets minAvailable: 2. A quorum system gets minAvailable equal to the quorum size (2 of 3, 3 of 5) because losing quorum is worse than losing a pod.

YAML
apiVersion: policy/v1        # GA since 1.21; policy/v1beta1 removed in 1.25
kind: PodDisruptionBudget
metadata:
  name: checkout-pdb
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: checkout

Mechanism

The disruption controller watches the PDB and the pods its selector matches, and writes status:

fieldmeaning
expectedPodspods matched by the selector
currentHealthymatched pods that are Ready
desiredHealthyminAvailable resolved to an integer
disruptionsAllowedmax(0, currentHealthy - desiredHealthy)

Eviction is a POST to /api/v1/namespaces/<ns>/pods/<name>/eviction with a policy/v1 Eviction object. The API server allows it only if every PDB selecting that pod has disruptionsAllowed > 0; otherwise it returns 429 Too Many Requests. kubectl drain uses the eviction API by default and retries on 429, so a blocked drain looks like a hang rather than an error.

Trade-offs

minAvailable vs maxUnavailable: use minAvailable when the floor is what matters (quorum, capacity), maxUnavailable when you want the budget to scale with replicas. Percentages round: minAvailable up, maxUnavailable down. At 5 replicas, minAvailable: 50% resolves to 3, allowing 2 disruptions; maxUnavailable: 50% resolves to 2, allowing 3. Pick the one whose rounding you can defend.

Failure modes

  • minAvailable equal to the replica count → disruptionsAllowed is always 0 → drain blocks forever. Detect: kubectl get pdb shows ALLOWED DISRUPTIONS 0, and drain logs "Cannot evict pod as it would violate the pod's disruption budget."
  • A failing readiness probe drops currentHealthy below desiredHealthy → disruptionsAllowed 0 → drain blocks even though the pods are running. Detect: kubectl get pdb <name> -o yaml shows status.currentHealthy under status.desiredHealthy.
  • Selector typo → status.expectedPods: 0 → the PDB silently protects nothing.
  • Bare pods with no controller: eviction succeeds but nothing recreates them, so capacity is permanently lost.
  • PDBs do not gate rolling updates. A Deployment rollout uses its own maxUnavailable/maxSurge, not the eviction API, so don't expect the PDB to slow a bad rollout.

Override: kubectl drain --disable-eviction deletes pods directly, bypassing the PDB. That's a break-glass action with a named owner, not a default.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Plan resilient Kubernetes scheduling.

Answer

First I'd ask: what's the SLO, how many failure domains, and what blast radius are we designing for? Assume 3 AZs, 12 nodes (4 per AZ), a stateless API with 6 replicas, p99 latency SLO 200 ms, and a Postgres StatefulSet with 3 replicas. The goal is to survive one AZ loss without dropping below the SLO.

The core mechanism is topologySpreadConstraints. For the API:

YAML
topologySpreadConstraints:
- maxSkew: 1
  topologyKey: topology.kubernetes.io/zone
  whenUnsatisfiable: DoNotSchedule
  labelSelector:
    matchLabels: app: api
- maxSkew: 1
  topologyKey: kubernetes.io/hostname
  whenUnsatisfiable: ScheduleAnyway
  labelSelector:
    matchLabels: app: api

maxSkew: 1 means the difference between the zone with the most and fewest matching pods is at most 1. DoNotSchedule makes it hard: if a zone is lost and the remaining zones can't satisfy skew ≤ 1, new pods stay Pending. That's the trade-off. For the API I'd use DoNotSchedule on zone because losing a zone still leaves 4 replicas across 2 zones, and I want even spread. For a batch job that can tolerate concentration, ScheduleAnyway keeps it schedulable.

PodDisruptionBudget is the other half, but it only covers voluntary disruptions: drain, eviction API, cluster autoscaler scale-down. It does not protect against a node crash. For the API:

YAML
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: api-pdb
spec:
  minAvailable: 4
  selector:
    matchLabels:
      app: api

With 6 replicas, minAvailable: 4 allows 2 concurrent evictions. If you set minAvailable equal to replicas, drain hangs forever: kubectl drain has --timeout 0 by default, so it retries indefinitely and the eviction API returns 429 Too Many Requests. Detection: kubectl get pdb shows DISRUPTIONS ALLOWED 0, and drain never completes.

Taints and tolerations: dedicated GPU nodes get taint nvidia.com/gpu=true:NoSchedule, and only GPU pods tolerate it. If you taint a pool NoSchedule and forget the toleration on a DaemonSet, the DaemonSet pods stay Pending. Node affinity for capabilities: nodeAffinity with requiredDuringSchedulingIgnoredDuringExecution on kubernetes.io/arch: amd64 or a GPU label. nodeSelector is simpler but only equality; nodeAffinity supports In, NotIn, Exists.

Priority: PriorityClass for the API at 1000000, batch at 1000. Preemption evicts lower-priority pods, but preemption does not respect PodDisruptionBudgets: it bypasses the eviction API. So a high-priority pod can evict a pod that a PDB was protecting. Use priority sparingly.

Autoscaler: cluster autoscaler scans every 10 s (--scan-interval), but node provisioning takes 1–5 minutes for a cloud VM, longer for GPU. So a burst that needs 4 new nodes can take 5+ minutes to become Ready. If the SLO is 200 ms and the queue drains in 30 s, autoscaling won't save you; you need headroom.

Failure modes and detection:

  • Zone loss: nodes go NotReady after 40 s (node-monitor-grace-period), pods are evicted after 5 minutes (tolerationSeconds 300 on the not-ready taint). If the API has 6 replicas spread 2/2/2 and one zone dies, you're at 4 replicas. If the PDB minAvailable is 4, you're exactly at the boundary: any further voluntary disruption is blocked.
  • Hard topology spread + zone loss: new pods Pending with event didn't match pod topology spread constraints. Detection: kubectl get events --field-selector reason=FailedScheduling.
  • Image pull: say a 2 GB image on a fresh node takes 1–2 minutes to pull. If the pod's startup probe fails during that, it restarts. Detection: kubectl describe pod shows ImagePullBackOff or ContainerCreating.
  • Capacity exhaustion: cluster autoscaler hits max node group size, event max node group size reached. Detection: Pending pods with no scale-up event.

Test: drain a node with kubectl drain --ignore-daemonsets --delete-emptydir-data, watch PDB disruptionsAllowed. Kill a zone in a staging cluster, measure pending time and p99. Measure skew: count pods per zone with kubectl get pods -o json | jq.

The one thing I'd not do: set hard anti-affinity with requiredDuringSchedulingIgnoredDuringExecution on hostname for a 6-replica deployment on 4 nodes. It can't schedule. Topology spread is the right tool for even distribution; anti-affinity is for strict pairwise separation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design graceful shutdown for a request-serving Pod.

Answer

The 90-second answer

Assume an HTTP service behind a Kubernetes Service, default terminationGracePeriodSeconds: 30, and a Go server. The goal: no request dropped, no write lost when the pod is deleted.

The ordering is the whole answer. On deletion the API server stamps deletionTimestamp; the endpoint controller removes the pod from EndpointSlices, but that removal takes time to reach kube-proxy and the load balancer: roughly 1–10s, longer through an ingress. Meanwhile the kubelet runs the preStop hook, then sends SIGTERM to PID 1, then SIGKILLs at the grace deadline. So the sequence must be: cover the propagation window, fail readiness, drain, exit. All inside 30s.

Concretely: preStop sleeps 10s while the app keeps serving normally, absorbing traffic from stale LB state. Then SIGTERM arrives; the app flips readiness to false, waits a few seconds for the last endpoint update, and calls http.Server.Shutdown, which stops accepting new connections, closes idle keep-alive connections, and waits for active handlers. Budget: 10s preStop + 5s readiness settle + 15s drain = 30s, with the drain timeout set below the remaining grace so the process exits cleanly instead of being SIGKILLed.

Why readiness must fail before the LB stops routing: readiness is polled (periodSeconds), so flipping it is not instantaneous, and endpoint propagation is a separate async step. Skip the wait and the LB keeps sending new connections to a server that has already stopped accepting: those get connection-refused.

Keep-alive is the subtle part. A client holds an open TCP connection and reuses it for the next request. Shutdown closes idle connections and sends Connection: close on responses, so a well-behaved client reconnects elsewhere. A client that ignores it and pipelines a request onto a closing connection sees a reset: that is why you drain rather than close immediately.

Go
var ready atomic.Bool
ready.Store(true)
mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
    if ready.Load() {
        w.WriteHeader(http.StatusOK)
    } else {
        w.WriteHeader(http.StatusServiceUnavailable)
    }
})

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer stop()
<-ctx.Done()

ready.Store(false)          // fail readiness first

time.Sleep(5 * time.Second) // let endpoint removal propagate

shutCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(shutCtx); err != nil {
    log.Printf("drain incomplete: %v", err) // leftovers get SIGKILLed
}

Trace: SIGTERM at t=0. ready=false at t=0. LB still routes until ~t=5. Shutdown at t=5 stops accepting, closes idle conns, waits for in-flight. A 12s request that started at t=4 finishes at t=16, inside the 15s drain window. At t=30 the kubelet SIGKILLs anything left. Note Shutdown does not wait for hijacked connections (websockets): track those separately or they are cut at t=30.

Alternatives: skip preStop and do the sleep in-process after SIGTERM. One place to reason about, but the app must own the propagation window and the grace clock is already running. Use preStop when you cannot change the app or run sidecars. For queue consumers the equivalent is stop fetching, finish the in-flight message, then ack: never ack-then-process.

Failure modes and detection:

  • Unhandled SIGTERM in PID 1 → process dies instantly, in-flight requests reset. Detect: connection-reset count and 5xx rate spike during rollout.
  • Request longer than the drain budget → SIGKILL mid-write. Detect: p99 request-duration histogram against the grace period; 502s at the LB.
  • Sidecar still accepting after the app exits → 503s. Detect: per-container exit ordering in pod events.
  • Duplicate work on retry → detect with idempotency keys and dedupe counters.

Trade-off: a longer grace period drains more safely but slows every rollout and node drain; 30s is the default for a reason. Set it from your p99.9 request duration plus propagation delay, not by feel.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design a safe rolling Deployment.

Answer

Core answer

Assume a stateless HTTP service, 20 replicas at peak, a Kubernetes Deployment, and a schema change that is backward compatible (expand/contract). If any of those is false, say so before designing: the design changes.

A safe rolling deployment has four parts: an immutable artifact, a rollout budget sized from capacity, a readiness gate that reflects real serving ability, and a decision rule for stopping.

Pin the image by digest, not tag. Tags are mutable; a digest is the exact bytes you tested.

Size the rollout budget from headroom, not from a default. maxUnavailable: 0 with maxSurge: 2 on 20 replicas means the controller adds 2 pods, waits for them to be Ready, then terminates 2 old ones. Available capacity never drops below 20, but you need room for 22: 10% headroom. If the cluster is already at 100% CPU, the surge pods get throttled and readiness times out.

Arithmetic: 20 pods × 500 rps = 10,000 rps capacity; peak is 8,000. maxSurge: 2 gives 11,000: fine. maxUnavailable: 2 drops you to 9,000, still above peak but only 12% margin; one node loss during the rollout takes you under. That is why maxUnavailable: 0 is the safer default for latency-sensitive services.

Readiness must reflect the ability to serve, not just "process started". A startup probe covers slow boot; readiness covers dependency health. minReadySeconds: 30 means a pod must stay Ready for 30s before it counts: this catches pods that pass readiness once and then crashloop.

YAML
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 2
    maxUnavailable: 0
minReadySeconds: 30
progressDeadlineSeconds: 600

progressDeadlineSeconds does not roll back. Default 600s. When the new ReplicaSet makes no progress for 600s, the controller sets ProgressDeadlineExceeded on the Deployment and stops. It does not revert. You need a watcher (CI/CD, Argo Rollouts, Flagger) to act on that condition. This is the most common misconception about rolling updates.

Termination: terminationGracePeriodSeconds defaults to 30. Endpoint removal is asynchronous: kube-proxy rules propagate after the pod is marked terminating, so in-flight requests can still arrive. A preStop sleep of 5–10s covers propagation; then SIGTERM, then drain.

Failure modes and how you see them:

failuredetection signaloperational cost
slow image pullpods Pending / ImagePullBackOffrollout stalls until the deadline; no auto-rollback
unready podskube_deployment_status_replicas_unavailable > 0surge pods hold capacity, old pods stay up
node loss mid-rolloutnode NotReady, pods evictedwith maxUnavailable: 0, capacity dips below desired
stalled progressProgressDeadlineExceeded conditionneeds an external watcher to act
drain blockedPDB eviction failuresnode drain hangs, rollout cannot complete

Trade-offs: rolling cannot split traffic by percentage. Each pod is all-or-nothing via readiness. If you need a 5% canary with automated metric analysis, use Argo Rollouts or Flagger. Rolling is the wrong tool when the schema change is not backward compatible (do expand/contract first), when you need an atomic switch (blue/green), or when mixed versions cannot coexist (protocol changes).

Roll back only if the new version wrote no state the old version cannot read. Otherwise roll forward.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How does Kubernetes implement Pod-to-Pod networking, and how do CNI plugins route traffic across different nodes?

Answer

The Kubernetes network model mandates three fundamental invariants:

  1. Every Pod receives its own unique IP address within the cluster.
  2. Pods can communicate with all other Pods on any node without Network Address Translation (NAT).
  3. Agents on a node (like kubelet) can communicate with all Pods on that same node.

Intra-Node Plumbing (Same Node)

When a Pod is scheduled, the container runtime (e.g., containerd via CRI) creates a Linux network namespace for the Pod sandbox. The Container Network Interface (CNI) plugin is invoked to set up interfaces:

  • It creates a virtual Ethernet pair (veth pair).
  • One end (eth0) is placed inside the Pod's network namespace and assigned the Pod CIDR IP.
  • The peer end (e.g., vethxxxx) resides in the host root network namespace.
  • For bridge-based setups, the host veth attaches to a Linux bridge (cbr0 or plugin bridge). For routing-based setups (such as Cilium or Calico in eBPF/host-routing mode), the peer interface attaches directly to the host routing table or TC/eBPF hooks.

Traffic between two Pods on the same node flows: Pod A eth0 -> vethA -> host bridge / routing / eBPF -> vethB -> Pod B eth0.

Cross-Node Routing (Different Nodes)

When Pod A on Node 1 (10.244.1.5) talks to Pod B on Node 2 (10.244.2.8), the packet leaves vethA into Node 1's root namespace. Because 10.244.2.8 is not local, the host routing table directs the packet according to the CNI's design pattern:

Pod A (10.244.1.5)           Node 1 (192.168.1.10)              Node 2 (192.168.1.20)           Pod B (10.244.2.8)
[ eth0 ] === vethA ===> [ Host Routing / Encapsulation ] ===> [ Decapsulation / Host Routing ] === vethB ===> [ eth0 ]
                             (VXLAN / BGP / VPC Route)                 (Inner packet restored)

There are two primary paradigms across nodes:

MechanismImplementation (e.g., Flannel VXLAN, Geneve)Direct / Underlay Routing (e.g., Calico BGP, AWS VPC CNI)
Packet StructureOuter UDP packet (Host IP header + UDP 4789 + VXLAN header + Original IP packet).Unmodified original packet with Pod source/dest IPs routed directly.
Underlying Network RequirementL3 IP connectivity between nodes; completely agnostic to fabric switches.Fabric/VPC must know Pod CIDRs (via BGP peering or VPC route table limits).
Overhead~50 bytes encap overhead per packet; requires reducing MTU (e.g., 1450 vs 1500) or causes fragmentation. CPU cost for encap/decap.Zero encapsulation overhead; native wire MTU (e.g., 9000 jumbo frames supported without penalty).

Common Failure Modes & Diagnostics

  1. MTU Mismatch & PMTU Blackholes: If the overlay adds a 50-byte VXLAN header but the Pod interface MTU remains at 1500 instead of 1450, TCP handshakes (small packets) succeed, but large bulk transfers (DF bit set) hang silently. Diagnose via ip link show inside the Pod vs the host physical device, or ping -M do -s 1472 <dest-ip>.
  2. rp_filter (Reverse Path Filtering): Asymmetric routing across multiple host NICs can cause the kernel to drop incoming cross-node Pod packets if net.ipv4.conf.all.rp_filter = 1 (strict mode). Check drops via nstat -az TcpExtIPReversePathFilter or dropwatch.
  3. Node IPAM CIDR Exhaustion: Kubelet allocates a /24 subnet per node by default from the cluster podCIDR. If node IPAM runs out of IPs or leases fail during rapid Pod churn, Pods get stuck in ContainerCreating with CNI allocation errors (no IP addresses available in range).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Debug a Service that has no reachable endpoints.

Answer

I’d split this into three cases before touching anything: no endpoints at all, endpoints that exist but are not ready, or ready endpoints that are unreachable. Those are different layers, and the first command tells you which one you’re in.

Assume a ClusterIP Service in a current Kubernetes release, EndpointSlices enabled, kube-proxy in iptables or IPVS mode. If it’s a LoadBalancer, the same diagnosis applies plus cloud health checks.

Start with:

Shell
kubectl get svc web -n prod -o wide
kubectl get endpointslice -n prod -l kubernetes.io/service-name=web -o yaml
kubectl get pods -n prod -l app=web -o wide --show-labels

The mechanism: the EndpointSlice controller watches the Service and Pods. It selects Pods whose labels match spec.selector, filters out Pods that are not Ready unless publishNotReadyAddresses: true, and writes addresses plus the resolved targetPort into EndpointSlices. kube-proxy watches Services and EndpointSlices and programs DNAT rules on every node so ClusterIP:port goes to PodIP:targetPort. So a failure is either selection, readiness, port mapping, or the dataplane.

Worked trace. Service web has selector: app=web, port: 80, targetPort: 8080. Pods:

$ kubectl get pods -n prod -l app=web -o wide --show-labels
NAME    READY   STATUS    IP         LABELS
web-0   0/1     Running   10.1.2.3   app=web

EndpointSlice:

YAML
endpoints:
- addresses: ["10.1.2.3"]
  conditions:
    ready: false
    serving: false
    terminating: false
ports:
- name: http
  port: 8080
  protocol: TCP

That means the selector matched and the port resolved, but the Pod is not Ready. kubectl describe pod web-0 shows the readiness probe failing, say HTTP 500 on /healthz. Fix the probe or the app. If the EndpointSlice list is empty instead, the selector or labels are wrong: kubectl get pods -l app=web returns nothing. If ready: true but clients still fail, move to the dataplane.

For ready endpoints that are unreachable, test from a representative client:

Shell
kubectl exec -n prod client -- curl -sv --max-time 2 http://web.prod.svc.cluster.local
kubectl exec -n prod web-0 -- ss -ltnp | grep 8080
kubectl get networkpolicy -n prod

DNS resolving but connection refused usually means targetPort is wrong or the app is not listening on 8080. A timeout from all clients points at NetworkPolicy or kube-proxy. A timeout from one node only points at stale kube-proxy rules: check iptables-save | grep web or ipvsadm -Ln on that node. For a LoadBalancer, check the cloud target group health; if externalTrafficPolicy: Local, only nodes with a local Pod are healthy, so a node without one gets marked unhealthy.

Failure modes and detection:

SymptomFirst checkLikely cause
EndpointSlice list emptykubectl get pods -l app=webselector/label mismatch
EndpointSlice ready: falsekubectl describe podreadiness probe failing, terminating Pod
ready: true, connection refusedkubectl exec pod -- ss -ltnpwrong targetPort, app not listening
ready: true, timeout from one node`iptables-savegrep web`
ready: true, timeout from all clientskubectl get networkpolicydefault-deny policy
LB unhealthycloud target group healthhealth check port/path, externalTrafficPolicy: Local

Trade-offs: publishNotReadyAddresses: true can unblock headless or stateful bootstrap, but it routes normal traffic to Pods that may not serve it. externalTrafficPolicy: Local preserves source IP and avoids an extra hop, but concentrates load and can fail health checks when no local endpoint exists. Disabling NetworkPolicy or opening all ports is fast but risky; prefer a scoped temporary allow rule and a test Pod with the same labels.

Once fixed, add a synthetic check that hits the Service DNS name from a client Pod and alerts when EndpointSlices for that Service have zero ready endpoints for more than two scrape intervals.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design Kubernetes Service discovery and traffic.

Answer

Core answer

Service is L4: a stable virtual IP and DNS name in front of a changing set of pod IPs. It does not do path routing, TLS termination, or authorization: those belong to a Gateway/Ingress and to your application.

Three questions decide the design before anything else:

  1. Is the client in-cluster or external?
  2. Is L4 enough, or do you need L7?
  3. Does anything downstream need the real client IP?

Assumptions I'll state up front: in-cluster TCP clients, one cluster, IPv4 single-stack, no L7 requirement.

Design: a ClusterIP Service with a selector matching pod labels, named ports, and targetPort set to the container port name. The EndpointSlice controller watches pods matching the selector and writes ready pod IPs into EndpointSlices (100 endpoints per slice by default). kube-proxy watches those slices and programs DNAT rules, so a client hitting the ClusterIP is rewritten to a pod IP. Clients resolve <service>.<namespace>.svc.cluster.local.

Mechanism, traced

Client → CoreDNS → 10.96.0.42 (ClusterIP) → kube-proxy iptables DNAT → 10.244.1.7:8080 (pod). Readiness gates this: a pod with Ready=False is not in the EndpointSlice, so it gets no new connections. That is the whole point of the abstraction: pod churn is invisible to clients.

Trade-offs

DecisionChooseWhen
selector vs manual EndpointSliceselectordefault; manual only for backends with no pod (external DB, VM)
ClusterIP / NodePort / LoadBalancer / ExternalNameClusterIPin-cluster; LoadBalancer for external L4; ExternalName is a CNAME, no proxying
externalTrafficPolicy Cluster vs LocalLocalwhen you need source IP; costs a hop and drops traffic if no local endpoint
iptables vs IPVSIPVSthousands of Services; iptables is O(n) rules and slow to sync

Failure modes

  • Overlapping selectors: two Services selecting the same pods both get endpoints, so a pod that should not serve traffic does. Detect with kubectl get endpointslice -l kubernetes.io/service-name=<svc>.
  • No ready endpoints: kube-proxy installs a REJECT rule, so clients get connection refused, not a timeout. Refused means check readiness probes, not the network.
  • Connection draining: removing an endpoint does not kill existing conntrack entries. Long-lived TCP flows keep hitting a terminating pod until the entry expires. Fix with a preStop sleep plus terminationGracePeriodSeconds (default 30s) and client retries.
  • DNS caching: the default ndots:5 makes short names do search-path lookups, and a stale negative cache can outlive a rollout. Use FQDNs.
  • Zone skew: endpoints spread across zones while clients sit in one; topology-aware routing (trafficDistribution: PreferClose) keeps traffic local but can overload a single zone.
  • Session affinity: sessionAffinity: ClientIP defaults to a 10800s (3h) timeout; it pins a client to one pod and breaks even load balancing.

Access control

Service routing is not authorization. Add NetworkPolicy for L3/L4 and app-level authn/authz. A ClusterIP is reachable by anything in the cluster that can route to it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you configure and debug Kubernetes NetworkPolicies to enforce pod isolation and default-deny traffic?

Answer

Core answer. Kubernetes networking is flat by default: every pod can reach every other pod in every namespace. NetworkPolicy is an additive allow-list: there is no deny rule. So isolation is always two moves: (1) a default-deny policy in the namespace, (2) layered allow policies for the flows you actually need. A pod becomes isolated only for the policyTypes listed in a policy that selects it; unlisted traffic in that direction is dropped. None of it works unless the CNI plugin enforces policy: the API server accepts the manifest either way.

1. Default-deny, then allow

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

podSelector: {} selects every pod in production. With both policy types listed and no rule lists, all inbound and outbound traffic is dropped: including DNS, which is the first thing that breaks.

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-coredns-and-frontend-ingress
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: orders
  policyTypes:
  - Ingress
  - Egress
  egress:
  - to:
    - namespaceSelector: {}
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - protocol: UDP
      port: 53
    - protocol: TCP
      port: 53
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

In the egress rule, namespaceSelector: {} matches all namespaces and podSelector matches kube-dns inside them: two selectors in one list item are ANDed. The orders pod can now reach DNS and accept TCP 8080 from app: frontend; everything else stays dropped.

2. Selector semantics and traps

Evaluation ElementScope / RuleFailure / Behavior Mode
Pod SelectionpodSelector: {} vs specific labelsUnmatched pods remain completely open (non-isolated).
Policy TypespolicyTypes: ["Ingress", "Egress"]Omitting Egress leaves all outbound traffic unrestricted.
Selector SyntaxArray item with - namespaceSelector: and - podSelector:Evaluates as OR rather than AND, accidentally permitting broad access.
CNI PluginCalico, Cilium, or cloud policy enginesIf disabled, API accepts policies but no dataplane drops occur.

3. Choosing a CNI: the trade-off that decides the design

NetworkPolicy is only as good as the dataplane behind it.

CNIEnforcementBeyond NetworkPolicy
Calicoiptables/ipset by default, eBPF dataplane optionalGlobalNetworkPolicy (cluster-wide), host endpoints; no L7 in the OSS datapath
CiliumeBPF (kernel 4.19+)CiliumNetworkPolicy: L7 HTTP/gRPC/Kafka, DNS-based egress (toFQDNs), host firewall
AWS VPC CNIonly with the network policy agent add-onL3/L4 only; no L7, no FQDN
GKE Dataplane V2Cilium-based, default on Autopilot and newer Standard clustersL7 via Cilium CRDs

Decision rule: if your cluster's CNI already enforces L3/L4, use it. Do not install a second policy engine, because two engines writing iptables/eBPF state is a debugging nightmare. Move to Cilium or Calico only when you need something NetworkPolicy cannot express.

4. When NetworkPolicy is the wrong tool

  • L7 rules (allow GET /health but not POST /admin, a gRPC method, a Kafka topic): NetworkPolicy has no concept above L4. Use CiliumNetworkPolicy or a mesh (Istio AuthorizationPolicy, Linkerd).
  • Egress by DNS name: NetworkPolicy matches CIDRs via ipBlock, not hostnames. Use Cilium toFQDNs or an egress proxy.
  • Identity / mTLS between services: that is a mesh, not a policy.
  • Node or external traffic: NetworkPolicy selects pods only. Host-level protection needs Calico host endpoints or Cilium host policies.
  • Hard multi-tenant isolation: namespaces + RBAC + admission control, with policy as one layer.

5. Debugging workflow

  1. Confirm enforcement: kubectl -n kube-system get ds for calico-node, cilium-agent, or aws-node. No agent, no drops.
  2. Confirm the pod is selected: kubectl get netpol -n production -o yaml and compare spec.podSelector against kubectl get pod <p> --show-labels. A typo here leaves the pod silently open.
  3. Split DNS from IP: kubectl exec <p> -- nslookup orders.production, then curl -m 2 <podIP>:8080. DNS timeout with a working direct IP means egress to kube-dns is blocked; both failing means the destination ingress rule is wrong.
  4. Read the datapath: cilium monitor --type drop, calicoctl node status, or iptables-save -c to see which rule is counting drops.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How does an Ingress Controller route external traffic to internal Services, and how do you isolate whether a 502 or 504 error originates at the Ingress proxy or the upstream Pod?

Answer

An Ingress Controller bypasses kube-proxy iptables/IPVS routing for request data: it watches Ingress, Service, and EndpointSlice resources via the Kubernetes API, dynamically updates its internal proxy configuration (e.g., Envoy or NGINX upstreams), and forwards Layer 7 traffic directly to individual Pod IPs.

Traffic Path

  1. External Client sends an HTTP request reaching an external Layer 4 Load Balancer.
  2. The Load Balancer terminates or passes traffic to the Ingress Controller Pods (via NodePort or hostNetwork).
  3. Ingress matches Host header and path prefixes defined in the Ingress resource.
  4. Rather than routing to the virtual ClusterIP of the destination Service, the Ingress proxy selects an upstream target directly from the resolved EndpointSlice (the Pod's IP and targetPort).
  5. Direct TCP/TLS connection is established from the Ingress Pod to the workload Pod.

Isolating 502 vs. 504 Errors

  • 502 Bad Gateway: Upstream reset or immediate failure. Occurs when the Ingress proxy connects to an IP/port where no process is listening (ECONNREFUSED), the container crashes during handshake, TLS negotiation fails, or the upstream resets the TCP connection (ECONNRESET) prematurely.
  • 504 Gateway Timeout: Upstream latency exceeded. Occurs when the TCP connection cannot be established within timeout (ETIMEDOUT), or the upstream accepts the connection but fails to return HTTP headers before the Ingress proxy's upstream read timeout expires (e.g., default 60s in ingress-nginx).
[Client] ---> [Ingress Proxy] ---(direct Pod IP)---> [Upstream Pod]
                   |                                       |
                   +-- 502: RST / Refused / TLS fail <-----+ (CrashLoop, OOMKilled, closed conn)
                   +-- 504: Read/Connect timeout <---------+ (App hang, DB lock, probe delay)

Systematic Triage Flow

StepInspection TargetExpected Failure Mode
1. Ingress Access LogsLook at $status, $upstream_status, $upstream_response_time, and $upstream_connect_time.If $status is 502 and $upstream_status is 502, upstream returned 502. If $status is 502 and $upstream_status is - or 502 with connect failure, Ingress could not establish TCP or received RST.
2. Endpoint StatusRun kubectl get endpointslices -l kubernetes.io/service-name=<svc>.EndpointSlice contains terminating Pod IPs or dead IPs where readiness probes failed or terminationGracePeriodSeconds races occurred.
3. Upstream Pod StateCheck kubectl describe pod <pod> and check restart count / exit codes.OOMKilled (Exit Code 137), application uncaught exceptions (Exit Code 1), or Pods stuck in CrashLoopBackOff.
4. In-cluster ConnectivityRun kubectl exec <ingress-pod> -- curl -Iv http://<pod-ip>:<port>/healthz.Verify whether network policies, firewall rules, or MTU mismatches drop cross-node CNI traffic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Harden a container image and runtime.

Answer

Assumptions: Kubernetes, and I own both the Dockerfile and the admission policy. On plain Docker the same controls exist but the enforcement points move to docker run flags and the daemon config.

First 90 seconds. Harden in two layers under one principle. The image layer shrinks what is in the container; the runtime layer shrinks what the container can do. Then verify both, because a control you cannot observe is a control you do not have. Concretely: build from a digest-pinned minimal base, run as a fixed non-root UID with all capabilities dropped, a seccomp profile and a read-only root filesystem, and enforce it at admission so a bad manifest never schedules.

Image layer, mechanism. A multi-stage build works because the final stage only receives what you COPY --from=builder; the compiler, headers and package cache never enter the last layer, so they cannot be exploited and do not count toward the CVE surface. Pinning by digest (FROM alpine:3.20@sha256:...) makes the base immutable: a tag can be repointed, a digest cannot. syft dir:. -o spdx-json emits the SBOM, cosign sign binds it to the digest, and Trivy --severity HIGH,CRITICAL --ignore-unfixed keeps the gate actionable instead of drowning in unfixable noise.

Runtime layer, mechanism. Each control removes a specific path.

ControlWhat it removesFailure signature
runAsNonRoot: true, runAsUser: 65532Escape starts unprivilegedPod rejected: runAsNonRoot with root image
capabilities.drop: ["ALL"]The 14 caps Docker grants by default, incl. NET_RAWEACCES binding port 80
allowPrivilegeEscalation: falseSets no_new_privs; setuid binaries cannot regain privilegesetuid helper silently fails
seccompProfile: RuntimeDefault~44 syscalls (ptrace, mount, keyctl)EPERM at startup, app dies
readOnlyRootFilesystem: trueImage becomes a read-only artifactEROFS on first write to /tmp

Anything that genuinely needs to write gets an explicit emptyDir at /tmp.

Trade-offs. Distroless static (~2 MB, no shell, no package manager) beats Alpine (~7 MB, musl) on attack surface, but you lose docker exec sh: you debug with ephemeral containers or a debug-tagged variant. Alpine's musl also breaks glibc-linked binaries. Debian slim (~75 MB) is the fallback when the build needs a package manager. Seccomp: RuntimeDefault is free and maintained by the runtime; a custom profile is tighter but every kernel or app change risks a silent EPERM, so write one only when you have a specific syscall to block. Read-only root is worth it almost always; the cost is that apps writing into their own directory now fail, which is a bug you want to find in staging, not production.

Other failure modes. Non-root with no fsGroup leaves mounted volumes unwritable. A missing NET_BIND_SERVICE is the most common drop-ALL surprise. Admission: Pod Security Admission restricted (GA in 1.25) or Kyverno: rejects the pod before it schedules, the cheapest place to catch a regression.

Signals. PID 1 must reap zombies and forward SIGTERM. Use exec-form ENTRYPOINT plus tini or --init, or the app gets SIGKILL after the grace period and drops in-flight requests.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you enforce image security and provenance throughout the container build and runtime lifecycle?

Answer

Assume Kubernetes 1.29+, containerd 1.7+ (or 2.0), images in an OCI registry you control, CI on GitHub Actions, cosign v2. The chain has four links and each fails closed: build a minimal image from a pinned toolchain, sign the digest and attach provenance, verify both at admission, then run it under a restricted securityContext. The admission webhook is the only link that actually enforces anything: everything upstream is advisory.

1. Build: shrink the artifact, then sign the digest

Multi-stage build, static binary, distroless runtime. gcr.io/distroless/static-debian12:nonroot unpacks to roughly 2 MB and ships no apt, apk, sh or bash; alpine:3.20 is about 7 MB and debian:bookworm about 120 MB. Fewer packages means fewer CVEs and no interpreter for an attacker who lands a foothold.

Dockerfile
FROM golang:1.23-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
    go build -trimpath -ldflags="-s -w" -o /bin/server .

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /bin/server /bin/server
ENTRYPOINT ["/bin/server"]

-trimpath strips local build paths from the binary; -s -w drops the symbol table and DWARF. The :nonroot tag already sets USER 65532:65532, so no USER line is needed.

Sign the digest, never the tag:

Shell
# GitHub Actions with `permissions: id-token: write` — cosign picks up the
# ambient OIDC token, signs keylessly via Fulcio, and writes a Rekor entry.
cosign sign --yes \
  registry.internal.net/apps/secure-service@sha256:9f2c1e4b7a8d0f3c5e6b1a2d4f7c8e9b0a1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e

cosign attest --yes --type slsaprovenance --predicate provenance.json \
  registry.internal.net/apps/secure-service@sha256:9f2c1e4b7a8d0f3c5e6b1a2d4f7c8e9b0a1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e

Fulcio issues a certificate valid for 10 minutes; the signature bundle carries the cert and the Rekor inclusion proof, so verification years later needs neither Fulcio nor Rekor online. Signatures and attestations attach to the image index through the OCI 1.1 Referrers API, or the legacy sha256-<digest>.sig tag on older registries.

2. Admission: verify, don't trust

YAML
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: verify-image-provenance
spec:
  validationFailureAction: Enforce
  failurePolicy: Fail
  webhookTimeoutSeconds: 15
  rules:
  - name: verify-signature-and-provenance
    match:
      any:
      - resources:
          kinds: [Pod]
    verifyImages:
    - imageReferences:
      - "registry.internal.net/apps/*"
      attestors:
      - entries:
        - keyless:
            subject: "https://github.com/acme/app/.github/workflows/release.yaml@refs/heads/main"
            issuer: "https://token.actions.githubusercontent.com"
      attestations:
      - predicateType: https://slsa.dev/provenance/v1
        conditions:
        - all:
          - key: "{{ runDetails.builder.id }}"
            operator: Equals
            value: "https://github.com/acme/ci/.github/workflows/build.yml@refs/heads/main"

Use subject (exact match), not a loose --certificate-identity-regexp. A regexp like https://github.com/acme/.* accepts a signature from any repo in the org, which is the same as accepting none.

3. Trace: what happens on kubectl apply

  1. API server persists the Deployment; the Deployment controller creates a ReplicaSet; the ReplicaSet controller creates a Pod object with no node assigned.
  2. Mutating admission runs first, then validating admission. Kyverno reads spec.containers[*].image.
  3. Kyverno resolves the digest, fetches the signature and attestation from the registry (or its cache), verifies the Fulcio chain against the Sigstore root, checks the Rekor inclusion proof, matches the certificate identity, then evaluates the SLSA predicate.
  4. Fail: the API server returns the webhook's message, the ReplicaSet records FailedCreate, and no Pod is ever bound. kubectl describe rs shows the reason.
  5. Pass: the scheduler binds the Pod, kubelet calls containerd, and containerd 2.0's image verifier plugin re-checks the signature at pull time before unpacking.

4. Runtime: provenance is not privilege

A signed image can still run as root. Enforce the Pod Security Standards restricted profile at the namespace (pod-security.kubernetes.io/enforce: restricted) and set the context explicitly:

YAML
spec:
  template:
    spec:
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: app
        image: registry.internal.net/apps/secure-service@sha256:9f2c1e4b7a8d0f3c5e6b1a2d4f7c8e9b0a1d2c3e4f5a6b7c8d9e0f1a2b3c4d5e
        imagePullPolicy: IfNotPresent
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]
        volumeMounts:
        - name: tmp
          mountPath: /tmp
      volumes:
      - name: tmp
        emptyDir:
          sizeLimit: 64Mi

RuntimeDefault denies syscalls including mount, ptrace, kexec_load, reboot and swapon. Digest pinning removes the tag TOCTOU window, so IfNotPresent is safe.

Trade-offs and failure modes

PhaseMechanismFailure modeDetection / mitigation
Builddistroless, no shellYou cannot kubectl exec to debugkubectl debug -it --image=... --target=app ephemeral containers (GA since 1.25); alert on pods/ephemeralcontainers create
AdmissionKyverno verifyImages, failurePolicy: FailRegistry or Rekor outage blocks every Pod create cluster-wideWatch apiserver_admission_webhook_rejection_count and apiserver_admission_webhook_admission_duration_seconds; cache verified digests with a bounded TTL; never set failurePolicy: Ignore on this rule
RuntimereadOnlyRootFilesystem: trueApp writes to /tmp and dies with EROFSMount a scoped emptyDir with sizeLimit; the CrashLoopBackOff log names the path
ProvenanceSignature covers the image, not the Pod specA signed image runs as root because the securityContext is permissivePSS restricted at the namespace, so the Pod spec is checked independently of the image

What this does not cover: a signature proves who built the image, not that it is vulnerability-free. Scan results are a point-in-time claim about a digest, so gate on severity in CI and re-scan on a schedule rather than treating a passing scan as a property of the artifact.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Secure workload identity and Kubernetes API access.

Answer

What I'd say first

Assume a multi-tenant cluster on Kubernetes 1.29+, RBAC as the authorizer, and workloads that call the API server or a cloud API. Three layers: identity, authorization, credential lifetime.

Identity: one ServiceAccount per workload, never default. automountServiceAccountToken: false on the ServiceAccount, opted back in per pod only where the API is actually called. Authorization: a namespaced Role bound to system:serviceaccount:<ns>:<name>, verbs and resources enumerated, no wildcards, no cluster-admin. Lifetime: projected bound tokens, not Secret-backed ones.

Why bound tokens beat long-lived Secrets

A legacy ServiceAccount token is a Secret of type kubernetes.io/service-account-token: a JWT with no exp, no aud, no object binding, valid until the Secret is deleted. Anyone who reads it (a leaked etcd backup, a get secrets grant, a log line) holds a permanent cluster identity. Kubernetes stopped auto-creating that Secret for new ServiceAccounts in 1.24, but hand-created ones still work.

A TokenRequest token differs in three ways:

  • Time. The kubelet requests expirationSeconds: 3600 and refreshes at 80% of TTL, so the file on disk is at most an hour old. The API server caps the request at --service-account-max-token-expiration (default 1h).
  • Audience. aud is set by the requester. A token minted for sts.amazonaws.com is rejected by the API server, which checks its own --service-account-issuer.
  • Object binding. The token carries a kubernetes.io claim with pod name and UID. Delete the pod and the API server rejects the token on the next request. That is the revocation story, because a bound token cannot be individually revoked before exp.

Federation

For cloud APIs, don't put static keys in a Secret. Publish the cluster OIDC issuer (--service-account-issuer must be a reachable HTTPS URL) and let the cloud trust it. EKS IRSA projects a token with aud: sts.amazonaws.com; the pod calls AssumeRoleWithWebIdentity for temporary IAM credentials. GKE Workload Identity binds a KSA to a GSA with roles/iam.workloadIdentityUser on member serviceAccount:<project>.svc.id.goog[<ns>/<ksa>]. AKS uses federated identity credentials with aud: api://AzureADTokenExchange. In each case the cloud credential is short-lived and trust is scoped to one namespace/SA pair.

When the simpler option is right

A workload that calls neither the API server nor a cloud API needs no ServiceAccount and no federation: automountServiceAccountToken: false and stop. A workload reading only its own namespace's ConfigMaps needs a Role, not a ClusterRole. Long-lived tokens are acceptable only where the consumer can't do TokenRequest (some CSI drivers, older operators); then encrypt Secrets at rest with a KMS provider and audit who can read them.

Failure modes

  • RBAC escalation. create on roles/clusterroles plus bind, or escalate, or impersonate on serviceaccounts, lets a workload mint a stronger identity. Audit those verbs.
  • system:masters. Any credential in that group is cluster-admin and RBAC cannot revoke it. Check client certs for it.
  • Node authorizer. kubelet identity system:node:<name> reads Secrets for pods scheduled to it; a pod that can influence scheduling inherits that reach.
  • Key rotation. Rotating the signing key without keeping the old one in --service-account-key-file invalidates every bound token at once. Keep both during rotation.
  • Detection. Audit at RequestResponse for system:serviceaccounts; alert on impersonate, escalate, bind, and 403 spikes from one SA.

Worked artefact

YAML
apiVersion: v1
kind: Pod
metadata: {name: api-client}
spec:
  serviceAccountName: api-client
  automountServiceAccountToken: false
  containers:
    - name: app
      image: registry.example.com/api-client:1.4.2
      volumeMounts:
        - {name: token, mountPath: /var/run/secrets/tokens, readOnly: true}
  volumes:
    - name: token
      projected:
        sources:
          - serviceAccountToken:
              path: api-token
              expirationSeconds: 3600
              audience: https://kubernetes.default.svc

Decoded payload:

JSON
{
  "aud": ["https://kubernetes.default.svc"],
  "iss": "https://oidc.eks.us-east-1.amazonaws.com/id/EXAMPLE",
  "sub": "system:serviceaccount:payments:api-client",
  "kubernetes.io": {
    "namespace": "payments",
    "serviceaccount": {"name": "api-client", "uid": "9f2c..."},
    "pod": {"name": "api-client", "uid": "4b81..."}
  },
  "exp": 1735689600
}

Trace: at T+0 the kubelet writes the file. At T+2880s it calls TokenRequest again and atomically replaces it: the app must re-read the file per request, not cache the string at startup. At T+3600s exp passes and the API server returns 401. If the pod is deleted at T+600s, the next request fails immediately because kubernetes.io.pod.uid no longer resolves, even though exp is still in the future.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Manage application secrets in Kubernetes.

Answer

The 90-second answer. Before I pick a mechanism I ask two things: can this credential be issued per-workload instead of stored, and what's the blast radius if it leaks. A read-only analytics token, or the primary database writer? That answer decides everything else. My default is that long-lived secrets don't belong in Kubernetes at all. I give the Pod an identity and let it fetch short-lived credentials: a bound service account token projected into the Pod (expirationSeconds: 3600, kubelet rotates it at 80% of TTL), exchanged via EKS IRSA or GKE Workload Identity for cloud credentials, or a Vault Agent Injector sidecar rendering dynamic database credentials into /vault/secrets/ with a lease TTL. Nothing static is stored, so there's nothing to steal from etcd.

When you do use a Kubernetes Secret. Encrypt at rest with the KMS v2 provider (GA since 1.29), not aescbc with a local key. The difference matters: with a local key, the key sits in the EncryptionConfiguration file on the API server host, so an etcd snapshot plus that host's disk is enough to decrypt everything. KMS v2 sends the data encryption key to an external KMS, so a stolen etcd backup alone is inert. Then RBAC: get on a Secret returns its value, and list returns every value in the namespace, so list or watch on secrets is read-all. Audit it with kubectl auth can-i list secrets --as=system:serviceaccount:prod:app.

How you deliver it decides how it fails.

deliveryrotation latencyleak surface
env varrestart required/proc/1/environ, inherited by every child process, core dumps, frameworks that log config at startup
volume mount~1–2 min (kubelet sync period + secret cache TTL)tmpfs in the Pod, readable by any process in it
subPath mountneversame, and stale forever
Vault / CSI dynamiclease TTL, e.g. 1hcredential dies with the lease

Rotation is dual-value, and the trace is the point.

  • T+0: the database creates role app_v2; both app_v1 and app_v2 authenticate.
  • T+0: bump the Secret, or let an ExternalSecret with refreshInterval: 1h sync it.
  • T+0→2min: kubelet rewrites the mounted file; the app re-reads on SIGHUP or a file watch.
  • T+2min: confirm nothing still connects as app_v1. pg_stat_activity, or the database's own audit log.
  • T+24h: revoke app_v1.

Failure modes, with detection. Rotating without an overlap window shows up as a 401/403 spike: alert on auth-failure rate, not on the rotation job exiting zero. A subPath mount never updates; detect it by comparing the file's mtime against the Secret's resourceVersion. And the one people miss: deleting the Secret is not revocation. The value survives in running Pods' tmpfs, in etcd backups taken before deletion, and in CI logs. Scan your snapshot and log stores for the old value, and revoke at the source: rotate the credential in the database. Same for key rotation: after changing the provider, rewrite existing objects with kubectl get secrets -A -o json | kubectl replace -f - so they're re-encrypted under the new key.

When plain Secrets are the right call. Short-lived clusters, non-production, or a credential an external system already rotates and Kubernetes merely caches. The cost of Vault or the Secrets Store CSI driver is a new control-plane dependency: if Vault is unreachable and leases expire, Pods can't get credentials. Cache with a fallback and alert on lease-renewal failures. The objective is protecting storage, distribution, use, rotation and deletion, and deletion is the one that quietly isn't done.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design namespace and multi-tenant isolation.

Answer

Core answer

Namespaces give you naming, RBAC scoping and quota accounting, not a security boundary. So the first move is to classify tenants: cooperative (same org, shared trust) versus hostile (untrusted code, multi-customer SaaS). Cooperative tenants can share a cluster with namespaces plus policy. Hostile tenants need node or kernel separation, because they share the kubelet, the container runtime and the host kernel.

Assume Kubernetes 1.29+, a CNI that actually enforces NetworkPolicy (Calico, Cilium, Antrea, not plain Flannel), and Pod Security Admission, which replaced PodSecurityPolicy when PSP was removed in 1.25.

What each layer actually enforces

RBAC is namespaced: a RoleBinding in team-a grants nothing in team-b. Cross-namespace list/watch only happens when you bind a ClusterRole cluster-wide, and that binding is the leak to audit. The check is kubectl auth can-i list pods -n team-b --as=system:serviceaccount:team-a:app.

NetworkPolicy is namespaced and additive: there is no deny rule. Default-deny is a policy that selects every pod and declares both directions with no rules:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: team-a
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]

ResourceQuota enforces aggregate per-namespace ceilings (requests.cpu, limits.memory, count/pods). LimitRange supplies per-container defaults so pods without requests aren't rejected by the quota. PSA applies through namespace labels (pod-security.kubernetes.io/enforce=restricted, with levels privileged/baseline/restricted and modes enforce/audit/warn) and blocks privileged pods, hostPath and hostNetwork.

LayerStopsDoes not stop
RBACcross-namespace API readscluster-scoped resources (Nodes, PVs, CRDs)
NetworkPolicypod-to-pod L3/L4DNS names, L7, a non-enforcing CNI
ResourceQuotaaggregate exhaustionnoisy neighbor inside the quota
PSA restrictedprivileged/hostPath podskernel exploits from allowed pods

Failure modes and detection

A CNI that silently ignores policy is the common one: from a pod in team-a, curl a pod IP in team-b; if it connects, the policy is not enforced. Confirm with kubectl get networkpolicy -A and the CNI's own metrics.

DNS leaks tenant names by default: dig other-svc.team-b.svc.cluster.local resolves from any namespace. Either accept it or run per-namespace DNS.

Missing quota lets one tenant's Deployment scale until it fills the node; the symptom is evictions and kubectl top nodes pinned at 100%. Set quota and LimitRange before onboarding, not after.

A shared-kernel escape owns the node and every tenant on it. Detect with runtime security (Falco) and node audit; contain with RuntimeClass (gVisor/Kata) or dedicated node pools via taints and tolerations.

Trade-offs

Namespace isolation is cheap and correct for cooperative tenants. It is insufficient when tenants run untrusted code, when a single kernel CVE is unacceptable, or when compliance demands dedicated nodes. Then pay for RuntimeClass sandboxing or one cluster per tenant: more cost and operational surface, but a real boundary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Test control-plane outage behavior.

Answer

Core answer (say this first)

Assume a self-managed Kubernetes cluster on v1.29, three etcd nodes, and that I can cut the API server without touching etcd. If it's managed (EKS, GKE), I can't stop the control plane at all: I cut the nodes' path to it with a security group or NetworkPolicy, which is the realistic failure anyway.

The test has two halves that measure different things. First: does the data plane keep serving while the API is unreachable? Second: how much reconciliation debt accumulates, and how does it drain when the API returns? I run them separately, because a 60-second outage and a 10-minute one fail in different places.

What survives, what doesn't

ThingAPI down 60sAPI down 10min
kubelet, running podskeep runningkeep running
kube-proxy Service rulesunchanged, traffic flowsunchanged
CoreDNSserves cached recordsnew Services unresolvable
new pod schedulingblockedblocked
Deployment rolloutblockedblocked
HPA scalingblockedblocked
new Endpoints programmednono
Secret/ConfigMap updatesnot deliverednot delivered
node statusNotReady after 40spods evicted around 5m40s

Those timings come from defaults, not guesses. The kubelet renews its node Lease every 10s; node-monitor-grace-period is 40s, so nodes flip NotReady at 40s; the node.kubernetes.io/not-ready:NoExecute toleration is 300s, so eviction starts near 5m40s. Controller-manager leader election uses leaseDuration 15s, renewDeadline 10s, retryPeriod 2s, so a restarted controller-manager takes up to ~15s to re-elect. etcd: three nodes tolerate one loss, five tolerate two; heartbeat 100ms, election timeout 1000ms.

How to run it

Don't inject the fault from inside the cluster with Chaos Mesh PodChaos on the API server: the chaos controller needs the API to schedule and to report, so it defeats itself. Use an already-running DaemonSet, or go out-of-band: on a self-managed cluster, move the kube-apiserver static pod manifest out of /etc/kubernetes/manifests and back; on managed, revoke the node security group's 443 to the control plane.

Before: record steady state. Ready replicas per Deployment, endpoint counts, p99 on the ingress, CoreDNS query rate, workqueue_depth per controller. During: watch apiserver_request_total fall to zero, and confirm etcd_server_leader_changes_seen_total stays flat. If that counter moves, you lost quorum and the test is invalid: stop and say so.

Failure modes and how you catch them

  • Alert storm: every node goes NotReady inside the same 40s window. Group by cluster in Alertmanager or you page 200 times. Detect: alerts per minute.
  • Eviction cascade: past 5m40s pods are evicted and can't be rescheduled, so capacity drops and doesn't return until the API does. Detect: ready replicas against desired.
  • GitOps revert: Argo CD or Flux can't reach the API during the outage, then on restore reconciles git over anything changed by hand. Detect: diff live against git before re-enabling sync.
  • Stale desired state: controllers replay their queue on restore; a Deployment mid-rollout resumes where it stopped. Detect: rollout status and generation against observedGeneration.

Restore and measure the drain

Bring the API back and watch workqueue_depth fall while rest_client_requests_total spikes: that spike is the replay. Time from restore to every controller at zero queue and every node Ready is your recovery number. Report it; "recovered" is not a result.

Trade-offs

60s versus 10min: 60s stays inside the lease and eviction windows, so it tests client resilience only. Past 5m40s you're testing rescheduling and capacity recovery, a different risk. Blocking writes only (etcd read-only) is cheaper and still exercises reconciliation without losing reads. If the blast radius is too large, fault one controller-manager or the scheduler at a time: you lose the cascade but keep the cluster.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Migrate a legacy service into containers.

Answer

What I'd say first

I'd pin down two things before touching anything: is this packaging-only, or packaging plus a move to Kubernetes? And does the service own durable state? My default is packaging-only onto Kubernetes, because it keeps the blast radius to one variable. If it owns state, that gets externalized before the first container runs, not after.

Then three phases: inventory, containerize, cut over.

Inventory

pstree -p for the process tree, ss -lntp for listening sockets, and then the things a Dockerfile won't tell you: files written outside the working directory, cron entries, the service account, and which signals the process actually handles. The JVM is the classic trap. JVMs older than Java 10 (and Java 8 before 8u191) read the host's memory, not the cgroup limit, so a container capped at 2 GiB still sizes its heap against the node's 64 GiB and gets OOM-killed with exit code 137. Either upgrade or set -Xmx explicitly and stop trusting MaxRAMPercentage.

Container contract

PID 1 matters. If the entrypoint is a shell script, the shell is PID 1 and never forwards SIGTERM; the app keeps running until terminationGracePeriodSeconds (default 30) expires and the kubelet sends SIGKILL, dropping in-flight requests. Use exec form, or --init for a real init that reaps zombies. Set STOPSIGNAL if the app wants something other than SIGTERM.

Shutdown trace with a shell entrypoint: t=0 kubelet sends SIGTERM to PID 1, the shell; the shell ignores it; t=30s kubelet sends SIGKILL; the app dies mid-request. With exec form: t=0 SIGTERM reaches the app; t=2s it finishes draining and exits; the pod terminates at t=2s.

Trade-off

The tempting alternative is decomposing the service while containerizing it. I'd refuse: when parity fails you can't tell whether the packaging or the split caused it. Containerize first, get a green baseline, decompose later against that baseline.

Failure modes and how I'd catch them

Legacy assumptionContainer realitySymptom
host RAM visiblecgroup limitOOMKill, exit 137
local disk persistswritable layer dies with the poddata loss on restart
init reaps childrenPID 1 is your appzombie PIDs, PID exhaustion
hostname stablepod name changesbroken peer config
local timezoneUTCwrong timestamps in logs and records

Detection is cheap: date inside the container versus the host, cat /proc/1/status for the signal mask, and a restart test that writes a file and checks it's gone.

Cutover

Run old and new side by side, canary the immutable digest (image@sha256:..., never :latest), start at 1% of traffic, and compare p99 latency and error rate against the old path. Keep the old deployment warm so rollback is a traffic switch, not a redeploy. Retire the old path only after a restore from backup has actually been exercised.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Measure orchestration effectiveness without gaming.

Answer

Assumptions: Kubernetes, a few hundred services, multi-tenant, changes shipped through a GitOps pipeline with progressive delivery, and a real on-call rotation. On VMs or a single-tenant cluster the shape holds; the metric names change.

Core answer. Measure at two boundaries, the change and the user request, and never publish a supply-side metric without the demand-side metric it can be improved by degrading. Orchestration effectiveness is "did this change reach users correctly, and did the platform absorb failure without human heroics," priced per successful change. Pod count, utilization and replica count are diagnostics you open when an outcome metric moves, not scores.

Why the obvious metrics fail is mechanical, not philosophical. Utilization rises when you remove headroom, so it improves while p99 latency degrades. Replica count rises when an HPA reacts to a noisy custom metric. Deployment count rises when one PR is split into five. Restart count falls when a crashlooping pod backs off. Each is a proxy a team can move without moving the outcome.

MetricPair it withWhy the pair resists gaming
Node utilization / packing densityp99 request latency, OOMKills per 1k podsDensity only counts if latency and OOM rate are flat
Deployment frequencyChange failure rate, MTTRFrequency alone is gamed by splitting PRs (DORA pairing)
HPA replica countQueue depth or saturation, cost per 1k requestsReplicas can be inflated; cost per request cannot
Headroom (allocatable − requested)p99 scheduling-pending time, unschedulable pod countHeadroom can be hoarded; pending time exposes the cost
Page/alert volumeUser-visible incidents from status page and support ticketsSuppressed alerts show up as divergence, not silence
Policy/provenance coverage% of running pods on a verified digest, admission denialsPolicy objects existing ≠ workloads complying

Worked trace: canary analysis. A service does 200 rps. Argo Rollouts sets the canary to 5% weight with a 10-minute analysis window: 120,000 requests total, 6,000 to the canary. The new revision is genuinely broken at a 5% error rate, so it produces 300 errors. An analysis template that queries the service aggregate sees 300/120,000 = 0.25% and passes a 0.5% threshold: the rollout promotes a bad revision. The same template grouped by the revision label (rollouts-pod-template-hash) sees 5% and aborts. At low canary weight, aggregate metrics hide canary-specific failure; the ratio must be computed on the canary subset. Pair it with a p99 histogram check (histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)) ≤ 0.300) and a 1-hour error-budget burn rate ≤ 2.

Arithmetic: cost per successful change. 500 changes/month, $60k infra, 0.5 engineer-hours of review and verification per change at $100/h = $25k, and each rollback costs 3 engineers × 2h = $600. At a 2% rollback rate: 10 rollbacks, $6k, total $91k over 490 successful changes = $186 each. Cut infra 20% to $48k but let the rollback rate rise to 6%: 30 rollbacks, $18k, total $91k over 470 successful changes = $194 each. The 20% infra saving is a 4% regression in the number that matters, and that is before customer impact.

Failure modes and how you catch them.

  • SLO drift: a team widens the SLO or excludes endpoints to stop burning budget. Detect by keeping SLO specs in git, alerting on changes to them, and running an external synthetic probe as ground truth.
  • Request deflation to hit a density target: p95 of working_set_bytes / requests above 1.2, plus a rising OOMKill rate per 1k pods.
  • Alert suppression: page volume falls while support tickets stay flat or climb.
  • Aggregate canary analysis: as traced above. The rollout passes and the incident lands on the on-call.
  • Toil measured by ticket count: teams stop filing tickets. Use an on-call survey plus logged toil hours, cross-checked against change lead time.

When a gameable metric is fine. Pod count is a legitimate capacity-planning input. Utilization is a legitimate diagnostic once paired. Deployment count is legitimate as DORA frequency once paired with change failure rate. Review quarterly, segmented by risk tier: a tier-1 user-facing API and a nightly batch job do not share an SLO, and averaging them hides both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a production container and orchestration platform.

Answer

Core answer (first 90 seconds)

Assume Kubernetes 1.29+ on Linux, one cluster per environment, ~40 services, mostly stateless HTTP plus two stateful stores. I'd answer in four layers: the image and runtime contract, scheduling and disruption policy, the security boundary, and the failure tests. The decision that drives the rest is the trust boundary: what runs as root, what can reach the API server, and what can talk to what.

Image and runtime contract

Build distroless or scratch images and pin by digest, not tag: image: registry.internal/api@sha256:.... Tags are mutable; a digest is the only thing that makes "the same artifact" true across environments. Run as non-root with a fixed UID, readOnlyRootFilesystem: true, drop all capabilities, allowPrivilegeEscalation: false, seccomp RuntimeDefault. Writable paths get explicit emptyDir mounts, /tmp and the app's cache dir, because a read-only rootfs breaks anything that writes a temp file.

YAML
securityContext:
  runAsNonRoot: true
  runAsUser: 10001
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
  capabilities: { drop: ["ALL"] }
  seccompProfile: { type: RuntimeDefault }
resources:
  requests: { cpu: "250m", memory: "1Gi" }
  limits:   { memory: "1Gi" }   # memory limit, no CPU limit

Requests equal limits on memory gives Guaranteed QoS for that dimension and makes the pod last in eviction order; omitting the CPU limit avoids CFS throttling that shows up as p99 latency spikes.

Scheduling and disruption

WorkloadControllerDeciding criterion
Stateless HTTPDeploymentAny replica can serve any request
Databases, queuesStatefulSetNeeds stable network identity or ordered storage
Per-node agentsDaemonSetOne pod per node by definition

Set requests from measured p95, not guesses: the scheduler packs on requests while the kubelet evicts on actual usage. A node with 8 vCPU and 32 GiB, minus ~1 vCPU and 2 GiB reserved for system, has 7 vCPU and 30 GiB allocatable. At 250m CPU and 1 GiB per pod, CPU binds first: 7 / 0.25 = 28 pods, versus 30 / 1 = 30 on memory. So that node holds 28 pods.

A PodDisruptionBudget of minAvailable: 80% on a 20-replica Deployment lets a node drain evict at most 4 pods at once. Rolling updates use the defaults maxSurge: 25% and maxUnavailable: 25%, so 5 extra pods come up and 5 go down.

Security boundary

Default-deny NetworkPolicy per namespace, then allow specific flows. RBAC: no cluster-admin for workloads; each service account gets a Role scoped to its namespace. Admission control (Gatekeeper or Kyverno) rejects images without a digest, pods running as root, or pods missing resource requests. Separate trust tiers by node pool with taints so untrusted workloads can't land on nodes holding cloud credentials.

Failure modes

  • Registry outage: nodes with cached images keep running; new pods sit in ImagePullBackOff. Detect via kube-state-metrics kube_pod_container_status_waiting_reason. Mitigate with a pull-through cache.
  • Control plane loss: existing pods keep serving, but nothing schedules and HPA stops scaling. Detect via apiserver request latency and etcd leader changes.
  • Node loss: pods reschedule after node-monitor-grace-period (default 40s) plus the node.kubernetes.io/not-ready toleration (default 300s). Up to ~5 minutes of reduced capacity. Size replica counts and PDBs for that window.
  • Zone loss: topology spread constraints with maxSkew: 1 across zones keep replicas balanced; without them one zone can hold every replica.

Trade-offs

Managed control plane (EKS/GKE) versus self-managed: managed removes etcd and upgrade toil but caps version choice and costs about $73/month per cluster on EKS. Shared multi-tenant cluster versus cluster-per-team: shared is cheaper and simpler, but the blast radius of a bad admission policy or a noisy neighbor is the whole platform. Start shared with hard namespace boundaries and split only when a team needs a different Kubernetes version or kernel.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Review containerization and orchestration before launch.

Answer

Assumptions first. I'll read this as: a stateful service, a Postgres-backed StatefulSet plus a stateless API Deployment, going to production on Kubernetes 1.29+ with a managed control plane and a CI pipeline that builds the images. The launch gate is a chain, and it fails at the weakest link: image trust → runtime contract → scheduling and capacity → rollout mechanics → failure drills. Ready replicas is the last thing I check, not the first, because a Deployment can report 3/3 ready while every pod runs an unreviewed image or will drop in-flight requests on the next deploy.

Image trust. Tags are mutable, digests are not. I compare what is running against what was signed:

$ kubectl get pod api-7d9f -o jsonpath='{.status.containerStatuses[0].imageID}'
registry.internal/api@sha256:9c1f...        # running
$ cosign verify registry.internal/api:1.4.2 | jq -r .critical.image['docker-manifest-digest']
sha256:4ab0...                              # signed

A mismatch means the tag was re-pushed after signing: someone else's build is live. That is enforced by an admission policy (Kyverno or the Cosign policy-controller) rejecting unsigned digests, not by a checklist someone reads once.

Runtime contract. If the Dockerfile uses shell-form CMD java -jar app.jar, PID 1 is /bin/sh, which does not forward SIGTERM. The app never sees it, and after terminationGracePeriodSeconds the kubelet sends SIGKILL: every rollout drops in-flight requests. Fix is exec-form CMD or --init. Then check the shutdown path: a preStop sleep of about 5s to cover endpoint propagation, plus a handler that drains the connection pool.

Probes. Readiness gates Service endpoints; liveness restarts the pod. A liveness probe with a 1s timeout on a JVM that GCs for 2s will restart-loop a healthy pod. A startup probe gives slow boots a budget of failureThreshold × periodSeconds before liveness takes over.

settingdefaultwhat it decides
terminationGracePeriodSeconds30sSIGTERM → SIGKILL window
readiness periodSeconds × failureThreshold10s × 3time to leave endpoints
Deployment maxSurge / maxUnavailable25% / 25%rollout blast radius
CrashLoopBackOff backoff10s, doubling, 5min caprecovery time after a bad config

Capacity and topology. Requests drive scheduling; limits drive throttling and OOM. A CPU limit means CFS throttling on 100ms periods; a memory limit means exit code 137. Check QoS class, anti-affinity, and PDB semantics: a PDB only constrains voluntary disruptions (drain, eviction API), not node failure and not Deployment rolling updates, which respect maxSurge/maxUnavailable instead. A PDB of minAvailable: 2 on a 3-replica StatefulSet backed by a single-replica Postgres is theatre.

Failure drills. Drain a node with the PDB in place. Kill a zone. Block the registry and confirm the pull-through cache and imagePullSecrets still work. Expire the credential and watch the pull fail. Fill memory and confirm the OOM path and restart backoff. For the stateful half, restore a backup into a scratch namespace and time it: an untested restore is not a backup.

Trade-offs. A managed control plane buys etcd and API availability, not your node pool, your PDB, or your registry. Single-tenant nodes cost more and remove noisy-neighbour risk; a shared kernel means a container escape is a node compromise, so seccomp RuntimeDefault, drop ALL capabilities, readOnlyRootFilesystem, runAsNonRoot, and a default-deny NetworkPolicy are the floor, not the ceiling.

Reject if the only evidence offered is ready replicas.

Curated: · Written: · Reviewed:

Difficulty: Hard