Learnings

Cloud and DevOps

Kubernetes

How a cluster keeps a bank API running: the control loop, the objects you write (Deployment, Service, Ingress, ConfigMap, Secret, HPA) and how to debug them, told mostly in diagrams. No cluster was available for this page. The 12 manifest files were schema-validated with kubeconform against the Kubernetes 1.34.0 schemas but never applied, the only real output is from kubeconform, one kubectl 1.34.1 client-side generator and one Python simulation, and every command that needs a cluster is marked "Not run for this page" with typical output.

The cluster

Part 1 of 6 · what it is for, its parts, and the loop that drives it

What problem it solves

The cluster

Docker runs one container on one machine. Kubernetes runs many containers on many machines and keeps them the way you declared, without a person watching.

Problem with plain serversWhat Kubernetes does
A process or a machine dies at nightStarts a replacement Pod, on another node if needed
Which machine has room?The scheduler places Pods by CPU and memory requests
Instances come and go, addresses changeA Service gives one stable name and IP
Deploys cause downtimeRolling update, with one-command rollback
Load changes during the dayThe HPA adds and removes replicas
Config and passwords baked into imagesConfigMaps and Secrets injected at start

Cost: a cluster is a distributed system to operate. For one service on one machine, Compose or a managed container service is usually enough.

Control plane and nodes

The cluster

The control plane decides, the nodes run containers. Every component talks only to the API server, and only the API server talks to etcd.

Control plane: the API server is the only door, etcd is the only store.
One worker node: the kubelet starts Pods, kube-proxy programs Service routing.
ComponentJobIf it is down
API serverValidates and serves every object over RESTNo changes. Running Pods keep running.
etcdConsistent key-value store (Raft) of all cluster stateQuorum lost: the cluster is read-only or gone. Back it up.
SchedulerPicks a node for each new PodNew Pods stay Pending
Controller managerRuns the loops: Deployment, ReplicaSet, Job, nodeNothing heals or scales
kubeletNode agent: starts containers, runs probes, reports statusNode goes NotReady, its Pods are replaced elsewhere
kube-proxyTurns Services into node routing rulesNew Services and endpoints do not route on that node

etcd runs with 3 or 5 members so a majority survives one or two failures. On a managed cluster (EKS, GKE, AKS) the provider runs the control plane and you see only nodes.

The reconcile loop

The cluster · the one idea behind everything else

You write the desired state (spec). A controller keeps comparing it with the actual state (status) and takes one step to close the gap, forever.

Level-triggered: the loop reacts to the current difference, not to a missed event.

A toy version of the ReplicaSet controller. This one was run (Python 3.9).

Consequence: you never tell Kubernetes "start a Pod". You change the spec and a loop does the work, so the same YAML applied twice changes nothing.

What one apply sets off

The cluster

No component calls another. Each one watches the API server and reacts to the objects it owns.

Four independent loops turn one Deployment into running containers.

Every object has the same four top-level fields.

FieldMeaning
apiVersion, kindWhich API and type: apps/v1 Deployment
metadataName, namespace, labels, annotations
specDesired state. You write it.
statusActual state. Controllers write it.

Running the bank API

Part 2 of 6 · Pod, ReplicaSet, Deployment, and their configuration

Pod

Running the bank API

A Pod is one or more containers that share an IP address and volumes, and are scheduled as one unit. It is disposable: a replacement gets a new name and a new IP.

Pod phases. CrashLoopBackOff and ImagePullBackOff are container states inside a phase, not phases.

Rule: do not create bare Pods for a service. Nothing recreates one after its node dies. A second container in a Pod is for a helper that must share its network or files (log shipper, proxy), not for a second service.

ReplicaSet and Deployment

Running the bank API

A ReplicaSet keeps N identical Pods alive. A Deployment owns ReplicaSets, one per version of the Pod template, and moves Pods from the old one to the new one. You only ever write the Deployment.

Ownership runs down. Pods are matched by label, not by name.

The whole file. Later chapters explain its probes, resources and strategy.

Not run for this page.

Trap: selector.matchLabels must match template.metadata.labels, and the selector cannot be changed after creation. The Pod name is Deployment name, ReplicaSet hash, random suffix.

