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
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 servers | What Kubernetes does |
|---|---|
| A process or a machine dies at night | Starts 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 change | A Service gives one stable name and IP |
| Deploys cause downtime | Rolling update, with one-command rollback |
| Load changes during the day | The HPA adds and removes replicas |
| Config and passwords baked into images | ConfigMaps 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 control plane decides, the nodes run containers. Every component talks only to the API server, and only the API server talks to etcd.
| Component | Job | If it is down |
|---|---|---|
| API server | Validates and serves every object over REST | No changes. Running Pods keep running. |
| etcd | Consistent key-value store (Raft) of all cluster state | Quorum lost: the cluster is read-only or gone. Back it up. |
| Scheduler | Picks a node for each new Pod | New Pods stay Pending |
| Controller manager | Runs the loops: Deployment, ReplicaSet, Job, node | Nothing heals or scales |
| kubelet | Node agent: starts containers, runs probes, reports status | Node goes NotReady, its Pods are replaced elsewhere |
| kube-proxy | Turns Services into node routing rules | New 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.
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
No component calls another. Each one watches the API server and reacts to the objects it owns.
Every object has the same four top-level fields.
| Field | Meaning |
|---|---|
apiVersion, kind | Which API and type: apps/v1 Deployment |
metadata | Name, namespace, labels, annotations |
spec | Desired state. You write it. |
status | Actual state. Controllers write it. |
Running the bank API
Part 2 of 6 · Pod, ReplicaSet, Deployment, and their configuration
Pod
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.
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
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.
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
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 as | After the ConfigMap is edited |
|---|---|
| Environment variables | Nothing changes until the Pod restarts |
| Files in a mounted volume | Files update after a delay. The app must re-read them. |
Volume with subPath | Never 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
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 you | What it does not |
|---|---|
| Separate RBAC from ConfigMaps | Encryption. Base64 is an encoding. |
| Sent only to nodes whose Pods use it | Encryption in etcd, unless the cluster enables it |
| Kept out of the image and the Pod spec | Safety 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
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.
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
The three types are layers: each one adds an entry point on top of the one before.
| Type | Reachable from | Use for |
|---|---|---|
ClusterIP (default) | Inside the cluster only | Service-to-service calls. Most Services. |
NodePort | Any node IP, on a port from 30000 to 32767 by default | Lab clusters, or behind your own load balancer |
LoadBalancer | A cloud load balancer with an external IP | The ingress controller, or a non-HTTP public service |
ExternalName | A DNS CNAME, no proxying | Naming an external database |
Headless (clusterIP: None) | DNS returns the Pod IPs | StatefulSets, 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
The cluster DNS (CoreDNS) gives every Service a name. Code calls the name, never an IP.
| Name | Works from |
|---|---|
bank-api | The same namespace |
bank-api.bank | Any namespace |
bank-api.bank.svc.cluster.local | Anywhere. The full name, cluster.local being the default domain. |
bank-db-0.bank-db | One 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
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.
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
The kubelet calls three probes, and each failure has a different consequence.
| Probe | Question | On failure | In deployment.yaml |
|---|---|---|---|
| Startup | Has it finished booting? | Restart, after the budget | /healthz, 30 tries, 2 s apart: up to 60 s |
| Liveness | Is the process stuck? | Restart the container | /healthz, 3 failures, 10 s apart |
| Readiness | Can it serve right now? | Removed from endpoints | /ready, 2 failures, 5 s apart |
| Mistake | What happens |
|---|---|
| Liveness checks the database | Database blip restarts every Pod at once. Liveness checks only the process. |
| No readiness probe | Traffic arrives before the app listens: errors on every deploy |
| Slow boot, no startup probe | Liveness kills the app while it starts: CrashLoopBackOff |
| Readiness depends on a shared dependency | All 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
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.
| QoS class | When | Under node pressure |
|---|---|---|
| Guaranteed | Every container has CPU and memory requests equal to limits | Evicted last |
| Burstable | Some request or limit is set, not all equal | In between |
| BestEffort | No requests or limits at all | Evicted 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
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.
| Trap | Detail |
|---|---|
replicas also in the Deployment | Every apply resets the count. Remove the field once an HPA owns it. |
| No CPU request | The HPA shows <unknown> and never scales |
| Scaling on CPU for an I/O-bound API | CPU stays low while requests queue. Scale on request rate or queue length through a metrics adapter or KEDA. |
| Slow start | New Pods arrive after the spike. Keep headroom in minReplicas. |
| Nodes full | New Pods stay Pending until a cluster autoscaler adds a node |
Rolling update and rollback
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.
maxSurge: 1 and maxUnavailable: 0: never fewer than 3 serving, at most 4 running.| Setting | Meaning | Default |
|---|---|---|
maxSurge | Extra Pods allowed above replicas | 25% |
maxUnavailable | Pods allowed to be missing | 25% |
revisionHistoryLimit | Old ReplicaSets kept for rollback | 10 |
strategy.type: Recreate | Kill 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
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.
| Disruption | PDB applies? |
|---|---|
kubectl drain, node upgrade, autoscaler scale-down | Yes |
| Node crash, OOM kill, hardware failure | No. It cannot stop an accident. |
| The Deployment's own rolling update | No. 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
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.
| Deployment | StatefulSet | |
|---|---|---|
| Pod names | Random suffix | bank-db-0, bank-db-1 |
| Storage | None, or one volume shared by all | One PersistentVolumeClaim per Pod |
| Start and update order | Any, in parallel | One at a time, in order |
| DNS | Service name only | Per Pod, through a headless Service |
| Use for | Stateless APIs, workers | Databases, 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
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.
| Field | Meaning |
|---|---|
backoffLimit | Retries before the Job is marked failed |
activeDeadlineSeconds | Hard time limit for the whole Job |
completions, parallelism | How many successes are needed, how many Pods at once |
concurrencyPolicy | Allow, Forbid (skip if the last run is still going) or Replace |
restartPolicy | Never 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
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.
| Object | Scope |
|---|---|
| Role, RoleBinding | One namespace |
| ClusterRole, ClusterRoleBinding | The whole cluster, and cluster-wide things such as nodes |
| ServiceAccount | The identity a Pod uses to call the API server |
| ResourceQuota, LimitRange | Caps and defaults for one namespace |
| NetworkPolicy | Which 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.
| Check | Needs a cluster | Catches |
|---|---|---|
| Schema validation (kubeconform) | No | Wrong types, unknown and missing fields |
kubectl apply --dry-run=server | Yes | Also admission rules, quotas, immutable fields |
kubectl diff -f | Yes | What would change against the live objects |
| Applying to a test cluster | Yes | Everything 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
Start from the STATUS column, then read the Events at the bottom of describe. Events say why, logs say what the app did.
| Symptom | Usual causes | Look at |
|---|---|---|
Pending | No node fits the requests, a taint with no toleration, an unbound PersistentVolumeClaim, quota | kubectl describe pod, the FailedScheduling event |
ImagePullBackOff, ErrImagePull | Wrong name or tag, private registry without imagePullSecrets, registry rate limit | Events, then pull the image by hand |
CrashLoopBackOff | The app exits at start (missing env, bad config, cannot reach the database), or liveness kills it | kubectl logs --previous, exit code in describe |
CreateContainerConfigError | A referenced ConfigMap, Secret or key does not exist | Events name the missing object |
OOMKilled, exit 137 | Memory limit too low, or a leak | Requests and limits |
Running but 0/1 Ready | Readiness probe fails: wrong path or port, dependency down | Events, then kubectl exec and call the path |
Evicted | Node ran out of memory or disk | kubectl describe node |
| Rollout stuck | New Pods never become Ready | kubectl 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
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 see | Cause | Fix |
|---|---|---|
| No endpoints, Pods are Ready | Selector does not match the Pod labels (app: bank against app: bank-api), or wrong namespace | Make the selector equal the template labels |
No endpoints, Pods are 0/1 | Readiness probe fails | Fix the probe or the app |
| Endpoints listed, connection refused | targetPort is wrong, or the app listens on 127.0.0.1 | Match the container port. Bind 0.0.0.0. |
| Works by port-forward, not by Ingress | Wrong ingressClassName, host, path or Service port | kubectl describe ingress, controller logs |
| Name does not resolve | Short name used from another namespace | Use 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.
| Need | Command |
|---|---|
List contexts, * marks the current one | kubectl config get-contexts |
| Show only the current context | kubectl config current-context |
| Switch cluster | kubectl config use-context docker-desktop |
| Set the default namespace for this context | kubectl config set-context --current --namespace=bank |
| Show the config in use, secrets hidden | kubectl config view --minify |
| Use another config file for one command | kubectl --kubeconfig=./other.yaml get nodes |
| API server address | kubectl cluster-info |
| Client and server versions | kubectl version |
| Is the API server healthy? | kubectl get --raw='/readyz?verbose' |
| Every kind this cluster knows, with short names | kubectl api-resources |
| Namespaces | kubectl get namespaces |
| Am I allowed to do this? | kubectl auth can-i create deployments -n bank |
Nodes
| Need | Command |
|---|---|
| List nodes with IP, OS, runtime and version | kubectl get nodes -o wide |
| Capacity, conditions, taints and the Pods on a node | kubectl describe node NODE |
| Node labels | kubectl get nodes --show-labels |
| CPU and memory in use (needs metrics-server) | kubectl top nodes |
| Every Pod running on one node | kubectl get pods -A -o wide --field-selector spec.nodeName=NODE |
| Stop new Pods landing on a node | kubectl cordon NODE |
| Move Pods off a node before maintenance | kubectl drain NODE --ignore-daemonsets --delete-emptydir-data |
| Put the node back in service | kubectl uncordon NODE |
| Label a node | kubectl label node NODE disk=ssd |
| A shell on the node itself | kubectl debug node/NODE -it --image=busybox |
Pods
| Need | Command |
|---|---|
| List Pods with node and Pod IP | kubectl get pods -o wide |
| Pods in every namespace | kubectl get pods -A |
| Only the Pods of one app | kubectl get pods -l app=bank-api |
| Watch changes as they happen | kubectl get pods -w |
| Pods that are not running | kubectl get pods -A --field-selector status.phase!=Running |
| Sort by restart count | kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' |
| Events, probes, image, last state: the first stop | kubectl describe pod POD |
| Full object as the cluster stores it | kubectl get pod POD -o yaml |
| Recent events, oldest first | kubectl get events --sort-by=.lastTimestamp |
| CPU and memory per Pod (needs metrics-server) | kubectl top pods |
| Reach a Pod port from your machine | kubectl port-forward pod/POD 8080:8000 |
| Delete a Pod; its Deployment makes a new one | kubectl delete pod POD |
| Restart every Pod of a Deployment, one by one | kubectl rollout restart deployment/bank-api |
| A throwaway Pod for testing DNS or a Service | kubectl run tmp --rm -it --image=busybox -- sh |
Containers inside a Pod
A Pod can hold several containers. Without -c, kubectl picks the default one.
| Need | Command |
|---|---|
| Names of the containers in a Pod | kubectl get pod POD -o jsonpath='{.spec.containers[*].name}' |
| Images a Pod is running | kubectl get pod POD -o jsonpath='{.spec.containers[*].image}' |
| Logs of one container | kubectl logs POD -c CONTAINER |
| Follow logs, last 100 lines | kubectl logs -f --tail=100 POD |
| Logs of the run before the last restart | kubectl logs POD --previous |
| Logs of all containers in the Pod | kubectl logs POD --all-containers |
| Logs from every Pod of an app | kubectl logs -l app=bank-api --prefix |
| A shell inside a container | kubectl exec -it POD -c CONTAINER -- sh |
| One command inside a container | kubectl exec POD -- env |
| Copy a file out of a container | kubectl 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 shell | kubectl debug -it POD --image=busybox --target=CONTAINER |
Shaping the output
| Need | Command |
|---|---|
| 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 field | kubectl explain pod.spec.containers |
| What would change, before applying | kubectl diff -f deployment.yaml |
Cheat sheet
| Need | Object or command |
|---|---|
| Run N copies of a stateless service | Deployment |
| Stable name in front of Pods | Service (ClusterIP) |
| HTTP from outside, by host and path | Ingress plus a controller, or the Gateway API |
| Settings, passwords | ConfigMap, Secret |
| Restart a stuck process | Liveness probe |
| Hold traffic until the app can serve | Readiness probe |
| Reserve capacity, cap memory | resources.requests, limits.memory |
| Scale with load | HorizontalPodAutoscaler |
| Survive node drains | PodDisruptionBudget, 2 or more replicas |
| Stable identity and its own disk | StatefulSet |
| Run once, run on a schedule | Job, CronJob |
| Who may do what | ServiceAccount, Role, RoleBinding |
| Start a manifest from a generator | kubectl create deployment NAME --image=IMAGE --dry-run=client -o yaml |
| Field documentation | kubectl explain deployment.spec.strategy |
| Why is it not running? | kubectl describe pod, kubectl logs --previous |
| Deploy, watch, undo | kubectl apply -f, rollout status, rollout undo |
Interview questions
| Question | Short 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.