ConfigMap

Running the bank API

A ConfigMap holds non-secret settings as strings, so one image runs in every environment. The Deployment above loads all its keys as environment variables with envFrom.

Injected asAfter the ConfigMap is edited
Environment variablesNothing changes until the Pod restarts
Files in a mounted volumeFiles update after a delay. The app must re-read them.
Volume with subPathNever updates

Habit: after a config change, run kubectl rollout restart deployment/bank-api, or put a hash of the config in a Pod template annotation so a change triggers a rollout. Values are strings: quote numbers and booleans.

Secret

Running the bank API

A Secret has the same shape as a ConfigMap, for passwords, tokens and keys. stringData takes plain text, and the API server stores it base64-encoded under data.

This generator runs on the client only, so it was run here (kubectl 1.34.1). The second command decodes its output.

What a Secret gives youWhat it does not
Separate RBAC from ConfigMapsEncryption. Base64 is an encoding.
Sent only to nodes whose Pods use itEncryption in etcd, unless the cluster enables it
Kept out of the image and the Pod specSafety in git: never commit a real one

In practice: keep the real value in a secret manager and sync it into the cluster (External Secrets Operator, a CSI secrets driver) or commit only an encrypted form (Sealed Secrets, SOPS). The file above is a placeholder for the example.

Reaching it

Part 3 of 6 · Services, DNS and Ingress

Service

Reaching it

Pod IPs change on every restart. A Service is a stable virtual IP and name in front of every Ready Pod that carries the selector's labels.

The EndpointSlice is the live list of Pod IPs. A controller keeps it in step with labels and readiness.

port is what clients dial, targetPort is the container port, here by its name http from the Deployment. Balancing is per connection, not per request, so long-lived gRPC or HTTP/2 connections stick to one Pod.

ClusterIP, NodePort, LoadBalancer

Reaching it

The three types are layers: each one adds an entry point on top of the one before.

LoadBalancer contains NodePort, which contains ClusterIP.
TypeReachable fromUse for
ClusterIP (default)Inside the cluster onlyService-to-service calls. Most Services.
NodePortAny node IP, on a port from 30000 to 32767 by defaultLab clusters, or behind your own load balancer
LoadBalancerA cloud load balancer with an external IPThe ingress controller, or a non-HTTP public service
ExternalNameA DNS CNAME, no proxyingNaming an external database
Headless (clusterIP: None)DNS returns the Pod IPsStatefulSets, client-side balancing

Cost: each LoadBalancer Service is one billed cloud load balancer. Put one in front of an ingress controller and route many Services through it.

DNS names

Reaching it

The cluster DNS (CoreDNS) gives every Service a name. Code calls the name, never an IP.

NameWorks from
bank-apiThe same namespace
bank-api.bankAny namespace
bank-api.bank.svc.cluster.localAnywhere. The full name, cluster.local being the default domain.
bank-db-0.bank-dbOne Pod of a StatefulSet behind a headless Service

Not run for this page. A throwaway Pod is the usual way to test a name from inside.

Ingress

Reaching it

An Ingress is HTTP routing rules: host and path to Service. It does nothing by itself. An ingress controller (a reverse proxy running in the cluster) reads the rules and serves them.

One load balancer and one proxy in front of many Services. TLS ends at the controller.

Check first: ingressClassName must name a controller that is installed, or the Ingress never gets an address. Which controllers are current changes (the community ingress-nginx project announced its retirement, and the Gateway API is the newer routing model), so check the docs for your cluster. bank-tls is a TLS Secret that is not in these manifests.

Healthy, sized and updated

Part 4 of 6 · probes, resources, autoscaling, rollouts

Liveness, readiness, startup

Healthy, sized and updated

The kubelet calls three probes, and each failure has a different consequence.

Liveness restarts. Readiness only removes the Pod from the Service, and puts it back when it passes.
ProbeQuestionOn failureIn deployment.yaml
StartupHas it finished booting?Restart, after the budget/healthz, 30 tries, 2 s apart: up to 60 s
LivenessIs the process stuck?Restart the container/healthz, 3 failures, 10 s apart
ReadinessCan it serve right now?Removed from endpoints/ready, 2 failures, 5 s apart
MistakeWhat happens
Liveness checks the databaseDatabase blip restarts every Pod at once. Liveness checks only the process.
No readiness probeTraffic arrives before the app listens: errors on every deploy
Slow boot, no startup probeLiveness kills the app while it starts: CrashLoopBackOff
Readiness depends on a shared dependencyAll Pods go unready together and the Service has no endpoints

Shutdown: on delete, endpoint removal and SIGTERM happen in parallel. The preStop sleep of 5 s lets routing catch up before the app gets SIGTERM, then the app has the rest of terminationGracePeriodSeconds to finish requests before SIGKILL. The sleep hook needs a recent cluster (check the docs). Older ones use exec with sleep 5.

Requests, limits, QoS, OOMKilled

Healthy, sized and updated

A request is what the scheduler reserves on a node. A limit is the ceiling the kernel enforces. The scheduler looks only at requests, never at real usage.

Memory cannot be taken back, so the container is killed. CPU can, so it is slowed down.
QoS classWhenUnder node pressure
GuaranteedEvery container has CPU and memory requests equal to limitsEvicted last
BurstableSome request or limit is set, not all equalIn between
BestEffortNo requests or limits at allEvicted first

The bank API asks for 250m CPU (a quarter core) and 256Mi, with a 512Mi memory limit and no CPU limit, so it is Burstable. Leaving the CPU limit off is a common choice: the request still guarantees a share, and no limit means no throttling when the node is idle.

Not run for this page.

Fix: find out whether it is a leak or an honest need (kubectl top pod, the memory graph), then fix the app or raise the limit. Tell the runtime about the limit too: a Go service wants GOMEMLIMIT, a worker pool wants fewer workers.

Horizontal Pod Autoscaler

Healthy, sized and updated

The HPA changes replicas to hold a metric near a target. It needs a metrics source (metrics-server for CPU and memory) and it needs requests, because utilization is a percentage of the request.

Another reconcile loop, run about every 15 seconds by default.
TrapDetail
replicas also in the DeploymentEvery apply resets the count. Remove the field once an HPA owns it.
No CPU requestThe HPA shows <unknown> and never scales
Scaling on CPU for an I/O-bound APICPU stays low while requests queue. Scale on request rate or queue length through a metrics adapter or KEDA.
Slow startNew Pods arrive after the spike. Keep headroom in minReplicas.
Nodes fullNew Pods stay Pending until a cluster autoscaler adds a node

Rolling update and rollback

Healthy, sized and updated

Changing the Pod template (a new image tag) creates a new ReplicaSet. The Deployment scales it up and the old one down, gated by readiness.

With maxSurge: 1 and maxUnavailable: 0: never fewer than 3 serving, at most 4 running.
SettingMeaningDefault
maxSurgeExtra Pods allowed above replicas25%
maxUnavailablePods allowed to be missing25%
revisionHistoryLimitOld ReplicaSets kept for rollback10
strategy.type: RecreateKill all, then start all. Downtime, but never two versions at once.

Not run for this page.

Limits of rollback: undo scales the previous ReplicaSet back up. It does not undo a database migration or a changed ConfigMap, and both versions serve traffic during every rollout, so schema changes must be backward compatible. In a GitOps setup, roll back by reverting the commit instead.

PodDisruptionBudget

Healthy, sized and updated

A PDB limits how many Pods a voluntary disruption may take down at once. Node drains during upgrades and autoscaler scale-down go through the eviction API, which respects it.

DisruptionPDB applies?
kubectl drain, node upgrade, autoscaler scale-downYes
Node crash, OOM kill, hardware failureNo. It cannot stop an accident.
The Deployment's own rolling updateNo. That follows maxUnavailable.

Trap: minAvailable equal to replicas, or a PDB on a single replica, blocks every drain and stalls cluster upgrades.

Other workloads and access

Part 5 of 6 · state, batch work, isolation

StatefulSet versus Deployment

Other workloads and access

Deployment Pods are interchangeable. StatefulSet Pods have an identity: a fixed name, a fixed DNS name and their own disk that follows them across restarts.

DeploymentStatefulSet
Pod namesRandom suffixbank-db-0, bank-db-1
StorageNone, or one volume shared by allOne PersistentVolumeClaim per Pod
Start and update orderAny, in parallelOne at a time, in order
DNSService name onlyPer Pod, through a headless Service
Use forStateless APIs, workersDatabases, brokers, anything with a replica identity

Honest advice: a StatefulSet gives stable names and disks. It does not give replication, failover or backups, and this sketch has no password or probes. For a bank's database, use a managed database or an operator that knows the engine.

Jobs and CronJobs

Other workloads and access

A Job runs Pods until a set number finish successfully, then stops. A CronJob creates a Job on a schedule. Here: monthly statements at 02:00 on the 1st.

FieldMeaning
backoffLimitRetries before the Job is marked failed
activeDeadlineSecondsHard time limit for the whole Job
completions, parallelismHow many successes are needed, how many Pods at once
concurrencyPolicyAllow, Forbid (skip if the last run is still going) or Replace
restartPolicyNever or OnFailure. Always is not allowed in a Job.

Design for it: a Job can run a Pod more than once (retry, node loss) and a CronJob can skip or, rarely, double a run. The statements job must be idempotent. A database migration is a good fit for a Job run before the rollout.

Namespaces and RBAC

Other workloads and access

A namespace is a scope for names, quotas and permissions, not a security wall. RBAC answers one question: may this subject do this verb on this resource? A binding joins a subject to a role. Rules only add, there is no deny.

ObjectScope
Role, RoleBindingOne namespace
ClusterRole, ClusterRoleBindingThe whole cluster, and cluster-wide things such as nodes
ServiceAccountThe identity a Pod uses to call the API server
ResourceQuota, LimitRangeCaps and defaults for one namespace
NetworkPolicyWhich Pods may talk. Without one, every Pod reaches every Pod.

Check a permission with kubectl auth can-i list secrets -n bank --as=system:serviceaccount:bank:bank-api (not run for this page; with the Role above the answer would be no). Give each service its own ServiceAccount and keep secrets and wildcards out of its Role.

Debugging and recap

Part 6 of 6 · check before applying, find the fault after

Validate before you apply

Debugging and recap · run for real

kubeconform checks YAML against the Kubernetes JSON schemas without a cluster. Every manifest on this page passed it: the 11 files shown plus a four-line Namespace named bank. -strict rejects unknown fields.

The same check on a copy with two mistakes: replicas: "3" and a misspelt readynessProbe.

CheckNeeds a clusterCatches
Schema validation (kubeconform)NoWrong types, unknown and missing fields
kubectl apply --dry-run=serverYesAlso admission rules, quotas, immutable fields
kubectl diff -fYesWhat would change against the live objects
Applying to a test clusterYesEverything else: wrong names, labels, images, ports

What it does not prove: a schema-valid file can still point a Service at the wrong label or a Deployment at a missing Secret. Those links between objects are plain strings, and nothing on this page was applied to check them at run time.

Debugging a Pod

Debugging and recap

Start from the STATUS column, then read the Events at the bottom of describe. Events say why, logs say what the app did.

Work outward: Pod, then Service, then Ingress.
SymptomUsual causesLook at
PendingNo node fits the requests, a taint with no toleration, an unbound PersistentVolumeClaim, quotakubectl describe pod, the FailedScheduling event
ImagePullBackOff, ErrImagePullWrong name or tag, private registry without imagePullSecrets, registry rate limitEvents, then pull the image by hand
CrashLoopBackOffThe app exits at start (missing env, bad config, cannot reach the database), or liveness kills itkubectl logs --previous, exit code in describe
CreateContainerConfigErrorA referenced ConfigMap, Secret or key does not existEvents name the missing object
OOMKilled, exit 137Memory limit too low, or a leakRequests and limits
Running but 0/1 ReadyReadiness probe fails: wrong path or port, dependency downEvents, then kubectl exec and call the path
EvictedNode ran out of memory or diskkubectl describe node
Rollout stuckNew Pods never become Readykubectl rollout status, then the new Pod

Not run for this page.

CrashLoopBackOff is a wait, not an error: the kubelet restarts the container with a growing delay, capped at about five minutes. The real error is in the previous run's logs and exit code.

A Service with no endpoints

Debugging and recap

Pods are Running, yet calls to the Service fail or time out. The Service found no Ready Pod with its labels, or it sends traffic to the wrong port.

Not run for this page.

What you seeCauseFix
No endpoints, Pods are ReadySelector does not match the Pod labels (app: bank against app: bank-api), or wrong namespaceMake the selector equal the template labels
No endpoints, Pods are 0/1Readiness probe failsFix the probe or the app
Endpoints listed, connection refusedtargetPort is wrong, or the app listens on 127.0.0.1Match the container port. Bind 0.0.0.0.
Works by port-forward, not by IngressWrong ingressClassName, host, path or Service portkubectl describe ingress, controller logs
Name does not resolveShort name used from another namespaceUse bank-api.bank

kubectl by task

Debugging and recap · not run for this page

The commands used every day, grouped by what you are looking at. NODE, POD and CONTAINER are names you fill in; add -n NAMESPACE to any of them, or -A for all namespaces.

Which cluster am I talking to?

A context is a cluster plus a user plus a default namespace, stored in ~/.kube/config. Check it before every change.

NeedCommand
List contexts, * marks the current onekubectl config get-contexts
Show only the current contextkubectl config current-context
Switch clusterkubectl config use-context docker-desktop
Set the default namespace for this contextkubectl config set-context --current --namespace=bank
Show the config in use, secrets hiddenkubectl config view --minify
Use another config file for one commandkubectl --kubeconfig=./other.yaml get nodes
API server addresskubectl cluster-info
Client and server versionskubectl version
Is the API server healthy?kubectl get --raw='/readyz?verbose'
Every kind this cluster knows, with short nameskubectl api-resources
Namespaceskubectl get namespaces
Am I allowed to do this?kubectl auth can-i create deployments -n bank

Nodes

NeedCommand
List nodes with IP, OS, runtime and versionkubectl get nodes -o wide
Capacity, conditions, taints and the Pods on a nodekubectl describe node NODE
Node labelskubectl get nodes --show-labels
CPU and memory in use (needs metrics-server)kubectl top nodes
Every Pod running on one nodekubectl get pods -A -o wide --field-selector spec.nodeName=NODE
Stop new Pods landing on a nodekubectl cordon NODE
Move Pods off a node before maintenancekubectl drain NODE --ignore-daemonsets --delete-emptydir-data
Put the node back in servicekubectl uncordon NODE
Label a nodekubectl label node NODE disk=ssd
A shell on the node itselfkubectl debug node/NODE -it --image=busybox

Pods

NeedCommand
List Pods with node and Pod IPkubectl get pods -o wide
Pods in every namespacekubectl get pods -A
Only the Pods of one appkubectl get pods -l app=bank-api
Watch changes as they happenkubectl get pods -w
Pods that are not runningkubectl get pods -A --field-selector status.phase!=Running
Sort by restart countkubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
Events, probes, image, last state: the first stopkubectl describe pod POD
Full object as the cluster stores itkubectl get pod POD -o yaml
Recent events, oldest firstkubectl get events --sort-by=.lastTimestamp
CPU and memory per Pod (needs metrics-server)kubectl top pods
Reach a Pod port from your machinekubectl port-forward pod/POD 8080:8000
Delete a Pod; its Deployment makes a new onekubectl delete pod POD
Restart every Pod of a Deployment, one by onekubectl rollout restart deployment/bank-api
A throwaway Pod for testing DNS or a Servicekubectl run tmp --rm -it --image=busybox -- sh

Containers inside a Pod

A Pod can hold several containers. Without -c, kubectl picks the default one.

NeedCommand
Names of the containers in a Podkubectl get pod POD -o jsonpath='{.spec.containers[*].name}'
Images a Pod is runningkubectl get pod POD -o jsonpath='{.spec.containers[*].image}'
Logs of one containerkubectl logs POD -c CONTAINER
Follow logs, last 100 lineskubectl logs -f --tail=100 POD
Logs of the run before the last restartkubectl logs POD --previous
Logs of all containers in the Podkubectl logs POD --all-containers
Logs from every Pod of an appkubectl logs -l app=bank-api --prefix
A shell inside a containerkubectl exec -it POD -c CONTAINER -- sh
One command inside a containerkubectl exec POD -- env
Copy a file out of a containerkubectl cp POD:/tmp/dump.txt ./dump.txt
Why the last run ended (exit code, OOMKilled)kubectl get pod POD -o jsonpath='{.status.containerStatuses[*].lastState}'
Debug an image that has no shellkubectl debug -it POD --image=busybox --target=CONTAINER

Shaping the output

NeedCommand
More columns-o wide
The whole object-o yaml, -o json
Names only, for scripts-o name
One field-o jsonpath='{.status.podIP}'
Your own columns-o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName
Documentation for a fieldkubectl explain pod.spec.containers
What would change, before applyingkubectl diff -f deployment.yaml

Cheat sheet

Debugging and recap

NeedObject or command
Run N copies of a stateless serviceDeployment
Stable name in front of PodsService (ClusterIP)
HTTP from outside, by host and pathIngress plus a controller, or the Gateway API
Settings, passwordsConfigMap, Secret
Restart a stuck processLiveness probe
Hold traffic until the app can serveReadiness probe
Reserve capacity, cap memoryresources.requests, limits.memory
Scale with loadHorizontalPodAutoscaler
Survive node drainsPodDisruptionBudget, 2 or more replicas
Stable identity and its own diskStatefulSet
Run once, run on a scheduleJob, CronJob
Who may do whatServiceAccount, Role, RoleBinding
Start a manifest from a generatorkubectl create deployment NAME --image=IMAGE --dry-run=client -o yaml
Field documentationkubectl explain deployment.spec.strategy
Why is it not running?kubectl describe pod, kubectl logs --previous
Deploy, watch, undokubectl apply -f, rollout status, rollout undo

Interview questions

Debugging and recap

QuestionShort answer
What happens when you run kubectl apply on a Deployment?The API server validates and stores it in etcd. The Deployment controller creates a ReplicaSet, that creates Pods, the scheduler binds each to a node, the kubelet starts the containers. Each step is a separate watch loop.
Why is Kubernetes called declarative?You store desired state, and controllers reconcile actual state toward it continuously. Applying the same file twice is a no-op, and drift is corrected without you.
Liveness versus readiness?Liveness failure restarts the container. Readiness failure only removes the Pod from Service endpoints. Liveness must not depend on external systems.
Requests versus limits?Requests drive scheduling and the QoS class. Limits are enforced by the kernel: over the memory limit is an OOM kill, over the CPU limit is throttling.
A Pod is in CrashLoopBackOff. What do you do?describe for exit code and events, logs --previous for the crash. Usual causes: missing config, a dependency, a liveness probe that fires during a slow start.
How does a Service find its Pods?By label selector. A controller writes the IPs of matching Ready Pods into EndpointSlices and kube-proxy programs each node to spread connections over them.
How do you deploy with zero downtime?Rolling update with maxUnavailable: 0, a real readiness probe, graceful SIGTERM handling with a short preStop delay, backward-compatible schema changes, and a PDB for node drains.
Deployment or StatefulSet?Deployment when Pods are interchangeable. StatefulSet when each replica needs a stable name and its own volume, as databases and brokers do.
Is a Secret secure?Not by itself. It is base64 in etcd unless encryption at rest is on. Its value comes from RBAC, from not being in the image, and from an external secret manager behind it.
The HPA is not scaling. Why?No metrics-server, no CPU request on the container, already at maxReplicas, or new Pods are Pending because nodes are full.
What does a PDB protect against?Voluntary evictions such as drains and autoscaler scale-down. Not crashes, and not the Deployment's own rollout.
What if the control plane goes down?Running Pods keep serving, because kubelets and routing rules work from what they already have. Nothing new is scheduled, healed or scaled until it returns.

Back to Cloud and DevOps.