{"guides":[],"hints":[{"hint":"The kubelet only runs pods that are already bound to its node, and the scheduler only picks nodes. Which controller compares a pod count with a replica number?","lessonID":"k8s.architecture","nuance":"The ReplicaSet controller in kube-controller-manager sees two pods where its spec asks for three and creates a Pod object. The scheduler then binds it to a node and that node's kubelet starts it."},{"hint":"Utilization is a percentage. Ask what the HPA divides the measured usage by, and which field of the container spec supplies that number.","lessonID":"k8s.autoscaling","nuance":"Utilization is usage divided by the CPU request. If a container in the targeted pods has no request, the HPA cannot compute a percentage, shows <unknown> and records FailedGetResourceMetric. Limits play no part."},{"hint":"An informer already keeps an up-to-date copy of every Deployment in memory. Ask which object reads that copy without calling the API server.","lessonID":"k8s.client-go","nuance":"A lister reads the informer's local cache, kept current by one shared List and Watch, so reconcile costs no API calls. A stored event object may be stale when its key is processed, and a watch per call multiplies load."},{"hint":"Ask when the kubelet resolves valueFrom for an environment variable, and whether anything in the pod template has changed since.","lessonID":"k8s.configmaps","nuance":"Env values are resolved once, when a container is created. Editing the ConfigMap leaves the pod template unchanged, so nothing rolls. rollout restart changes a template annotation and replaces the pods; mounted files would refresh."},{"hint":"The container you can read now is a new instance that has not crashed yet. Ask which flag reads the log of the instance before it.","lessonID":"k8s.debugging-pods","nuance":"The kubelet keeps the log of the previous container instance; kubectl logs --previous prints it, panic included. The current log belongs to a fresh container, and exec cannot enter a container that is not running."},{"hint":"Client-side apply sets every field that appears in the file. Is replicas in the file?","lessonID":"k8s.declarative-apply","nuance":"replicas is in the manifest, so apply sets it back to 3 and prints deployment.apps/web configured. To keep a count chosen at run time, remove replicas from the file or let an HPA own it."},{"hint":"Ask whether replicas lives inside spec.template, and what the hash in a ReplicaSet's name is computed from.","lessonID":"k8s.deployments-replicasets","nuance":"replicas is not part of the Pod template, so pod-template-hash stays the same. The Deployment scales its current ReplicaSet to 6, which creates three Pods; existing Pods are untouched and no revision is added."},{"hint":"Read the search line in the pod's resolv.conf. Which namespace is appended to a short name first?","lessonID":"k8s.dns","nuance":"NXDOMAIN means CoreDNS answered: no Service web exists in the caller's namespace. Short names expand with the pod's own namespace first, so a Service in shop needs web.shop or its full name."},{"hint":"The nginx page means the controller replied, not the app. Would an unmatched host produce a 503, or a different status?","lessonID":"k8s.ingress","nuance":"ingress-nginx answers 404 when no rule matches and 503 when a rule matches but its Service is missing or has no ready endpoints. / still works, so the host rule exists: check kubectl get endpoints api."},{"hint":"Allow, Forbid and Replace differ only in what they do when the previous Job has not finished yet.","lessonID":"k8s.jobs-cronjobs","nuance":"Forbid does not start a scheduled run while the previous Job is active. Replace would stop the old Job, Allow would run both. The skipped run may still start late when the old Job ends, unless its startingDeadlineSeconds has passed."},{"hint":"set-context writes to a file, not to your shell session. Which namespace does a command use when you pass no -n?","lessonID":"k8s.kubectl-contexts","nuance":"set-context --current stored shop in the context entry in kubeconfig, so it survives new terminals. Plain commands look in shop until you pass -n default or run set-context --current --namespace=default."},{"hint":"One transformer matches containers by image name and replaces only the parts you give it: the name, the tag or the digest.","lessonID":"k8s.kustomize-helm","nuance":"The images transformer finds every container whose image is gopherforge/web and sets its tag to v2, or a digest. namePrefix renames objects, and a generated ConfigMap never changes a container's image."},{"hint":"Selectors are evaluated continuously. Which objects select app=web, and does anything select app=debug?","lessonID":"k8s.labels-selectors","nuance":"The ReplicaSet releases the pod that no longer matches and creates a new one to get back to 3, and the Service drops it from its endpoints. The relabelled pod keeps running with no owner until you delete it."},{"hint":"Namespaces own the objects inside them. What is the namespace controller doing while a namespace shows Terminating?","lessonID":"k8s.namespaces-quotas","nuance":"Deletion cascades: the namespace turns Terminating, the namespace controller deletes every object in it, and the namespace disappears once empty. Bound PVs follow their reclaim policy, so with Delete the data goes too."},{"hint":"Look at the from entry: it has a podSelector but no namespaceSelector. Which namespace are the matching pods taken from?","lessonID":"k8s.network-policies","nuance":"A from podSelector without a namespaceSelector matches pods in the policy's namespace only. Add a namespaceSelector in the same from item, such as kubernetes.io/metadata.name: web, to admit that namespace's frontends."},{"hint":"The node is tainted within a minute. Ask what every pod carries that lets it stay on a node with that taint, and for how long.","lessonID":"k8s.node-failures","nuance":"Admission gives every pod tolerations for the not-ready and unreachable NoExecute taints with tolerationSeconds: 300. Pods stay bound for five minutes after the taint, then are evicted and their ReplicaSet replaces them."},{"hint":"Field names are case-sensitive. Think about what kubectl asks the API server to do with fields its schema does not know.","lessonID":"k8s.objects-yaml","nuance":"kubectl requests strict field validation by default, so the API server rejects the request with strict decoding error: unknown field \"spec.template.spec.containers[0].readinessprobe\" and creates nothing."},{"hint":"CrashLoopBackOff is a reason attached to a container state, not a phase. With restartPolicy Always, can the pod ever reach a terminal phase?","lessonID":"k8s.pods","nuance":"The pod has started containers and restartPolicy Always restarts them forever, so its phase stays Running. CrashLoopBackOff is the container's Waiting reason between restart attempts."},{"hint":"Only some probe types ever restart a container. Which ones, and what does the other one change instead?","lessonID":"k8s.probes","nuance":"A failing readiness probe marks the Pod not ready, so it is removed from the EndpointSlices of its Services and stops receiving traffic. Only liveness and startup probe failures make the kubelet restart a container."},{"hint":"Ask which setting forbids the Deployment controller from removing an old pod before a new one is Ready, and what decides Ready.","lessonID":"k8s.production-checklist","nuance":"With maxUnavailable: 0 the controller removes an old pod only after a surge pod is Ready. A pod failing its readiness probe never counts, so the rollout stalls at one extra pod while the old ReplicaSet keeps serving."},{"hint":"Look at where the RoleBinding lives. In which namespaces can a RoleBinding grant anything, even when its roleRef is a ClusterRole?","lessonID":"k8s.rbac","nuance":"RBAC is additive and namespaced: a binding in shop grants nothing in orders. Add a RoleBinding in orders, to the same ClusterRole if you want to reuse it; RBAC changes apply on the next request, no restart needed."},{"hint":"CPU and memory behave differently at their limits. Which one can be taken away gradually, and which one cannot?","lessonID":"k8s.resources-qos","nuance":"Memory cannot be throttled, so the kernel OOM killer ends a container that exceeds its memory limit with SIGKILL: exit code 137. A CPU limit only throttles, and an eviction deletes the Pod instead of restarting it."},{"hint":"Percentages become Pod counts: surge rounds up, unavailability rounds down. Add one to replicas and subtract the other.","lessonID":"k8s.rolling-updates","nuance":"25% of 10 is 2.5. maxSurge rounds up to 3, so at most 13 Pods exist; maxUnavailable rounds down to 2, so at least 8 Pods stay available at every step of the rollout."},{"hint":"A taint and a toleration together decide where a Pod may go. What decides where it should go?","lessonID":"k8s.scheduling","nuance":"A toleration only removes the taint as an obstacle; ordinary nodes stay feasible and may score higher. Dedicated nodes need a taint to keep others off plus a nodeSelector or required affinity to keep the workload on."},{"hint":"Encoding and encryption differ. Which one needs a key, and does encryption at rest change what the API server returns to an authorized reader?","lessonID":"k8s.secrets","nuance":"Base64 is reversible by anyone. Encryption at rest protects etcd files and backups, but the API server decrypts for every authorized request, so only RBAC on get, list and watch keeps the password from this user."},{"hint":"Ask which Service type skips the virtual IP and publishes the pod addresses in DNS instead of hiding them behind kube-proxy.","lessonID":"k8s.service-types","nuance":"A headless Service (clusterIP: None) has no virtual IP: DNS returns each ready pod, and a StatefulSet gets records like db-0.db.ns.svc.cluster.local. ClusterIP and LoadBalancer hide pods behind one address."},{"hint":"The Service exists and has endpoints, so the name and the selector work. Compare the port in each endpoint with the port the process opens.","lessonID":"k8s.services","nuance":"Refused with endpoints present means packets reach the pod IP but nothing listens on that port: targetPort is wrong. A NetworkPolicy causes a timeout, and a DNS problem fails before any connection."},{"hint":"StatefulSet storage belongs to an ordinal, not to a Pod. What would scaling back up need?","lessonID":"k8s.statefulsets-daemonsets","nuance":"persistentVolumeClaimRetentionPolicy defaults to Retain for both whenScaled and whenDeleted, so data-db-1 and data-db-2 stay Bound and are reattached when those ordinals return. Set Delete to remove them."},{"hint":"Latency and CPU are normal, so this is not saturation, and every pod is Ready. What changed at the moment the errors started?","lessonID":"k8s.traffic-debugging","nuance":"A steady error rate that starts with a rollout, with normal latency and saturation, points at the new version. Ready pods keep getting traffic, so undo the rollout first and debug the image afterwards."},{"hint":"Read the claim's events, not only the pod's. Which object must exist before a provisioner can create a volume for a claim?","lessonID":"k8s.volumes-pvc","nuance":"Dynamic provisioning needs the StorageClass the claim names. If it does not exist the claim stays Pending with ProvisioningFailed, and the scheduler cannot place a pod whose claim is unbound. Fix storageClassName or create the class."}],"id":"kubernetes","labs":[{"checks":[],"id":"k8s-playground","initialFiles":{},"instructions":"A simulated Kubernetes cluster runs in this terminal: one control-plane node and two workers, metrics-server and ingress-nginx. Nothing here is a real container, but kubectl, traffic and curl behave like the real thing. Start with kubectl get nodes, deploy something (kubectl create deployment web --image=gopherforge/web:v1 --replicas=3 --port=8080), expose it, and send it traffic (traffic run svc/web --rps 200). cluster status and cluster config shape the cluster; cluster node fail kind-worker takes a node down; help kubectl and help traffic list the commands. Reset rebuilds the cluster.","objective":"A simulated cluster with three nodes, metrics and an ingress controller, to try anything from the course.","setup":"cluster create --workers 2 --ingress >/dev/null","starter":"kubectl get nodes\nkubectl get pods -A\n","title":"Kubernetes playground"},{"checks":[{"command":"kubectl get deploy web -o jsonpath='{.status.readyReplicas}'","description":"Deployment web has 3 ready replicas","equals":"3"},{"command":"kubectl get svc web -o jsonpath='{.spec.ports[0].port}'","description":"Service web listens on port 80","equals":"80"},{"command":"kubectl run check --rm -it --image=busybox --restart=Never -- wget -qO- http://web","contains":"gopherforge web","description":"http://web answers from inside the cluster"}],"id":"k8s-first-deployment","initialFiles":{},"instructions":"Create a Deployment named web from the image gopherforge/web:v1 with 3 replicas; the app listens on port 8080. Then create a ClusterIP Service named web on port 80 that sends traffic to port 8080. Useful commands: kubectl create deployment, kubectl expose, kubectl rollout status, kubectl get endpoints web. The checks also call http://web from inside the cluster.","objective":"Run three replicas of a web app and reach them through a Service by name.","setup":"kind create cluster >/dev/null","starter":"kubectl create deployment web --image=gopherforge/web:v1 --replicas=3 --port=8080\nkubectl rollout status deployment/web\n# now expose it on port 80 → 8080\n","title":"Deploy and expose a service"},{"checks":[{"command":"kubectl get deploy shop -o jsonpath='{.status.readyReplicas}'","description":"shop has 2 ready replicas","equals":"2"},{"command":"kubectl get deploy shop -o jsonpath='{.spec.template.spec.containers[0].image}'","contains":"nginx:1.2","description":"shop runs an nginx image that exists"}],"id":"k8s-imagepull","initialFiles":{},"instructions":"The shop Deployment was released with a typo in its image tag and none of its two pods ever ran. Find the cause with kubectl get pods, kubectl describe pod and the Events at the bottom, then point the Deployment at an nginx tag that exists (for example nginx:1.27) and wait for the rollout.","objective":"Find why the shop Deployment's pods never start and fix the image.","setup":"kind create cluster >/dev/null\nkubectl create deployment shop --image=nginx:1.99 --replicas=2 >/dev/null\ncluster tick 20s >/dev/null","starter":"kubectl get pods\nkubectl describe pod -l app=shop | tail -n 8\n","title":"Fix an ImagePullBackOff"},{"checks":[{"command":"kubectl get deploy db -o jsonpath='{.status.readyReplicas}'","description":"db has a ready replica","equals":"1"},{"command":"kubectl get deploy db -o jsonpath='{.spec.template.spec.containers[0].envFrom[*].secretRef.name}{.spec.template.spec.containers[0].env[*].valueFrom.secretKeyRef.name}'","contains":"db","description":"the password comes from a Secret, not a literal"}],"id":"k8s-crashloop","initialFiles":{},"instructions":"The db Deployment (postgres:16) keeps restarting. Read why with kubectl logs deploy/db --previous. Store the password in a Secret named db (key POSTGRES_PASSWORD), wire it into the Deployment (kubectl set env deploy/db --from=secret/db, or a secretKeyRef in a manifest) and wait for the rollout.","objective":"Read the crashing container's log and give the database what it needs, from a Secret.","setup":"kind create cluster >/dev/null\nkubectl create deployment db --image=postgres:16 >/dev/null\ncluster tick 40s >/dev/null","starter":"kubectl get pods -l app=db\nkubectl logs deploy/db --previous\n","title":"Fix a CrashLoopBackOff"},{"checks":[{"command":"kubectl get deploy web -o jsonpath='{.spec.template.spec.containers[0].image}'","description":"web runs gopherforge/web:v1","equals":"gopherforge/web:v1"},{"command":"kubectl get deploy web -o jsonpath='{.status.updatedReplicas}/{.status.readyReplicas}'","description":"all 4 replicas are updated and ready","equals":"4/4"}],"id":"k8s-rollback","initialFiles":{},"instructions":"web was updated to gopherforge/web:v2-broken a moment ago. Its new pods never become Ready, the rollout stalls, and the old pods are still serving. Confirm it with kubectl rollout status deployment/web --timeout=20s and kubectl describe pod, look at kubectl rollout history, then roll back with kubectl rollout undo and wait until all 4 replicas run v1 again.","objective":"Notice a rollout that cannot finish and return the Deployment to the version that worked.","setup":"kind create cluster >/dev/null\ncat > /lab/.web.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  replicas: 4\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - containerPort: 8080\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: 8080\nEOF\nkubectl apply -f /lab/.web.yaml >/dev/null\nrm /lab/.web.yaml\nkubectl rollout status deployment/web >/dev/null\nkubectl set image deployment/web web=gopherforge/web:v2-broken >/dev/null\ncluster tick 20s >/dev/null","starter":"kubectl rollout status deployment/web --timeout=20s\nkubectl get pods -l app=web\nkubectl rollout history deployment/web\n","title":"Roll back a stalled rollout"},{"checks":[{"command":"kubectl exec client -- wget -qO- http://web","contains":"gopherforge web","description":"the client gets an answer from http://web"}],"id":"k8s-service-port","initialFiles":{},"instructions":"The web pods are Running and Ready, but the client pod cannot reach them: kubectl exec client -- wget -qO- http://web is refused. Compare the Service's targetPort (kubectl get svc web -o yaml, kubectl get endpoints web) with the port the container listens on (kubectl describe pod -l app=web), and fix the Service (kubectl patch or apply).","objective":"Find why calls to http://web are refused although the pods are Running, and fix the Service.","setup":"kind create cluster >/dev/null\nkubectl create deployment web --image=gopherforge/web:v1 --replicas=2 --port=8080 >/dev/null\nkubectl expose deployment web --port=80 --target-port=80 >/dev/null\nkubectl run client --image=busybox -- sleep 3600 >/dev/null\nkubectl rollout status deployment/web >/dev/null\nkubectl wait --for=condition=Ready pod/client >/dev/null","starter":"kubectl exec client -- wget -qO- http://web\nkubectl get endpoints web\nkubectl describe svc web\n","title":"Fix a Service that refuses connections"},{"checks":[{"command":"curl -s -H 'Host: shop.local' http://localhost/","contains":"gopherforge web","description":"shop.local/ is served by web"},{"command":"curl -s -H 'Host: shop.local' http://localhost/api","description":"shop.local/api is served by api","equals":"api says hello"}],"id":"k8s-ingress","initialFiles":{"shop-ingress.yaml":"apiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: shop\nspec:\n  ingressClassName: nginx\n  rules:\n  - host: shop.local\n    http:\n      paths:\n      # add a /api path to the api Service here, and / to web\n"},"instructions":"The cluster runs ingress-nginx and two Services: web (port 80, the website) and api (port 80, a small API). Create an Ingress named shop for the host shop.local with two Prefix paths: /api to the api Service and / to the web Service (ingressClassName: nginx). Test with curl -H 'Host: shop.local' http://localhost/ and http://localhost/api.","objective":"Send /api to one Service and everything else to another, by host name, through ingress-nginx.","setup":"cluster create --ingress >/dev/null\nkubectl create deployment web --image=gopherforge/web:v1 --port=8080 >/dev/null\nkubectl expose deployment web --port=80 --target-port=8080 >/dev/null\nkubectl create deployment api --image=hashicorp/http-echo --port=5678 -- /http-echo '-text=api says hello' >/dev/null\nkubectl expose deployment api --port=80 --target-port=5678 >/dev/null\nkubectl rollout status deployment/web >/dev/null\nkubectl rollout status deployment/api >/dev/null","starter":"cat shop-ingress.yaml\n# edit it with: nano shop-ingress.yaml\nkubectl get svc\n","title":"Route two apps through one Ingress"},{"checks":[{"command":"kubectl exec frontend -- wget -qO- http://api","contains":"gopherforge web","description":"frontend can call the api"},{"command":"kubectl exec other -- curl -s -m 2 http://api || echo blocked","description":"other is blocked","equals":"blocked"}],"id":"k8s-network-policy","initialFiles":{},"instructions":"Pods frontend (labelled role=frontend) and other can both call http://api right now. Write a NetworkPolicy that selects the api pods (app=api) and allows ingress only from pods labelled role=frontend. Check with kubectl exec frontend -- wget -qO- http://api and kubectl exec other -- curl -sS -m 2 http://api.","objective":"Write a NetworkPolicy that lets pods labelled role=frontend reach the api pods and blocks the rest.","setup":"kind create cluster >/dev/null\nkubectl create deployment api --image=gopherforge/web:v1 --replicas=2 --port=8080 >/dev/null\nkubectl expose deployment api --port=80 --target-port=8080 >/dev/null\nkubectl run frontend --image=busybox --labels=role=frontend -- sleep 3600 >/dev/null\nkubectl run other --image=busybox --labels=role=batch -- sleep 3600 >/dev/null\nkubectl rollout status deployment/api >/dev/null\nkubectl wait --for=condition=Ready pod/frontend pod/other >/dev/null","starter":"kubectl exec frontend -- wget -qO- http://api\nkubectl exec other -- wget -qO- http://api\nkubectl get pods --show-labels\n","title":"Allow only the frontend to call the API"},{"checks":[{"command":"kubectl get hpa web -o jsonpath='{.spec.scaleTargetRef.name}'","description":"an HPA targets web","equals":"web"},{"command":"[ $(kubectl get deploy web -o jsonpath='{.spec.replicas}') -ge 3 ] && echo scaled","description":"web scaled out to at least 3 replicas","equals":"scaled"}],"id":"k8s-autoscaling","initialFiles":{},"instructions":"web runs one replica with a CPU request of 100m and receives 300 requests per second in the background (traffic status). Create a HorizontalPodAutoscaler for the web Deployment: minimum 1, maximum 8, target 50% CPU. Then let time pass with cluster tick 2m and watch kubectl get hpa web and kubectl get events --for hpa/web.","objective":"Let a HorizontalPodAutoscaler add replicas while traffic is running.","setup":"cluster create >/dev/null\nkubectl create deployment web --image=gopherforge/web:v1 --port=8080 >/dev/null\nkubectl set resources deployment web --requests=cpu=100m --limits=cpu=200m >/dev/null\nkubectl expose deployment web --port=80 --target-port=8080 >/dev/null\nkubectl rollout status deployment/web >/dev/null\ntraffic start svc/web --rps 300 >/dev/null","starter":"traffic status\nkubectl top pods\nkubectl get deploy web\n","title":"Autoscale under load"},{"checks":[{"command":"kubectl get node kind-worker2 -o jsonpath='{.spec.unschedulable}'","description":"kind-worker2 is unschedulable","equals":"true"},{"command":"kubectl get pods -l app=web --field-selector spec.nodeName=kind-worker2 -o name | wc -l","description":"no web pod runs on kind-worker2","equals":"0"},{"command":"kubectl get deploy web -o jsonpath='{.status.readyReplicas}'","description":"web still has 3 ready replicas","equals":"3"}],"id":"k8s-drain","initialFiles":{},"instructions":"The cluster has three workers and web runs three replicas. kind-worker2 needs maintenance: cordon it and evict its pods with kubectl drain (DaemonSet pods such as kube-proxy stay; that needs --ignore-daemonsets). Afterwards the node is unschedulable, no web pod runs on it, and web still has 3 ready replicas.","objective":"Move every workload off kind-worker2 so it can be patched, keeping the app available.","setup":"cluster create --workers 3 >/dev/null\nkubectl create deployment web --image=gopherforge/web:v1 --replicas=3 --port=8080 >/dev/null\nkubectl rollout status deployment/web >/dev/null","starter":"kubectl get nodes\nkubectl get pods -o wide -l app=web\n","title":"Drain a node for maintenance"},{"checks":[{"command":"kubectl get deploy api -o jsonpath='{.status.readyReplicas}'","description":"api has a ready replica","equals":"1"},{"command":"kubectl get deploy api -o jsonpath='{.spec.template.spec.containers[0].env[*].valueFrom.configMapKeyRef.name} {.spec.template.spec.containers[0].envFrom[*].configMapRef.name}'","contains":"api-config","description":"LOG_LEVEL comes from the api-config ConfigMap"},{"command":"kubectl get deploy api -o jsonpath='{.spec.template.spec.containers[0].env[*].valueFrom.secretKeyRef.name} {.spec.template.spec.containers[0].envFrom[*].secretRef.name}'","contains":"api-db","description":"DATABASE_URL comes from the api-db Secret"}],"id":"k8s-config","initialFiles":{},"instructions":"The api Deployment (gopherforge/api:v1) crashes because DATABASE_URL is missing (kubectl logs deploy/api --previous). Create a ConfigMap named api-config with LOG_LEVEL=info and a Secret named api-db with DATABASE_URL=postgres://app:s3cret@db:5432/app, add both to the Deployment's environment (kubectl set env --from=configmap/api-config, then --from=secret/api-db) and wait for the rollout.","objective":"Give the api its settings from a ConfigMap and its database URL from a Secret.","setup":"kind create cluster >/dev/null\nkubectl create deployment api --image=gopherforge/api:v1 --port=8080 >/dev/null\ncluster tick 30s >/dev/null","starter":"kubectl get pods -l app=api\nkubectl logs deploy/api --previous\n","title":"Configure an API with a ConfigMap and a Secret"}],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"k8s.architecture","designGuide":{"cautions":["etcd holds everything, so back it up and restrict access to it.","Changes made by hand to running containers are undone by reconciliation."],"cost":"A control plane to run or rent, and the habit of debugging through objects, status and events rather than hosts.","family":"kubernetes","flow":["kubectl sends the object","API server stores it in etcd","Controllers create pods","Scheduler binds to nodes","Kubelet starts containers"],"ratings":[],"strengths":["Each component reconciles independently, so restarts and missed events heal themselves.","One API makes every part of the system observable with kubectl."]},"hint":"The kubelet only runs pods that are already bound to its node, and the scheduler only picks nodes. Which controller compares a pod count with a replica number?","id":"k8s.architecture","introduction":"Kubernetes is easy to treat as a black box until something does not start; then you need to know which component was supposed to act. A cluster is a store of desired state plus independent control loops that keep moving reality towards it. This lesson maps those parts, follows one Deployment from kubectl to running containers, and builds a local cluster with kind to look at them.","nuance":"The ReplicaSet controller in kube-controller-manager sees two pods where its spec asks for three and creates a Pod object. The scheduler then binds it to a node and that node's kubelet starts it.","objective":"Name the control-plane and node components, trace a kubectl apply from the API request to a running container, and inspect the nodes and system pods of a kind cluster.","question":"You delete one of the three pods of a Deployment. Seconds later there are three pods again. Which component created the new Pod object?","references":["https://kubernetes.io/docs/concepts/architecture/","https://kubernetes.io/docs/concepts/overview/components/","https://kubernetes.io/docs/concepts/architecture/controller/","https://kind.sigs.k8s.io/docs/user/quick-start/"],"reviewAnswer":"The ReplicaSet controller in kube-controller-manager","reviewPrompt":"Who replaces a deleted RS pod?","sections":[{"body":"kube-apiserver is the front door and the only component that talks to etcd. kubectl, the controllers, the scheduler and every kubelet are clients of its REST API. Each request is authenticated, authorized (normally by RBAC), filled in with defaults, run through admission control, which can modify or reject it, validated, and then stored in etcd, a consistent key-value store that is the cluster's only source of truth: lose etcd without a backup and you lose the cluster. kube-scheduler watches for pods that have no node, filters out nodes that cannot run them (resources, taints, affinity), scores the rest and records its choice in the pod's spec.nodeName. kube-controller-manager runs dozens of controllers in one process, among them the Deployment, ReplicaSet, Job, node lifecycle, EndpointSlice, namespace and garbage-collector controllers. None of them start containers; they create, update and delete other objects.","title":"The control plane: one API, one store, many controllers"},{"body":"Every node, the control-plane node included, runs a kubelet. It watches the API for pods bound to its node and asks the container runtime, containerd in kind and most clusters, through the Container Runtime Interface to pull images, create the pod sandbox and start containers. It then runs probes and writes container states back into pod status. kube-proxy watches Services and EndpointSlices and programs iptables or nftables rules so that a Service's virtual IP reaches pod IPs; some network plugins replace it entirely. The CNI plugin, kindnet in kind, gives each pod an IP from its node's pod range. The control-plane components are themselves static pods: the kubelet on the control-plane node starts them from manifest files in /etc/kubernetes/manifests, so they run before any scheduler exists, and read-only mirror pods represent them in kube-system.","title":"Nodes: kubelet, container runtime and kube-proxy"},{"body":"Objects carry a spec, the desired state you write, and a status, the observed state written by the component responsible for it. A controller is a loop: observe the current state through watches, compare it with the spec, act to narrow the gap, record what it saw in status, and repeat. Controllers are level-triggered: they react to how things are now, not to a log of past events, so a missed notification or a restarted controller is harmless, because the next pass sees the same gap and closes it. This is why deleting a pod that a ReplicaSet owns does not reduce the replica count, why pods from a dead node reappear on other nodes, and why the fix for drift is to change the spec rather than to poke at whatever is running.","title":"Desired state, observed state and reconciliation"},{"body":"Follow kubectl apply -f web.yaml for a Deployment with three replicas. kubectl sends the object to kube-apiserver, which authenticates you, checks RBAC, runs admission, validates the object and writes it to etcd; apply returns as soon as the object is stored, before anything runs. The Deployment controller notices a Deployment without a matching ReplicaSet and creates one. The ReplicaSet controller sees zero of three pods and creates three Pod objects that have no node yet. The scheduler binds each pod to a node. The kubelet on that node sees the new pod, has containerd pull the image and start the container, and reports the pod Running, then Ready once its probes pass. Every component acted on an object that the previous one wrote, and every step left an event you can read afterwards.","title":"From kubectl apply to a running container"},{"body":"kind (Kubernetes IN Docker) runs each node as a container on your machine, from the kindest/node image that contains the kubelet, containerd and kubeadm. kind create cluster boots the control plane with kubeadm, installs the kindnet CNI and a local-path StorageClass, adds a context named kind-NAME to ~/.kube/config and makes it current. The result is a conformant cluster, good for learning, CI and testing manifests, but not a production environment: all nodes share one kernel and disk, LoadBalancer Services need an extra component, and your laptop's memory is the limit. A small config file describes the node layout. With a single node, kind removes the control-plane taint so that ordinary pods can run there; with workers, the control-plane node keeps its NoSchedule taint and your pods land on the workers.","code":"kind: Cluster\napiVersion: kind.x-k8s.io/v1alpha4\nnodes:\n- role: control-plane\n- role: worker\n- role: worker","language":"yaml","title":"kind: a whole cluster in containers","walkthrough":"This is the whole file for a three-node cluster: one control-plane node and two workers, each a container on your machine. For the default cluster name kind they are called kind-control-plane, kind-worker and kind-worker2. Pass the file with kind create cluster --config kind.yaml; on your own machine, --name lets several clusters run side by side, each with its own kind-NAME context."},{"body":"Build a three-node cluster from a kind config file and look at what kind installed: the nodes, the system pods in kube-system and the details of the control-plane node. Then create a Deployment and read the events to watch the chain of components turn one command into running pods. Deleting all of its pods at the end shows reconciliation at work: nobody asks for new pods, but the ReplicaSet still wants three.","code":"cat > kind.yaml <<'EOF'\nkind: Cluster\napiVersion: kind.x-k8s.io/v1alpha4\nnodes:\n- role: control-plane\n- role: worker\n- role: worker\nEOF\nkind create cluster --config kind.yaml\nkubectl cluster-info\nkubectl get nodes -o wide\nkubectl get pods -n kube-system -o wide\nkubectl describe node kind-control-plane\nkubectl create deployment web --image=nginx:1.27 --replicas=3\nkubectl get events --sort-by=.metadata.creationTimestamp\nkubectl rollout status deploy/web\nkubectl get pods -o wide\nkubectl delete pod -l app=web\nkubectl get pods","language":"bash","title":"Try it in the lab terminal","walkthrough":"get nodes lists kind-control-plane, kind-worker and kind-worker2, all Ready on v1.34.1 with containerd://2.1.1. In kube-system, etcd, kube-apiserver, kube-controller-manager and kube-scheduler are static pods named after their node, using its IP 172.18.0.2; kindnet and kube-proxy run once per node; the lab adds metrics-server, which plain kind does not install. describe node shows the taint node-role.kubernetes.io/control-plane:NoSchedule, so web lands on the workers. The events follow the chain: ScalingReplicaSet, three SuccessfulCreate, Scheduled to kind-worker or kind-worker2, Pulling, Pulled. After delete pod -l app=web, three new web-<hash>-<id> pods are already ContainerCreating."}],"takeaway":"A cluster is the API server and etcd holding desired state, plus controllers, the scheduler and kubelets that each reconcile one piece of it. When something does not happen, ask which component should have acted and read its events.","title":"How a cluster works: control plane, nodes and reconciliation loops","unitID":"k8s-foundations","wrongAnswers":["The kubelet on the node where the pod ran","The scheduler, which restores deleted pods"]},{"conceptTag":"k8s.kubectl-contexts","designGuide":{"cautions":["use-context changes every terminal that shares the kubeconfig.","A remembered default namespace makes objects seem to vanish."],"cost":"A visible context in the prompt and explicit --context and -n flags in every script.","family":"kubernetes","flow":["Check current-context","Choose the namespace with -n","Search widely with -A","Pass --context in scripts"],"ratings":[],"strengths":["One file describes every cluster, identity and default namespace you use.","Per-namespace contexts make switching cheap and explicit."]},"hint":"set-context writes to a file, not to your shell session. Which namespace does a command use when you pass no -n?","id":"k8s.kubectl-contexts","introduction":"Every kubectl command goes to one API server, as one user, in one namespace, and all three come from a file you rarely look at. The most expensive kubectl mistakes are seldom wrong commands; they are right commands sent to the wrong cluster or namespace. This lesson explains kubeconfig, contexts and namespaces, and the habits that keep production out of reach of a command meant for your laptop.","nuance":"set-context --current stored shop in the context entry in kubeconfig, so it survives new terminals. Plain commands look in shop until you pass -n default or run set-context --current --namespace=default.","objective":"Read a kubeconfig, list, create and switch contexts, set a default namespace, and use -n, -A and explicit contexts so that commands reach the cluster and namespace you intend.","question":"Yesterday you ran kubectl config set-context --current --namespace=shop. Today, in a new terminal, kubectl get deployment web reports NotFound, although web runs in default. What is still in effect?","references":["https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/","https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/","https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/"],"reviewAnswer":"Stores the context's default namespace in kubeconfig","reviewPrompt":"set-context --current --namespace?","sections":[{"body":"kubectl reads ~/.kube/config unless the KUBECONFIG environment variable lists other files, which it merges in order (colon-separated on Linux and macOS). The file holds three lists and a pointer. clusters hold an API server URL and the CA certificate to trust. users hold credentials: a client certificate, a token, or an exec plugin that fetches short-lived tokens, which is how EKS, GKE and AKS usually sign you in. contexts each join one cluster and one user under a name, optionally with a default namespace. current-context names the context kubectl uses when you do not pass --context. kind create cluster adds a cluster, a user and a context, all called kind-NAME, and makes that context current, which is why creating a cluster quietly changes where your next command goes.","code":"apiVersion: v1\nkind: Config\nclusters:\n- name: kind-kind\n  cluster:\n    server: https://127.0.0.1:6443\n    certificate-authority-data: LS0tLS1CRUdJTi...\nusers:\n- name: kind-kind\n  user:\n    client-certificate-data: LS0tLS1CRUdJTi...\n    client-key-data: LS0tLS1CRUdJTi...\ncontexts:\n- name: kind-kind\n  context:\n    cluster: kind-kind\n    user: kind-kind\n- name: dev\n  context:\n    cluster: kind-kind\n    user: kind-kind\n    namespace: dev\ncurrent-context: kind-kind","language":"yaml","title":"What kubeconfig contains","walkthrough":"Two contexts share one cluster and one user and differ only in their default namespace, a common way to give each team or environment its own entry. The user's credentials are an embedded certificate and private key with full admin rights on the kind cluster, so treat the file like a private key: never commit it, and keep production credentials in a separate file that you add to KUBECONFIG only when you need it."},{"body":"kubectl config get-contexts lists every context and marks the current one with an asterisk; kubectl config current-context prints only its name, which is what scripts should check. use-context NAME rewrites current-context in the file, so it affects every terminal and every tool that reads the same kubeconfig, not only the shell where you typed it. set-context NAME --cluster=C --user=U --namespace=N creates or edits a context entry. A context is only a named triple, so one per namespace you work in costs nothing, and none of these commands touch the server: the namespace does not even have to exist yet. delete-context removes the entry but not the cluster or user it refers to. kubectl config view prints the merged configuration with credentials redacted, and --minify limits it to what the current context uses.","title":"Listing, switching and creating contexts"},{"body":"Most objects, such as pods, Deployments, Services and Secrets, live in a namespace; nodes, namespaces, PersistentVolumes, StorageClasses and ClusterRoles do not, and kubectl api-resources shows which is which in its NAMESPACED column. Every command acts in one namespace: the one given with -n or --namespace, otherwise the context's namespace, otherwise default. -A (--all-namespaces) widens a read to every namespace and adds a NAMESPACE column. Names are unique only within a namespace, so web in shop and web in default are unrelated objects. A fresh cluster has default, kube-system for cluster components, kube-public, kube-node-lease for node heartbeats and, in kind, local-path-storage. Namespaces scope names, RBAC permissions and quotas; they are not a network boundary unless NetworkPolicies make them one.","title":"Namespaces are the default scope"},{"body":"Typing -n shop on every command is tedious, so you store it once in the context with kubectl config set-context --current --namespace=shop. That convenience is also the most common source of a puzzling No resources found: the setting lives in kubeconfig, survives new terminals and reboots, and kubectl never reminds you of it. Look at the NAMESPACE column of get-contexts when results seem to be missing. An explicit -n always overrides the context's namespace, and so does a namespace written in a manifest's metadata. When a manifest names one namespace and -n names another, kubectl refuses with the namespace from the provided object does not match, rather than guessing which one you meant.","code":"kubectl config set-context --current --namespace=shop\nkubectl config get-contexts\nkubectl get deployments\nkubectl get deployments -n default","language":"bash","title":"Set a default namespace, and remember that you did","walkthrough":"After set-context, the current line of get-contexts shows shop in its NAMESPACE column, and a plain get deployments lists the objects in shop. The last command looks in default for this one invocation only; the stored setting stays shop until you change it with another set-context."},{"body":"Wrong-context accidents follow a pattern: a context switched in one terminal changes the file every other terminal reads; kind create cluster or a cloud CLI's get-credentials command makes a new cluster current without asking; a script runs against whatever happens to be current. Guards that work: show the context and namespace in your shell prompt (kube-ps1 or your prompt theme can do it); keep production credentials in a separate kubeconfig that you load deliberately, with read-only permissions by default; in scripts and CI, pass --context and -n on every command or point KUBECONFIG at a file that contains only the intended cluster; and make destructive scripts check kubectl config current-context first. The lab terminal holds one cluster, but --context works there for any context in its kubeconfig, so you can practise the habit.","code":"kubectl --context kind-staging -n shop get deployments\nKUBECONFIG=$HOME/.kube/prod.yaml kubectl get nodes","language":"bash","title":"Guarding against the wrong context","walkthrough":"The first command names its cluster and namespace explicitly, so it does the same thing whatever is current. The second points a single command at a dedicated production kubeconfig without merging it into your everyday file. Both make the target visible in shell history and in code review, which is where wrong-context mistakes are caught."},{"body":"Create a namespace and a Deployment inside it, then see how the namespace decides what a plain command shows and how -n and -A override it. Next, store a default namespace in the current context, add a second context for the same cluster and switch to it. The last command is meant to fail, because kubectl can only switch to contexts that already exist in kubeconfig.","code":"kind create cluster\nkubectl config get-contexts\nkubectl create namespace shop\nkubectl create deployment web --image=nginx:1.27 -n shop\nkubectl get deployments\nkubectl get deployments -A\nkubectl config set-context --current --namespace=shop\nkubectl get deployments\nkubectl config set-context dev --cluster=kind-kind --user=kind-kind --namespace=default\nkubectl config use-context dev\nkubectl config get-contexts\nkubectl get deployments\nkubectl get deployments -n shop\nkubectl config use-context prod","language":"bash","title":"Try it in the lab terminal","walkthrough":"get-contexts starts with one context, kind-kind, current and without a namespace. The Deployment created with -n shop is invisible to a plain get deployments, which answers No resources found in default namespace., and appears with -A beside the system Deployments. After set-context --current --namespace=shop the same plain command lists web. The dev context reuses the kind-kind cluster and user; after use-context dev the asterisk moves to dev, kind-kind keeps shop in its NAMESPACE column, and plain commands look in default again until you add -n shop. use-context prod fails with error: no context exists with the name: \"prod\"."}],"takeaway":"A context is a named cluster, user and namespace in kubeconfig, and current-context silently decides where every command goes. Keep it visible in your prompt, pass --context and -n in scripts, and keep production credentials out of your everyday file.","title":"kubeconfig, contexts and namespaces: know where every kubectl command goes","unitID":"k8s-foundations","wrongAnswers":["A shell variable that pins kubectl to kube-system","An RBAC rule that hides default from new sessions"]},{"conceptTag":"k8s.objects-yaml","designGuide":{"cautions":["A valid field in the wrong place still passes validation.","Status is current only when observedGeneration equals generation."],"cost":"Learning to navigate schemas with explain and to query state with jsonpath instead of reading tables.","family":"kubernetes","flow":["Scaffold with --dry-run","Look fields up with explain","Apply and fix strict errors","Read status with jsonpath"],"ratings":[],"strengths":["One uniform shape for every kind makes any object readable.","Strict validation turns typos into errors at apply time."]},"hint":"Field names are case-sensitive. Think about what kubectl asks the API server to do with fields its schema does not know.","id":"k8s.objects-yaml","introduction":"Everything in Kubernetes is an object stored by the API server, and every object has the same shape. Once you can read that shape you can write manifests without copying them blindly, find any field with kubectl explain, and query live state precisely instead of scanning tables. The API server is strict about the shape too: a misspelt field is an error, not something it quietly ignores.","nuance":"kubectl requests strict field validation by default, so the API server rejects the request with strict decoding error: unknown field \"spec.template.spec.containers[0].readinessprobe\" and creates nothing.","objective":"Write a manifest from scratch or from a dry-run scaffold, tell spec from status, choose between labels and annotations, look fields up with kubectl explain, read live state with jsonpath and recognise strict validation errors.","question":"You apply a Deployment whose container spec contains readinessprobe: with a lower-case p. What does kubectl apply do with default settings?","references":["https://kubernetes.io/docs/concepts/overview/working-with-objects/","https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/","https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/","https://kubernetes.io/docs/reference/kubectl/jsonpath/"],"reviewAnswer":"Its controller, never the manifest","reviewPrompt":"Who writes an object's status?","sections":[{"body":"apiVersion and kind select the schema: apps/v1 Deployment, v1 Pod, batch/v1 Job, networking.k8s.io/v1 Ingress. The part before the slash is the API group, and the core group has none. metadata identifies the object: name (unique per kind and namespace), namespace, labels and annotations; the server adds uid, resourceVersion, generation and creationTimestamp. spec is the desired state and belongs to you. status is the observed state and belongs to the controller that manages the object. You never write status in a manifest, and an update through the main resource cannot change it, because status is a separate subresource that the controller writes. When spec and status disagree, the object is still converging or something is stuck, and status usually says which.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\n  annotations:\n    team.example.com/owner: payments\n    team.example.com/runbook: https://wiki.example.com/web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: nginx\n        image: nginx:1.27\n        ports:\n        - containerPort: 80","language":"yaml","title":"Four fields you write and one you read","walkthrough":"There are two metadata blocks: the Deployment's own and the pod template's. Only the template becomes pods, so labels on the Deployment itself never reach them, and the selector must match the template's labels or the API server rejects the object. No namespace is set, so the manifest lands wherever kubectl points, which keeps it reusable. The runbook link is an annotation because nothing will ever select on it."},{"body":"Labels are short key-value pairs that the system queries: selectors in ReplicaSets, Services and NetworkPolicies, and kubectl -l, all match on labels. Keys may carry a DNS prefix, as in app.kubernetes.io/name, and values are at most 63 characters of letters, digits, dashes, underscores and dots. Annotations hold everything that is not used for selection: owners, runbook links, build commits, and settings read by tools, which is why ingress controllers are configured through annotations. They can be large, up to 256 KiB per object in total, and they are not indexed. The rule of thumb: if you would ever write -l key=value or a selector with it, make it a label; otherwise make it an annotation. The recommended app.kubernetes.io labels (name, instance, version, component, part-of, managed-by) give tools a shared vocabulary.","title":"Labels select, annotations describe"},{"body":"You do not need to memorise schemas. kubectl explain prints the documentation of any field path from the server's OpenAPI schema, so it matches your cluster's version exactly, and --recursive shows a whole subtree at once. For a starting manifest, let kubectl generate one: the imperative create commands accept --dry-run=client -o yaml, which builds the object locally and prints it instead of sending it. The output may contain empty placeholder fields you can delete, and it lacks things you will want, such as resource requests and probes. Edit the file and keep it; the scaffold is a typing aid, not the deliverable. --dry-run=server goes one step further: the API server runs defaulting, validation and admission on the object but stores nothing.","code":"kubectl explain deployment.spec\nkubectl explain pod.spec.containers\nkubectl create deployment web --image=nginx:1.27 --replicas=2 --dry-run=client -o yaml > web.yaml","language":"bash","title":"Find fields with explain, scaffold with --dry-run","walkthrough":"explain deployment.spec lists replicas, selector, template, strategy and the other fields with their types; explain pod.spec.containers does the same one level down, including image, ports, env, resources and the three probes. In the lab the descriptions are short notes; on a real cluster they are the full API documentation. The last command writes a complete Deployment to web.yaml and creates nothing."},{"body":"kubectl asks the API server for strict field validation by default (--validate=strict). A field the schema does not know, or a field given twice, fails the whole request instead of being dropped. That turns a misspelt imagee, or a readinessProbe indented under the wrong parent, into an immediate error that names the exact path, rather than a Deployment that silently ignores half of what you wrote. Wrong types are rejected as well, such as replicas: \"2\" written as a string. Use --validate=warn only when you must apply manifests written for a newer API, and treat every warning as a bug. Validation cannot catch a valid field in a place where it is also valid, such as a label put on the Deployment's metadata instead of the template's, so read manifests critically.","title":"Strict validation: typos are errors"},{"body":"kubectl get -o yaml shows the object as stored, including the defaults the server added, such as the RollingUpdate strategy, and the full status. For scripts and quick checks, -o jsonpath extracts exact fields and -o custom-columns builds a table of your own. Compare metadata.generation, which increases on every spec change, with status.observedGeneration: while they differ, the controller has not processed your latest change, and the rest of status describes an older spec. Conditions are the structured part of status, a list of entries with type, status and reason, such as Available and Progressing for a Deployment; kubectl wait and rollout status read them too. Prefer these fields to parsing table output, whose columns are meant for people and may change between versions.","code":"kubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{\"\\n\"}'\nkubectl get deployment web -o jsonpath='{.status.conditions[?(@.type==\"Available\")].status}{\"\\n\"}'\nkubectl get pods -o custom-columns=NAME:.metadata.name,PHASE:.status.phase,NODE:.spec.nodeName","language":"bash","title":"Read live state: -o yaml, jsonpath and custom columns","walkthrough":"The jsonpath expressions print bare values, such as 2 2 for generation and observedGeneration and True for the Available condition, which a script can compare directly. The filter [?(@.type==\"Available\")] selects a condition by its type instead of its position, which matters because the order of conditions is not guaranteed. custom-columns prints a table with exactly the columns you named."},{"body":"Look up the Deployment fields and let kubectl generate a scaffold, then apply a hand-written manifest that contains a one-letter typo and watch the API server reject it. After fixing the typo with sed, read back what the server stored. Finally change the spec through the file, apply it again, and query generation, a condition and pod placement with jsonpath and custom columns.","code":"kind create cluster\nkubectl explain deployment.spec\nkubectl create deployment web --image=nginx:1.27 --replicas=2 --dry-run=client -o yaml\ncat > web.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\n  annotations:\n    team.example.com/owner: payments\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: nginx\n        imagee: nginx:1.27\nEOF\nkubectl apply -f web.yaml\nsed -i 's/imagee:/image:/' web.yaml\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\nkubectl get deployment web -o yaml\nsed -i 's/replicas: 2/replicas: 3/' web.yaml\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\nkubectl get deployment web -o jsonpath='{.metadata.generation} {.status.observedGeneration}{\"\\n\"}'\nkubectl get deployment web -o jsonpath='{.status.conditions[?(@.type==\"Available\")].status}{\"\\n\"}'\nkubectl get pods -o custom-columns=NAME:.metadata.name,PHASE:.status.phase,NODE:.spec.nodeName","language":"bash","title":"Try it in the lab terminal","walkthrough":"explain deployment.spec lists replicas, selector, template and strategy, and the dry-run prints a Deployment without creating it. The first apply fails with Error from server (BadRequest) ... strict decoding error: unknown field \"spec.template.spec.containers[0].imagee\", and nothing is created. After the fix, -o yaml shows what the server added: uid, resourceVersion, generation: 1, a RollingUpdate strategy with 25% maxSurge and maxUnavailable, and a status block you never wrote. Applying the edited file prints configured; generation and observedGeneration then both read 2, Available is True, and custom-columns lists each web-<hash>-<id> pod as Running on kind-control-plane."}],"takeaway":"Every object is apiVersion, kind, metadata, spec and status: you own the spec, controllers own the status. Scaffold with --dry-run=client -o yaml, look fields up with kubectl explain, let strict validation catch typos, and read state with jsonpath rather than by eye.","title":"Anatomy of an object: apiVersion, kind, metadata, spec and status","unitID":"k8s-foundations","wrongAnswers":["Creates it and silently drops the unknown field","Creates it and corrects the name to readinessProbe"]},{"conceptTag":"k8s.pods","designGuide":{"cautions":["A bare pod is never replaced after deletion or node loss.","The STATUS column is not the phase; read the container state."],"cost":"Learning three overlapping status vocabularies and wrapping every long-lived pod in a controller.","family":"kubernetes","flow":["Group co-located containers","Choose a restartPolicy","Read container states","Use logs --previous and exec","Let a controller own the pod"],"ratings":[],"strengths":["Co-located containers share network and volumes without extra plumbing.","Container states and reasons pinpoint most start-up failures."]},"hint":"CrashLoopBackOff is a reason attached to a container state, not a phase. With restartPolicy Always, can the pod ever reach a terminal phase?","id":"k8s.pods","introduction":"A Pod is the smallest thing Kubernetes schedules: one or more containers that always run together on one node and share a network identity. Most debugging starts by reading a pod's state, and the STATUS column that kubectl prints mixes three different things. This lesson separates them, shows how restart policy changes what a failure looks like, and explains why you will rarely create a Pod yourself.","nuance":"The pod has started containers and restartPolicy Always restarts them forever, so its phase stays Running. CrashLoopBackOff is the container's Waiting reason between restart attempts.","objective":"Run and inspect pods, tell the pod phase from container states and the STATUS column, choose a restartPolicy, use logs and exec, and explain why controllers rather than people should create pods.","question":"kubectl get pods shows STATUS CrashLoopBackOff for a pod that a Deployment owns. What is the pod's status.phase?","references":["https://kubernetes.io/docs/concepts/workloads/pods/","https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/","https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/","https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/"],"reviewAnswer":"Running, with the container Waiting in CrashLoopBackOff","reviewPrompt":"Pod phase during CrashLoopBackOff?","sections":[{"body":"Containers in a pod share a network namespace: one IP address, one port space and localhost between them, so two containers in a pod cannot both listen on port 80. They also share the hostname, and they can share volumes, such as an emptyDir that lives exactly as long as the pod. They are scheduled together onto one node and deleted together. That is the test for putting containers into one pod: they must be co-located and share a lifecycle, like an application and the agent that ships its logs, or a proxy that serves only it. A web application and its database scale and fail independently, so they belong in separate pods. Init containers run to completion before the app containers start, and native sidecars, init containers with restartPolicy: Always, start first and keep running beside them.","code":"apiVersion: v1\nkind: Pod\nmetadata:\n  name: pair\n  labels:\n    app: pair\nspec:\n  volumes:\n  - name: html\n    emptyDir: {}\n  containers:\n  - name: web\n    image: nginx:1.27\n    ports:\n    - containerPort: 80\n    volumeMounts:\n    - name: html\n      mountPath: /usr/share/nginx/html\n  - name: writer\n    image: busybox\n    command: [\"sh\", \"-c\", \"while true; do date > /html/index.html; sleep 10; done\"]\n    volumeMounts:\n    - name: html\n      mountPath: /html","language":"yaml","title":"One pod, several containers, one network namespace","walkthrough":"The writer container rewrites index.html every ten seconds in the shared emptyDir, and nginx serves the same file from its own mount path: one volume, two mount points. Because the containers share the pod's network, the writer could also reach nginx at http://localhost:80. If either process exits, the kubelet restarts only that container, according to the pod's restartPolicy, and leaves the other one running."},{"body":"status.phase is a coarse summary with five values. Pending: accepted, but not every container has started, which covers scheduling and image pulls. Running: bound to a node, with at least one container running, starting or restarting. Succeeded: every container exited with code 0 and none will restart. Failed: every container has terminated and at least one failed. Unknown: the node stopped reporting. Each container has its own state: Waiting with a reason such as ContainerCreating, ErrImagePull, ImagePullBackOff or CrashLoopBackOff; Running with a start time; or Terminated with an exit code and a reason such as Completed, Error or OOMKilled. The STATUS column of kubectl get pods is computed by kubectl from all of this and shows the most telling reason. So a pod in CrashLoopBackOff is in phase Running, and an ImagePullBackOff pod is Pending.","title":"Pod phase, container state and the STATUS column"},{"body":"The pod's restartPolicy applies to all of its app containers and is enforced by the kubelet on the same node; it never moves a pod to another node. Always, the default and the only value a Deployment accepts, restarts a container whenever it exits, even with code 0, after an exponential back-off of 10, 20, 40 seconds and so on, capped at five minutes; the waits between attempts are what CrashLoopBackOff means. OnFailure restarts only after a non-zero exit, so a successful run ends in Succeeded. Never leaves the container terminated and the pod Succeeded or Failed; Jobs use OnFailure or Never. A restart creates a fresh process from the same image in the same pod: same IP and volumes, but no in-memory state. kubectl logs --previous shows the output of the run before.","title":"restartPolicy decides what a failure looks like"},{"body":"kubectl run creates a single Pod. --image is required, --restart sets restartPolicy, --port records a containerPort, --labels sets labels, and everything after -- becomes the container's args, or its command when you add --command. kubectl logs reads a container's stdout and stderr as kept by the kubelet on the node, so the logs disappear with the pod; ship them to a log store for anything you need later. Use -c to choose a container, --previous for the last terminated instance, --tail and --since to limit the output, and -f to follow it. kubectl exec starts a new process inside a running container with whatever tools its image contains. Minimal images often have no shell at all, which is what kubectl debug and ephemeral containers are for on a real cluster; the lab does not offer kubectl debug.","code":"kubectl run web --image=nginx:1.27 --port=80\nkubectl run once --image=busybox --restart=Never -- echo done\nkubectl logs web --tail=20\nkubectl exec web -- cat /etc/hostname\nkubectl delete pod web","language":"bash","title":"kubectl run, logs and exec","walkthrough":"The first pod runs nginx with the default restartPolicy Always. The second runs echo done once and ends in phase Succeeded, which kubectl shows as Completed. Once web is running, logs --tail=20 prints nginx's start-up lines, and exec runs cat inside its container and prints the hostname, web. delete removes the pod for good: nothing recreates it."},{"body":"A Pod is bound to one node for its whole life. If that node fails or is drained, or if you delete the pod by mistake, the pod is gone and nothing creates a replacement. Pods are also nearly immutable: most of the spec cannot change after creation, the container image being one of the few exceptions, so changing ports, environment or volumes means deleting and recreating the pod. Controllers solve both problems. A Deployment keeps a number of interchangeable replicas and replaces pods when the template changes, a StatefulSet adds stable names and storage, a DaemonSet runs one pod per node, and a Job runs pods to completion with retries. Bare pods are fine for a one-off debugging shell or a quick experiment; everything you want to keep running should have an owner.","title":"Why you rarely create bare Pods"},{"body":"Start four single-container pods that end up in four different states, let half a minute of cluster time pass with cluster tick, and compare the STATUS column with the phase and container state underneath it. Then read the events of the pod that cannot pull its image and the logs of the one that crashes. Finally run the two-container pod from above, and delete a bare pod to see that nothing brings it back.","code":"kind create cluster\nkubectl run web --image=nginx:1.27 --port=80\nkubectl run once --image=busybox --restart=Never -- echo done\nkubectl run typo --image=nginx:1.277\nkubectl run crash --image=gopherforge/web:v3-crash\ncluster tick 30s\nkubectl get pods\nkubectl get pods -o custom-columns=NAME:.metadata.name,PHASE:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount,WAITING:.status.containerStatuses[0].state.waiting.reason,EXIT:.status.containerStatuses[0].state.terminated.exitCode\nkubectl describe pod typo\nkubectl logs crash --previous\ncat > pair.yaml <<'EOF'\napiVersion: v1\nkind: Pod\nmetadata:\n  name: pair\n  labels:\n    app: pair\nspec:\n  volumes:\n  - name: html\n    emptyDir: {}\n  containers:\n  - name: web\n    image: nginx:1.27\n    ports:\n    - containerPort: 80\n    volumeMounts:\n    - name: html\n      mountPath: /usr/share/nginx/html\n  - name: writer\n    image: busybox\n    command: [\"sh\", \"-c\", \"while true; do date > /html/index.html; sleep 10; done\"]\n    volumeMounts:\n    - name: html\n      mountPath: /html\nEOF\nkubectl apply -f pair.yaml\nkubectl wait --for=condition=Ready pod/pair\nkubectl exec pair -c writer -- hostname\nkubectl delete pod web\nkubectl get pods","language":"bash","title":"Try it in the lab terminal","walkthrough":"After 30 seconds get pods shows four STATUS values: crash CrashLoopBackOff with 2 restarts, once Completed, typo ImagePullBackOff, web Running. The custom columns show what lies underneath: crash is in phase Running while its container waits in CrashLoopBackOff, once is Succeeded with exit code 0, and typo is still Pending. describe pod typo ends with Failed to pull image \"nginx:1.277\" ... not found and Back-off pulling image events, and logs --previous shows the Go panic that killed crash. pair turns Ready with 2/2 containers, exec -c writer -- hostname prints pair, and after delete pod web nothing replaces it."}],"takeaway":"A pod's phase, its containers' states and kubectl's STATUS column are three different views; read the container state and its reason to learn what is wrong. Containers in a pod share network, hostname and volumes, and pods are disposable, so let a controller own them.","title":"Pods: shared containers, phases, container states and restart policy","unitID":"k8s-foundations","wrongAnswers":["Failed, until the next restart attempt succeeds","Pending, because no container is running at the moment"]},{"conceptTag":"k8s.labels-selectors","designGuide":{"cautions":["Overlapping selectors make controllers adopt, or Services route to, the wrong pods.","Workload selectors are immutable; a wrong one means a new object."],"cost":"A labelling convention agreed up front and discipline about which labels go into selectors.","family":"kubernetes","flow":["Choose stable selector labels","Stamp them in the template","Query with -l and -L","Relabel to quarantine a pod"],"ratings":[],"strengths":["Loose coupling lets one label change move a pod in or out of rotation.","One selector language serves kubectl, controllers, Services and policies."]},"hint":"Selectors are evaluated continuously. Which objects select app=web, and does anything select app=debug?","id":"k8s.labels-selectors","introduction":"Kubernetes has no fixed links between a ReplicaSet and its pods or between a Service and its backends; they find each other through labels, and the match is evaluated continuously. That makes the system flexible, because changing one label can pull a pod out of rotation. It also makes it fragile when two selectors overlap or a label changes by accident.","nuance":"The ReplicaSet releases the pod that no longer matches and creates a new one to get back to 3, and the Service drops it from its endpoints. The relabelled pod keeps running with no owner until you delete it.","objective":"Label objects, query them with equality-based and set-based selectors, explain how ReplicaSets and Services choose pods by label, and predict what relabelling a pod does.","question":"A web pod misbehaves and you change its label from app=web to app=debug. Its ReplicaSet wants 3 replicas, and a Service selects app=web. What happens next?","references":["https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/","https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/","https://kubernetes.io/docs/concepts/services-networking/service/","https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/"],"reviewAnswer":"RS makes a replacement; the old pod runs without traffic","reviewPrompt":"Pod relabelled out of its RS?","sections":[{"body":"A label is a key-value pair in metadata.labels, and keys may carry a DNS prefix such as app.kubernetes.io/name. Selectors come in two forms. Equality-based: app=web, and app!=web, which also matches objects without an app label. Set-based: app in (web,cache), tier notin (backend), tier for objects that have the key, and !tier for objects that do not. Commas mean AND and there is no OR across keys; in on a single key is the only way to accept several values. kubectl get -l accepts both forms, --show-labels appends every label, and -L app,tier (long form --label-columns) adds one column per key. In manifests, a Service takes a plain map matched by equality, while ReplicaSets, Deployments, Jobs and NetworkPolicies take matchLabels and matchExpressions.","code":"kubectl get pods --show-labels\nkubectl get pods -l app=web\nkubectl get pods -l 'app in (web,cache),tier!=backend'\nkubectl get pods -l '!tier' --label-columns=app,tier","language":"bash","title":"Labels and the selector language","walkthrough":"Quote set-based selectors so that the shell does not interpret the parentheses or the exclamation mark. The third command matches pods labelled web or cache unless they have tier=backend, so pods without any tier label match too. The fourth lists only pods without a tier label and shows their app and tier values as columns, the second of them empty."},{"body":"Workload controllers use a LabelSelector: matchLabels for exact values and matchExpressions with the operators In, NotIn, Exists and DoesNotExist; every condition must hold. The pod template's labels must satisfy the selector, or the API server rejects the object with selector does not match template labels. A Deployment adds a pod-template-hash label to the selector and pods of each ReplicaSet it creates, so the ReplicaSets of different revisions never claim each other's pods. Keep selectors narrow. A ReplicaSet adopts any pod without an owner that matches its selector, so a hand-made pod with the same labels is counted, and the ReplicaSet deletes a pod to get back to its number. A Service whose selector matches two workloads sends traffic to both.","code":"apiVersion: apps/v1\nkind: ReplicaSet\nmetadata:\n  name: web\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: web\n    matchExpressions:\n    - key: track\n      operator: In\n      values: [stable, canary]\n  template:\n    metadata:\n      labels:\n        app: web\n        track: stable\n    spec:\n      containers:\n      - name: nginx\n        image: nginx:1.27","language":"yaml","title":"matchLabels and matchExpressions","walkthrough":"This ReplicaSet keeps three pods that carry app=web and a track label of stable or canary. Its template stamps app=web and track=stable on every pod it creates, which satisfies both conditions, and kubectl get rs -o wide prints the selector as app=web,track in (stable,canary). In practice you create Deployments rather than ReplicaSets, but their selector field has exactly this shape."},{"body":"Selection is live. The ReplicaSet controller compares the pods that match its selector with spec.replicas whenever something changes: it adopts matching pods that have no controller, and it releases pods it owns that stop matching by removing its ownerReference from them. The EndpointSlice controller recomputes a Service's endpoints from its selector, and only Ready pods among them receive traffic. NetworkPolicies, PodDisruptionBudgets and topology spread constraints select pods by label as well. The consequences are direct: a label changed by hand takes effect everywhere at once; a stray pod created with app=web may be adopted by an existing ReplicaSet; and a Service whose selector matches two Deployments balances across both, which is how some canary releases work on purpose and how many outages happen by accident.","title":"Who selects by label, and when"},{"body":"Relabelling is the standard way to quarantine a misbehaving pod without killing it. Change app=web to app=debug and three things happen. The ReplicaSet no longer matches the pod, releases it and, now one short, creates a replacement. The Service drops the pod's IP from its endpoints, so it receives no new requests. The pod itself keeps running untouched, with its memory and logs intact for exec, logs or port-forward. When you are done, delete it; it no longer has an owner, so nothing else will. Do not relabel it back, because the ReplicaSet would adopt it, count one pod too many and delete one. The GopherForge lab models the release and the replacement too.","code":"POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')\nkubectl label pod $POD app=debug --overwrite\nkubectl get pods --label-columns=app\nkubectl get endpoints web","language":"bash","title":"Taking a pod out of its ReplicaSet","walkthrough":"On a real cluster, get pods then shows four pods from the web ReplicaSet's template: the quarantined one with APP debug and three with web, one of them only seconds old. get endpoints web lists the IPs of the three web pods only. The first line stores a pod name in a shell variable, a common pattern because pod names carry random suffixes."},{"body":"In apps/v1, spec.selector of a Deployment, ReplicaSet, StatefulSet or DaemonSet cannot change after creation; an update fails with spec.selector ... field is immutable. The reason is ownership: a new selector could suddenly match another workload's pods, or orphan every pod the controller runs, and there is no safe automatic answer to either. Template labels may change as long as they still satisfy the selector, and you can add labels to the template freely. To change a selector, create a new Deployment under a new name, move traffic to it, and delete the old one. So choose selector labels on day one that will never need to change, such as app.kubernetes.io/name and app.kubernetes.io/instance, and keep version or track labels out of the selector.","title":"Why a Deployment's selector is immutable"},{"body":"Run two Deployments and expose one of them as a Service, query their pods with both selector forms, and look at the selector each ReplicaSet uses. Then quarantine one web pod by relabelling it and watch the Service's endpoints shrink, the Service side of the story above. The last command tries to change the Deployment's selector and is meant to fail, because the API server refuses it.","code":"kind create cluster\nkubectl create deployment web --image=nginx:1.27 --replicas=3\nkubectl create deployment cache --image=redis:7\nkubectl rollout status deploy/web\nkubectl expose deployment web --port=80\nkubectl get pods --show-labels\nkubectl get pods -l 'app in (web,cache)' --label-columns=app\nkubectl get rs -o wide\nkubectl get endpoints web\nPOD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')\nkubectl label pod $POD app=debug --overwrite\nkubectl get endpoints web\nkubectl patch deployment web -p '{\"spec\":{\"selector\":{\"matchLabels\":{\"app\":\"web2\"}},\"template\":{\"metadata\":{\"labels\":{\"app\":\"web2\"}}}}}'","language":"bash","title":"Try it in the lab terminal","walkthrough":"--show-labels reveals the pod-template-hash label each Deployment added beside app, and get rs -o wide shows it inside each ReplicaSet's selector, as in app=web,pod-template-hash=<hash>. The set-based query lists the three web pods and the cache pod with an APP column. get endpoints web starts with three pod IPs on port 80; after one pod is relabelled to app=debug it lists two. On a real 1.34 cluster get endpoints also warns that v1 Endpoints is deprecated in favour of EndpointSlices. The patch fails with The Deployment \"web\" is invalid: spec.selector: Invalid value: ... field is immutable."}],"takeaway":"Selectors, not links, connect controllers and Services to pods, and they are evaluated continuously, so a label change takes effect everywhere at once. Pick narrow, stable selector labels at creation, because a Deployment's selector can never change.","title":"Labels and selectors: how controllers and Services find their pods","unitID":"k8s-foundations","wrongAnswers":["The RS deletes the relabelled pod and creates a new one","Nothing changes until the Deployment is next rolled out"]},{"conceptTag":"k8s.declarative-apply","designGuide":{"cautions":["Manual changes to applied fields are overwritten without a warning.","Deleting a file does not delete the objects it created."],"cost":"A repository of manifests, a review process, and the discipline to change the cluster only through them.","family":"kubernetes","flow":["Write manifests in git","Review changes as pull requests","apply -f DIR or apply -k DIR","Read created and configured","Fix drift in the file"],"ratings":[],"strengths":["Git history becomes the audit log and the rollback mechanism.","Overlays keep differences between environments small and reviewable."]},"hint":"Client-side apply sets every field that appears in the file. Is replicas in the file?","id":"k8s.declarative-apply","introduction":"Imperative commands such as kubectl create and kubectl scale are quick, but they leave no record of what the cluster should look like, and nobody can review or reproduce them. Declarative management keeps the desired state in files, in git, and lets kubectl apply work out what to change. This lesson shows how apply decides, how it corrects drift, and how kustomize produces variants of the same manifests without copying them.","nuance":"replicas is in the manifest, so apply sets it back to 3 and prints deployment.apps/web configured. To keep a count chosen at run time, remove replicas from the file or let an HPA own it.","objective":"Manage objects from version-controlled manifests with kubectl apply, interpret created, configured and unchanged, apply and delete whole directories, and produce per-environment variants with kustomize.","question":"During an incident someone ran kubectl scale deployment web --replicas=10. The manifest in git says replicas: 3. What happens on the next kubectl apply -f of that manifest?","references":["https://kubernetes.io/docs/concepts/overview/working-with-objects/object-management/","https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/","https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/","https://kubernetes.io/docs/reference/using-api/server-side-apply/"],"reviewAnswer":"Restores the file's value and prints configured","reviewPrompt":"apply after manual replica change?","sections":[{"body":"kubectl supports three styles. Imperative commands, such as create deployment, expose, scale and set image, act directly and suit experiments and one-off fixes. Imperative object configuration, create -f and replace -f, uses files but still names the operation, so create fails when the object exists and replace overwrites the whole object. Declarative configuration, apply -f, only states what should exist: kubectl compares the file with the live object and sends the difference, creating the object when it is missing. Use apply for anything that should outlive the afternoon. Do not mix styles on the same fields: a kubectl scale or set image on an applied object lasts only until the next apply of the file, which is correct when git is the source of truth and a nasty surprise when someone fixed production by hand.","title":"Imperative commands and declarative files"},{"body":"apply prints one line per object: created when it did not exist, configured when the request changed something, and unchanged when the live object already matched the file. Client-side apply, the default, stores the file it applied in the kubectl.kubernetes.io/last-applied-configuration annotation and computes a three-way patch from that annotation, the new file and the live object. Fields in the file are set. Fields that were in the last applied file but are gone from the new one are removed. Fields that neither mentions, such as status, server defaults or a label another tool added, are left alone. That is why deleting a line from a manifest removes the field on the next apply, and why applying to an object first made with kubectl create prints a warning about the missing annotation.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: nginx:1.27\n        ports:\n        - containerPort: 80","language":"yaml","title":"What apply does and what its output means","walkthrough":"The manifest lives in shop/deployment.yaml beside shop/service.yaml. The field to watch is replicas, which the exercise changes from 2 to 3. Because replicas is in the file, every apply sets it, overriding a manual kubectl scale; if a HorizontalPodAutoscaler is to own the count, remove replicas from the file so that apply stops fighting it."},{"body":"-f accepts a directory and applies every .yaml, .yml and .json file in it in lexical order; add -R to descend into subdirectories. Order matters only for dependencies, such as a Namespace that must exist before the objects in it, which a file named 00-namespace.yaml takes care of. kubectl delete -f with the same directory deletes exactly the objects its files define, which makes cleanup precise. Keep these directories in git: a pull request is the review, history records who changed what and why, and a git revert followed by apply is a rollback. Deleting a file does not delete its object, because plain apply only knows the files you pass it, so delete the objects with delete -f before you remove the files. Never commit Secrets in plain text.","code":"kubectl apply -f shop/\nkubectl apply -f shop/ --dry-run=server\nkubectl delete -f shop/","language":"bash","title":"Directories, deletion and git","walkthrough":"--dry-run=server sends the objects through validation and admission without storing anything, the closest check to a real apply. On a real cluster, kubectl diff -f shop/ goes further and prints the changes apply would make; diff is not available in the lab. delete -f removes exactly the Deployment and Service the two files define."},{"body":"kustomize is built into kubectl as apply -k DIR, long form --kustomize DIR. The directory's kustomization.yaml lists resources, which are files or other kustomization directories, and transformations applied to all of them. namespace sets metadata.namespace everywhere; namePrefix and nameSuffix rename objects and update references to them; images replaces image names or tags without editing the Deployment; replicas overrides counts; labels adds labels, which go into selectors only when you ask for it. The usual layout is a base directory with plain manifests and an overlay per environment, such as overlays/staging, whose resources entry is ../../base. The lab follows ../ paths as well; the exercise keeps everything in one directory to stay short. A directory with a kustomization.yaml is meant for -k; pointing -f at it makes kubectl try to apply kustomization.yaml itself.","code":"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n- deployment.yaml\n- service.yaml\nnamespace: staging\nnamePrefix: staging-\nimages:\n- name: nginx\n  newTag: \"1.26\"","language":"yaml","title":"kustomize: one set of manifests, variants per environment","walkthrough":"Applied with kubectl apply --kustomize shop/, this creates a staging-web Deployment and Service in the staging namespace running nginx:1.26, while deployment.yaml and service.yaml stay untouched. The images entry matches the image name as the Deployment writes it, nginx, whatever its tag. The Service's selector stays app=web, which is fine because a Service only selects pods in its own namespace."},{"body":"Client-side apply tracks ownership crudely, in one annotation that only kubectl reads. Server-side apply, kubectl apply --server-side, moves the merge into the API server: every field records its manager in metadata.managedFields, an apply that would change a field owned by another manager fails with a conflict unless you pass --force-conflicts, and controllers, people and GitOps tools can share one object without overwriting each other. Flux applies server-side by default and Argo CD offers it as a sync option. It is the better model for new automation, but conflicts surface differently, so switch deliberately and for a whole set of manifests at once. The GopherForge lab uses client-side semantics throughout: created, configured and unchanged, with the file you apply deciding what is set.","title":"Field ownership and server-side apply"},{"body":"Apply a directory of two manifests twice, change the file, cause drift by hand and apply again to see which side wins, then delete everything the directory defines. Next, turn the same directory into a staging variant with a kustomization.yaml and apply it with kustomize. The last command deliberately points -f at the directory that now contains kustomization.yaml, a mistake that is easy to make and only half fails.","code":"kind create cluster\nmkdir shop\ncat > shop/deployment.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: nginx:1.27\n        ports:\n        - containerPort: 80\nEOF\ncat > shop/service.yaml <<'EOF'\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector:\n    app: web\n  ports:\n  - port: 80\n    targetPort: 80\nEOF\nkubectl apply -f shop/\nkubectl apply -f shop/\nsed -i 's/replicas: 2/replicas: 3/' shop/deployment.yaml\nkubectl scale deployment web --replicas=5\nkubectl apply -f shop/\nkubectl get deployment web\nkubectl delete -f shop/\ncat > shop/kustomization.yaml <<'EOF'\napiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n- deployment.yaml\n- service.yaml\nnamespace: staging\nnamePrefix: staging-\nimages:\n- name: nginx\n  newTag: \"1.26\"\nEOF\nkubectl create namespace staging\nkubectl apply --kustomize shop/\nkubectl get deploy,svc -n staging -o wide\nkubectl apply -f shop/","language":"bash","title":"Try it in the lab terminal","walkthrough":"The first apply prints deployment.apps/web created and service/web created, the second unchanged for both. With replicas: 3 in the file and 5 set by hand, the next apply prints deployment.apps/web configured and service/web unchanged, and get deployment shows READY 1/3 while pods start: the file wins. delete -f removes both objects. apply --kustomize creates staging-web objects in staging, and -o wide shows nginx:1.26 although deployment.yaml still says 1.27. The final apply -f first creates the unprefixed web objects in default, then fails with error: resource mapping not found ... no matches for kind \"Kustomization\", which leaves you with an extra copy to delete."}],"takeaway":"Keep desired state in files under git and let kubectl apply compute the changes; created, configured and unchanged tell you what happened. Use kustomize for per-environment differences instead of copies, and remember that the file overrides manual changes on the next apply.","title":"Declarative configuration with kubectl apply, manifest directories and kustomize","unitID":"k8s-foundations","wrongAnswers":["Keeps 10, because live changes take precedence over files","Fails with a conflict until you pass --force-conflicts"]},{"conceptTag":"k8s.deployments-replicasets","designGuide":{"cautions":["Edits to a ReplicaSet are reverted by its Deployment.","Overlapping selectors make controllers fight over Pods."],"cost":"One Deployment manifest per stateless component, kept in version control with stable selector labels.","family":"kubernetes","flow":["Write the Deployment manifest","Controller creates a ReplicaSet","ReplicaSet creates the Pods","Scale and heal through it"],"ratings":[],"strengths":["Deleted or lost Pods are replaced automatically, on any node.","Scaling is one field change that never restarts running Pods."]},"hint":"Ask whether replicas lives inside spec.template, and what the hash in a ReplicaSet's name is computed from.","id":"k8s.deployments-replicasets","introduction":"A Pod you create by hand is gone for good when someone deletes it or its node dies. A Deployment declares how many identical Pods you want and what they look like; a ReplicaSet keeps that many running, and the Deployment manages ReplicaSets so that the template can change safely. Knowing which object owns which is what lets you read kubectl output and fix a stuck workload.","nuance":"replicas is not part of the Pod template, so pod-template-hash stays the same. The Deployment scales its current ReplicaSet to 6, which creates three Pods; existing Pods are untouched and no revision is added.","objective":"Create a Deployment, trace its ReplicaSet and Pods through labels and owner references, read the READY, UP-TO-DATE and AVAILABLE columns, and watch the controllers scale and replace Pods.","question":"You change only replicas from 3 to 6 in a Deployment manifest and apply it. What do the controllers do?","references":["https://kubernetes.io/docs/concepts/workloads/controllers/deployment/","https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/","https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/","https://kubernetes.io/docs/concepts/architecture/controller/"],"reviewAnswer":"Scales the current ReplicaSet; no new revision","reviewPrompt":"Changing only replicas does?","sections":[{"body":"The Deployment stores desired state: a replica count, a label selector and a Pod template. The Deployment controller, running in kube-controller-manager, creates one ReplicaSet per distinct template and decides how many replicas each should have. The ReplicaSet controller then creates or deletes Pods until the number of live Pods matching its selector equals its replicas field. Every Pod carries an ownerReference to its ReplicaSet, and every ReplicaSet one to its Deployment; the garbage collector follows these links when you delete the Deployment. Controllers are level-triggered: they compare desired with observed state on every change, so a missed event is corrected on the next pass rather than lost. You almost never create ReplicaSets yourself; you change the Deployment and let the chain converge.","title":"Three objects, two controllers"},{"body":"spec.selector tells the Deployment which Pods are its own, and it must match spec.template.metadata.labels or the API server rejects the object. In apps/v1 the selector is immutable after creation, so choose stable labels such as app: web rather than anything containing a version. replicas defaults to 1. Everything under template is the Pod that will be stamped out; containerPort is informational, but listing it documents the contract that Services and probes rely on. Keep this file in version control and change it there, so that the cluster is always something you can recreate from Git.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - containerPort: 8080","language":"yaml","title":"A Deployment manifest","walkthrough":"Three label sets appear. The label on the Deployment itself only lets you select Deployments, for example kubectl get deploy -l app=web. The selector app: web decides which Pods the Deployment claims, and the template label app: web is stamped on every Pod its ReplicaSet creates. If the last two disagree, the API server refuses the Deployment because the selector does not match the template labels."},{"body":"The Deployment controller hashes the Pod template and adds the result as the pod-template-hash label to the ReplicaSet's selector, to its template and therefore to every Pod it creates; the ReplicaSet is named web-<hash>. Two ReplicaSets of the same Deployment therefore never select each other's Pods, although both also match app=web. Any change under template, such as the image, an environment variable or a template annotation, produces a new hash and a new ReplicaSet: that is a rollout. replicas is not part of the template, which is why scaling never starts a rollout. Never set pod-template-hash yourself, and never give two controllers overlapping selectors: the documentation warns that such controllers fight with each other and do not behave correctly.","title":"pod-template-hash ties a ReplicaSet to one template"},{"body":"READY is the number of ready Pods over the desired replica count. UP-TO-DATE counts Pods created from the current template, so it lags during a rollout. AVAILABLE counts Pods that have stayed ready for at least minReadySeconds, zero by default; it is what the Available condition and rollout decisions use. For a ReplicaSet, DESIRED is its replicas field, CURRENT the Pods it currently owns and READY the ready ones among them. A Deployment showing 3/3 with UP-TO-DATE 1 is in the middle of a rollout; 2/3 with UP-TO-DATE 3 means a Pod is missing or not ready and the ReplicaSet is dealing with it. kubectl describe deploy adds the Conditions and the ScalingReplicaSet events that record what the controller decided and when.","title":"Reading kubectl get deploy and get rs"},{"body":"kubectl scale sets replicas on the Deployment, which passes the number to its current ReplicaSet. When a Pod disappears because it was deleted, evicted or lost with its node, the ReplicaSet sees fewer matching Pods than desired and creates a replacement with a new name, a new UID and usually a new IP; nothing is restarted in place. That is why clients reach Pods through a Service, never by Pod IP. Changing a ReplicaSet directly does not stick: the Deployment controller owns its replicas field and puts it back. When scaling down, the ReplicaSet removes unscheduled and not-ready Pods first, then prefers Pods on nodes that run more replicas and newer Pods; the controller.kubernetes.io/pod-deletion-cost annotation lets you influence the choice.","title":"Scaling and self-healing"},{"body":"Create a fresh single-node cluster, apply the manifest and follow the chain from Deployment to ReplicaSet to Pods through labels and owner references. Then delete one Pod, scale the Deployment to five replicas, and try to scale its ReplicaSet behind the Deployment's back. The $(...) substitutions pick the first Pod or ReplicaSet name, so you never copy random suffixes by hand. Watch the AGE column: replacements are new Pods, not restarted ones.","code":"kind create cluster\ncat > web.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - containerPort: 8080\nEOF\nkubectl apply -f web.yaml\nkubectl get deploy web\nkubectl rollout status deploy/web\nkubectl get deploy,rs,pods --show-labels\nkubectl get pods -o custom-columns=NAME:.metadata.name,OWNER:.metadata.ownerReferences[0].name\nkubectl delete $(kubectl get pods -l app=web -o name | head -n 1)\nkubectl get deploy web\nkubectl get pods\nkubectl scale deploy web --replicas=5\nkubectl rollout status deploy/web\nkubectl scale $(kubectl get rs -l app=web -o name) --replicas=1\nkubectl get rs\nkubectl describe deploy web","language":"bash","title":"Try it in the lab terminal","walkthrough":"Right after apply, get deploy shows web 0/3 3 0: three Pods exist from the current template, none ready yet. After the rollout, ReplicaSet web-<hash> and its three Pods all carry app=web,pod-template-hash=<hash>, and the OWNER column names that ReplicaSet. Deleting web-<hash>-<id> drops the Deployment to 2/3 3 2 while a replacement with a new suffix is ContainerCreating. Scaling the ReplicaSet to 1 prints scaled, yet get rs still shows DESIRED 5, and the last event in describe reads Scaled up replica set web-<hash> from 1 to 5. On a real cluster a few Pods may be replaced during that race."}],"takeaway":"A Deployment owns one ReplicaSet per Pod template, and each ReplicaSet owns Pods that it replaces whenever they disappear. Change and scale the Deployment, never its ReplicaSets, and read READY, UP-TO-DATE and AVAILABLE to tell a rollout from a missing Pod.","title":"Deployments, ReplicaSets and Pods: the controller chain behind every replica","unitID":"k8s-workloads","wrongAnswers":["A new ReplicaSet rolls out and replaces all Pods","Every Pod restarts to pick up the new replica count"]},{"conceptTag":"k8s.rolling-updates","designGuide":{"cautions":["Old and new versions serve together and must be compatible.","Nothing rolls back automatically when the deadline passes."],"cost":"Spare capacity for surge Pods, backward-compatible releases and a pipeline that waits on rollout status.","family":"kubernetes","flow":["Edit image and change-cause","kubectl apply","Gate on rollout status","Undo or fix forward"],"ratings":[],"strengths":["Capacity bounds are explicit and predictable at every step.","A release that never gets ready stalls instead of replacing healthy Pods."]},"hint":"Percentages become Pod counts: surge rounds up, unavailability rounds down. Add one to replicas and subtract the other.","id":"k8s.rolling-updates","introduction":"Changing a Deployment's Pod template starts a rollout: a new ReplicaSet grows while the old one shrinks. How fast that happens, how much spare capacity it needs and how much serving capacity it may lose are all settings. Just as important is what happens when the new version never becomes ready: Kubernetes stops, keeps the old Pods serving, and leaves the decision to roll back to you.","nuance":"25% of 10 is 2.5. maxSurge rounds up to 3, so at most 13 Pods exist; maxUnavailable rounds down to 2, so at least 8 Pods stay available at every step of the rollout.","objective":"Configure a Deployment's update strategy, predict how many Pods exist during a rollout, follow and steer it with kubectl rollout, and recover from a release that never becomes ready.","question":"A Deployment with 10 replicas uses the default 25% maxSurge and maxUnavailable. Which bounds does the controller keep during a rollout?","references":["https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment","https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#failed-deployment","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_rollout/","https://kubernetes.io/docs/tutorials/kubernetes-basics/update/update-intro/"],"reviewAnswer":"At most 13 Pods, at least 8 available","reviewPrompt":"10 replicas, 25%/25% bounds?","sections":[{"body":"RollingUpdate, the default, replaces Pods gradually: the Deployment controller scales the new ReplicaSet up and the old one down in steps, and only counts new Pods once they are available, meaning ready for minReadySeconds. Old and new versions serve side by side for a while, so every release must be compatible with the previous one, including database schema, API responses and session formats. Recreate deletes every old Pod first and only then creates new ones. It causes downtime, but it is the right choice when two versions must never run at once, for example a single writer holding a ReadWriteOnce volume, or a migration the old code cannot tolerate.","title":"RollingUpdate and Recreate"},{"body":"maxSurge is how many Pods may exist above replicas during the update; maxUnavailable is how many of the desired replicas may be unavailable. Both accept a number or a percentage of replicas and both default to 25%. Percentages round up for surge and down for unavailability. With replicas: 10 that is a surge of 3 and an unavailability of 2: at most 13 Pods exist and at least 8 are available at every moment. With replicas: 4 both become 1. maxSurge: 1 with maxUnavailable: 0 replaces one Pod at a time without ever dropping below full capacity, at the price of room for one extra Pod; maxSurge: 0 with maxUnavailable: 1 needs no spare room but runs one Pod short. Both cannot be zero.","code":"spec:\n  replicas: 10\n  minReadySeconds: 5\n  progressDeadlineSeconds: 600\n  revisionHistoryLimit: 10\n  strategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxSurge: 25%        # ceil(10 * 0.25) = 3 extra Pods allowed\n      maxUnavailable: 25%  # floor(10 * 0.25) = 2 Pods may be unavailable","language":"yaml","title":"maxSurge and maxUnavailable arithmetic","walkthrough":"During a rollout of this Deployment the controller keeps between 8 and 13 Pods, at least 8 of them available. minReadySeconds makes a new Pod count as available only after it has stayed ready for 5 seconds, which catches versions that crash shortly after starting. The last two fields show their defaults: ten minutes without progress marks the rollout as failed, and ten old ReplicaSets are kept for rollbacks."},{"body":"rollout status waits until the rollout finishes and exits non-zero if it fails or times out, which makes it a natural deployment gate in CI. rollout history lists revisions, one per ReplicaSet, and --revision=N shows one revision's template. rollout undo copies the previous revision's template, or the one named with --to-revision, back into the Deployment; the old ReplicaSet scales up again and receives a new revision number, so numbers only grow. rollout pause stops the controller from acting on template changes, so you can change image, resources and environment and release them as one rollout with rollout resume. rollout restart sets a kubectl.kubernetes.io/restartedAt annotation in the template, which replaces every Pod through a normal rolling update without changing the image.","code":"kubectl rollout status deploy/web --timeout=5m\nkubectl rollout history deploy/web\nkubectl rollout history deploy/web --revision=2\nkubectl rollout undo deploy/web --to-revision=1\nkubectl rollout pause deploy/web\nkubectl set image deploy/web web=gopherforge/web:v2\nkubectl set resources deploy/web -c web --requests=cpu=100m,memory=64Mi\nkubectl rollout resume deploy/web\nkubectl rollout restart deploy/web","language":"bash","title":"Steering a rollout with kubectl rollout","walkthrough":"The pause, set image, set resources and resume sequence produces a single new ReplicaSet that carries both changes, instead of two rollouts back to back. undo --to-revision=1 is how you return to a known-good version when the previous one is bad as well. Every command here only edits the Deployment object; the controller does the actual work."},{"body":"The CHANGE-CAUSE column of rollout history comes from the kubernetes.io/change-cause annotation on each ReplicaSet, which the controller copies from the Deployment. The --record flag that used to set it is deprecated, so set the annotation yourself, ideally in the same manifest change as the new image so that one apply carries both. progressDeadlineSeconds, 600 by default, is how long a rollout may go without progress, such as a new Pod becoming available. When it passes, the Progressing condition turns False with reason ProgressDeadlineExceeded and rollout status fails. Kubernetes does not roll back by itself: the old ReplicaSet keeps serving within the maxUnavailable budget while you choose between undo and a fix forward. A paused rollout is not checked against the deadline.","title":"Change-cause and the progress deadline"},{"body":"The manifest uses maxSurge: 1 and maxUnavailable: 0, a short progressDeadlineSeconds of 60 so the failure shows quickly, and a readiness probe on /readyz, explained in the probes lesson. The change-cause annotation lives in the manifest and names the image, so one sed edit changes both and a single apply records them together. gopherforge/web:v2-broken starts but never passes its readiness probe.","code":"kind create cluster\ncat > web.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  annotations:\n    kubernetes.io/change-cause: \"deploy gopherforge/web:v1\"\nspec:\n  replicas: 4\n  progressDeadlineSeconds: 60\n  strategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxSurge: 1\n      maxUnavailable: 0\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - containerPort: 8080\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: 8080\n          periodSeconds: 2\nEOF\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\nkubectl expose deploy web --port 80 --target-port 8080\nsed -i 's/web:v1/web:v2/g' web.yaml\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\nkubectl rollout history deploy/web\nsed -i 's/web:v2/web:v2-broken/g' web.yaml\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\nkubectl get rs\ntraffic run svc/web --rps 50 --duration 5s\nkubectl rollout undo deploy/web\nkubectl rollout history deploy/web","language":"bash","title":"Try it in the lab terminal","walkthrough":"The v2 rollout reports 1, 2 and 3 out of 4 new replicas updated, then 1 old replicas are pending termination, and history lists revisions 1 and 2 with their causes. The v2-broken rollout stops at 1 out of 4 and ends with error: deployment \"web\" exceeded its progress deadline. get rs shows the new ReplicaSet at 1 desired, 0 ready, beside the v2 ReplicaSet with 4 ready, and traffic run reports 100.0% ok from those four Pods. After undo, history lists 1, 3 and 4: revision 2 became 4. web.yaml still says v2-broken, so fix it before the next apply."}],"takeaway":"A rolling update is bounded by maxSurge and maxUnavailable and only advances as new Pods become available, so a release that never gets ready stalls while the old Pods keep serving. Record a change-cause with every change, gate deployments on rollout status, and roll back deliberately with rollout undo.","title":"Rolling updates: maxSurge, maxUnavailable, rollout history, undo and stalled rollouts","unitID":"k8s-workloads","wrongAnswers":["At most 12 Pods, at least 7 available","At most 13 Pods, at least 7 available"]},{"conceptTag":"k8s.probes","designGuide":{"cautions":["Liveness that checks dependencies causes restart storms.","Tight timeouts restart healthy Pods under load."],"cost":"Two small HTTP handlers in every service and probe settings tuned to its real start-up and response times.","family":"kubernetes","flow":["Startup: allow a slow boot","Readiness: gate traffic","Liveness: restart if stuck","Clear ready on SIGTERM"],"ratings":[],"strengths":["Rollouts and Services only use Pods that are actually ready.","A hung process is restarted without anyone being paged."]},"hint":"Only some probe types ever restart a container. Which ones, and what does the other one change instead?","id":"k8s.probes","introduction":"Kubernetes knows only that a container's process is running. Whether the application can serve traffic yet, and whether it is still making progress, it learns from probes that the kubelet runs on the node. Each probe answers a different question and triggers a different action, and confusing them is one of the most common causes of self-inflicted downtime.","nuance":"A failing readiness probe marks the Pod not ready, so it is removed from the EndpointSlices of its Services and stops receiving traffic. Only liveness and startup probe failures make the kubelet restart a container.","objective":"Choose the right probe for each question, configure its timing, implement /readyz and /healthz handlers in a Go service, and avoid the probe settings that cause outages.","question":"A Go service's readiness probe starts failing while its liveness probe keeps passing. What does Kubernetes do?","references":["https://kubernetes.io/docs/concepts/configuration/liveness-readiness-startup-probes/","https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/","https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes"],"reviewAnswer":"The Pod leaves Service endpoints; nothing restarts","reviewPrompt":"A readiness probe fails: effect?","sections":[{"body":"A readiness probe asks whether the container should receive traffic now. While it fails, the Pod is not ready and is removed from the EndpointSlices of every Service that selects it, but nothing is restarted; it runs for the container's whole life, so a Pod can leave and rejoin rotation. Readiness also drives rollouts, because a new Pod counts as available only once it is ready. A liveness probe asks whether the container is stuck beyond recovery: after failureThreshold consecutive failures the kubelet kills it and restarts it according to restartPolicy. A startup probe protects slow starters: until it succeeds, liveness and readiness probes are not run, and if it does not succeed within its budget the container is killed and restarted.","title":"Three probes, three consequences"},{"body":"A probe is an httpGet, where any status from 200 to 399 passes, a tcpSocket connection, an exec command that must exit 0, or a gRPC health check. The kubelet runs it from the node against the Pod IP. periodSeconds (default 10) sets the interval, timeoutSeconds (default 1) the deadline for one attempt, and failureThreshold (default 3) and successThreshold (default 1, always 1 for liveness and startup) how many consecutive results flip the state. Worst-case detection is roughly periodSeconds times failureThreshold, so the liveness probe below restarts a hung container after about 30 seconds, and the startup probe allows 5 x 24 = 120 seconds to start. The GopherForge lab terminal simulates this too: while a startupProbe is failing, liveness and readiness wait, and a startup probe that never passes gets the container restarted.","code":"containers:\n- name: web\n  image: gopherforge/web:v2\n  ports:\n  - name: http\n    containerPort: 8080\n  startupProbe:\n    httpGet:\n      path: /healthz\n      port: http\n    periodSeconds: 5\n    failureThreshold: 24     # up to 120 s to start\n  readinessProbe:\n    httpGet:\n      path: /readyz\n      port: http\n    periodSeconds: 5\n    failureThreshold: 2\n  livenessProbe:\n    httpGet:\n      path: /healthz\n      port: http\n    periodSeconds: 10\n    timeoutSeconds: 2\n    failureThreshold: 3","language":"yaml","title":"Probe mechanics and timing","walkthrough":"The startup probe gives the process up to two minutes to answer /healthz before liveness checks begin. Readiness uses its own endpoint and reacts within about ten seconds, taking the Pod out of rotation without a restart. Liveness tolerates two-second responses and three misses in a row before restarting. With a startup probe in place, initialDelaySeconds is rarely needed on the other two."},{"body":"Liveness should answer one question only: can this process still make progress? Check state local to the process, such as a heartbeat that the main worker loop updates, and never call the database or another service from it. Readiness can be stricter: return 503 until caches are warm and configuration is loaded, and again as soon as shutdown begins, so the Pod leaves the endpoints while in-flight requests finish. Keep both handlers cheap and free of locks that request handlers hold, or a busy server fails its own probes.","code":"var (\n\tready    atomic.Bool  // set after warm-up, cleared on SIGTERM\n\tlastBeat atomic.Int64 // unix seconds, updated by the worker loop\n)\n\nfunc healthz(w http.ResponseWriter, r *http.Request) {\n\tif time.Since(time.Unix(lastBeat.Load(), 0)) > 30*time.Second {\n\t\thttp.Error(w, \"worker loop stalled\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc readyz(w http.ResponseWriter, r *http.Request) {\n\tif !ready.Load() {\n\t\thttp.Error(w, \"not ready\", http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}","language":"go","title":"Designing /healthz and /readyz in Go","walkthrough":"healthz fails only when the worker loop has not reported for 30 seconds, a condition a restart can actually fix. readyz is under the application's control: call ready.Store(true) after warm-up, and ready.Store(false) first thing in the SIGTERM handler, before http.Server.Shutdown. The atomic values keep both handlers lock-free, so they still answer when request handlers are blocked."},{"body":"A liveness probe that checks a dependency turns a database outage into a restart storm: every replica restarts at once, caches go cold and recovery takes longer. A readiness probe that checks a shared dependency has a similar trap, since all Pods leave the Service together and clients get connection errors instead of a clear 503; check shared dependencies only when routing to another Pod could help. Aggressive thresholds, such as a one-second timeout with failureThreshold: 1, restart healthy containers during garbage-collection pauses or CPU throttling and push more load onto the survivors. A liveness probe on a slow starter without a startup probe kills it before it ever serves. And without any readiness probe, a container receives traffic the moment its process starts, before it listens.","title":"Probe mistakes that cause outages"},{"body":"gopherforge/web:slow needs 25 seconds before it listens. First deploy it without probes and send traffic; then apply a manifest with a readiness probe, which replaces the Pods through a rolling update while traffic keeps flowing. Finally, gopherforge/web:deadlock stops answering 30 seconds after it starts, and a liveness probe with a 5-second period and a threshold of 3 restarts it. cluster tick advances virtual time so you do not have to wait.","code":"kind create cluster\nkubectl create deployment web --image=gopherforge/web:slow --replicas=2 --port=8080\nkubectl expose deploy web --port 80 --target-port 8080\nkubectl rollout status deploy/web\ntraffic run svc/web --rps 20 --duration 25s\ncat > web.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:slow\n        ports:\n        - containerPort: 8080\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: 8080\n          periodSeconds: 5\nEOF\nkubectl apply -f web.yaml\ntraffic run svc/web --rps 20 --duration 60s\nkubectl get pods\ncat > stuck.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: stuck\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: stuck\n  template:\n    metadata:\n      labels:\n        app: stuck\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:deadlock\n        ports:\n        - containerPort: 8080\n        livenessProbe:\n          httpGet:\n            path: /healthz\n            port: 8080\n          periodSeconds: 5\n          failureThreshold: 3\nEOF\nkubectl apply -f stuck.yaml\ncluster tick 60s\nkubectl get pods -l app=stuck\nkubectl describe pod -l app=stuck","language":"bash","title":"Try it in the lab terminal","walkthrough":"Without a probe, rollout status succeeds within seconds and both Pods count as ready, yet traffic run reports 13.0% ok with 435 requests refused: the Service sent traffic to Pods that were not listening yet. During the probed rollout, READY PODS reads 2/3 and the run ends 100.0% ok, because each new Pod joins the endpoints only once /readyz passes while the old Pods keep serving. The stuck Pod shows RESTARTS 1 and Last State: Terminated, and its events list Unhealthy warnings for the liveness probe followed by Killing: Container web failed liveness probe, will be restarted."}],"takeaway":"Readiness decides whether a Pod gets traffic, liveness whether its container is restarted, and startup how long it may take to begin. Give every server a readiness probe, keep liveness local and lenient, and never let a dependency outage restart your Pods.","title":"Readiness, liveness and startup probes: routing traffic and restarting stuck containers","unitID":"k8s-workloads","wrongAnswers":["The kubelet restarts the container after three failures","The Pod is evicted and rescheduled on another node"]},{"conceptTag":"k8s.resources-qos","designGuide":{"cautions":["CPU limits throttle latency even at low average usage.","A memory limit below the working set means an OOMKill loop."],"cost":"Load tests and monitoring to learn real usage, and a periodic review of every workload's requests and limits.","family":"kubernetes","flow":["Measure usage under load","Requests from typical usage","Memory limit near the peak","Watch top and OOMKilled"],"ratings":[],"strengths":["The scheduler never overcommits what Pods request.","Guaranteed Pods are the last to be evicted under pressure."]},"hint":"CPU and memory behave differently at their limits. Which one can be taken away gradually, and which one cannot?","id":"k8s.resources-qos","introduction":"Without resource settings, the scheduler places Pods as if they cost nothing and the node discovers the truth under load. Requests tell the scheduler what to reserve; limits tell the kernel where to stop a container. CPU and memory behave very differently at that limit: one slows down, the other is killed.","nuance":"Memory cannot be throttled, so the kernel OOM killer ends a container that exceeds its memory limit with SIGKILL: exit code 137. A CPU limit only throttles, and an eviction deletes the Pod instead of restarting it.","objective":"Set requests and limits deliberately, predict how the scheduler and the kernel use them, recognise CPU throttling and OOMKilled containers, and know which QoS class each workload gets.","question":"A Pod restarts repeatedly and describe shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137. What happened?","references":["https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/","https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/","https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/","https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/"],"reviewAnswer":"The container exceeded its memory limit and was killed","reviewPrompt":"OOMKilled with exit code 137?","sections":[{"body":"A request is what the scheduler reserves: a Pod fits on a node only if the requests already placed there plus its own stay within the node's allocatable capacity. Actual usage plays no part in that decision. At runtime the CPU request also sets the container's share of CPU when the node is busy. A limit is enforced by the Linux kernel through cgroups and is never used for scheduling. CPU is measured in cores, so 250m is a quarter of a core; memory in bytes, with Mi and Gi as binary units, so 128Mi is not the same as 128M. If you set only a limit, the request defaults to the same value. Requests and limits are set per container, and a Pod's request is essentially the sum of its containers'.","title":"Requests reserve, limits cap"},{"body":"Kubernetes derives a quality-of-service class from the resources of every container in the Pod. Guaranteed requires a CPU and a memory limit on every container, with requests equal to limits. Burstable means at least one request or limit is set but the Pod does not qualify as Guaranteed. BestEffort means no requests or limits at all. You cannot choose the class directly; kubectl describe pod and status.qosClass show the result.","code":"apiVersion: v1\nkind: Pod\nmetadata:\n  name: api\nspec:\n  containers:\n  - name: api\n    image: gopherforge/web:v2\n    env:\n    - name: GOMEMLIMIT\n      value: \"230MiB\"\n    resources:\n      requests:\n        cpu: 500m\n        memory: 256Mi\n      limits:\n        cpu: 500m\n        memory: 256Mi","language":"yaml","title":"Three QoS classes","walkthrough":"Requests equal limits for both resources, so the Pod is Guaranteed and the scheduler reserves exactly what the kernel will allow. GOMEMLIMIT asks the Go garbage collector to work harder as the heap approaches about 90 percent of the limit instead of growing into an OOMKill. Lowering either request or removing the CPU limit would make the Pod Burstable."},{"body":"CPU is compressible. A container that reaches its CPU limit is throttled by the CFS quota: it may use its quota within each 100 ms period and then waits for the next one, so a request needing 30 ms of CPU can take far longer under load even though average usage looks modest. Memory is not compressible. When a container's memory exceeds its limit, the kernel's OOM killer ends the process; the kubelet reports Last State: Terminated, Reason: OOMKilled, Exit Code: 137, which is 128 plus SIGKILL's 9, and restarts it with back-off. Since Go 1.25 the runtime derives GOMAXPROCS from the cgroup CPU limit; set GOMEMLIMIT a little below the memory limit so that the garbage collector gets a chance before the kernel does.","title":"CPU is throttled, memory is killed"},{"body":"When a node runs short of memory or disk, the kubelet evicts Pods before the kernel has to kill processes at random. It first considers Pods whose usage exceeds their requests, ordered by Pod priority and then by how far above the request they are. BestEffort Pods request nothing, so any usage counts as excess and they go first; Burstable Pods using more than they asked for follow; Guaranteed Pods and Burstable Pods within their requests are evicted last. The QoS class also sets the oom_score_adj the kernel uses if it must act before the kubelet. Evicted Pods are not restarted in place: their controller creates replacements, possibly on another node.","title":"QoS classes and eviction order"},{"body":"kubectl top pods and top nodes read the Metrics API that metrics-server provides: current usage sampled about every 15 seconds, with no history. Use them to spot a Pod creeping towards its memory limit, and use Prometheus or a similar system for percentiles over days. A sound starting point is a CPU request near typical usage, a memory request near the peak working set, a memory limit equal to or a little above the memory request, and either no CPU limit or a generous one for latency-sensitive services. Revisit the numbers after load tests and significant releases: requests that are too high waste nodes, requests that are too low invite contention and eviction.","title":"kubectl top and right-sizing"},{"body":"Two Pods show the two failure modes. leak requests 64Mi and is limited to 128Mi while its memory grows by several MiB per second; cluster tick advances virtual time so you can watch it approach the limit. hog asks for six CPUs on a lab node with four allocatable, so no amount of waiting will schedule it. describe pod and describe node show where each decision is recorded, and the last command prints the QoS class of both Pods.","code":"kind create cluster\ncat > leak.yaml <<'EOF'\napiVersion: v1\nkind: Pod\nmetadata:\n  name: leak\nspec:\n  containers:\n  - name: web\n    image: gopherforge/web:leak\n    ports:\n    - containerPort: 8080\n    resources:\n      requests:\n        cpu: 100m\n        memory: 64Mi\n      limits:\n        memory: 128Mi\nEOF\nkubectl apply -f leak.yaml\ncluster tick 12s\nkubectl top pod leak\ncluster tick 14s\nkubectl get pod leak\nkubectl describe pod leak\ncat > hog.yaml <<'EOF'\napiVersion: v1\nkind: Pod\nmetadata:\n  name: hog\nspec:\n  containers:\n  - name: app\n    image: gopherforge/web:v1\n    resources:\n      requests:\n        cpu: \"6\"\n        memory: 256Mi\n      limits:\n        cpu: \"6\"\n        memory: 256Mi\nEOF\nkubectl apply -f hog.yaml\nkubectl get pod hog\nkubectl describe pod hog\nkubectl describe node kind-control-plane\nkubectl get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass","language":"bash","title":"Try it in the lab terminal","walkthrough":"top pod shows leak at 60Mi a few seconds after it starts. Soon after it passes 128Mi, get pod reports CrashLoopBackOff, or OOMKilled if you are quick, with RESTARTS 1, and describe shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137 and QoS Class: Burstable. hog stays Pending with a FailedScheduling warning: 0/1 nodes are available: 1 Insufficient cpu. The node lists 4000m allocatable CPU, and its Allocated resources section counts only the requests of Pods already placed there. The last command prints Guaranteed for hog and Burstable for leak."}],"takeaway":"Requests decide placement and CPU shares under contention; limits are enforced by the kernel, which throttles CPU and kills on memory. Size memory from measured peaks, treat OOMKilled with exit code 137 as a sizing or leak problem, and know which QoS class each workload gets.","title":"Resource requests and limits, CPU throttling, OOMKills and QoS classes","unitID":"k8s-workloads","wrongAnswers":["The container exceeded its CPU limit and was killed","The kubelet evicted the Pod under node disk pressure"]},{"conceptTag":"k8s.scheduling","designGuide":{"cautions":["A hard constraint with one matching node fails on drain.","Tolerations without selectors do not dedicate nodes."],"cost":"A labelling and tainting convention for nodes, kept consistent with the constraints written into every workload.","family":"kubernetes","flow":["Label and taint nodes","Select or prefer with affinity","Tolerate the taint","Spread across zones and nodes"],"ratings":[],"strengths":["Placement rules live in manifests, not in runbooks.","FailedScheduling explains why every node was rejected."]},"hint":"A taint and a toleration together decide where a Pod may go. What decides where it should go?","id":"k8s.scheduling","introduction":"Every new Pod starts without a node. The scheduler picks one, and if it cannot, the Pod waits in Pending with an event that explains why, node by node. Most scheduling problems are constraints you wrote yourself: a selector no node matches, a taint nobody tolerates, or requests that do not fit. Knowing the vocabulary turns that event into a one-line diagnosis.","nuance":"A toleration only removes the taint as an obstacle; ordinary nodes stay feasible and may score higher. Dedicated nodes need a taint to keep others off plus a nodeSelector or required affinity to keep the workload on.","objective":"Explain how the scheduler filters and scores nodes, steer Pods with nodeSelector and affinity, keep them off nodes with taints, and read FailedScheduling messages after a cordon, a drain or a bad constraint.","question":"You taint three GPU nodes dedicated=gpu:NoSchedule and give your training Pods a matching toleration, yet some still land on ordinary nodes. Why?","references":["https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/","https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/","https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/","https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/"],"reviewAnswer":"No: it permits; a selector or affinity attracts","reviewPrompt":"Does a toleration attract Pods?","sections":[{"body":"kube-scheduler watches for Pods without spec.nodeName. For each, filter plugins remove nodes that cannot run it: not enough allocatable CPU or memory for its requests, a node selector or required affinity that does not match, an untolerated taint, a host port in use, a volume bound elsewhere, or a hard topology spread constraint. Score plugins then rank the remaining feasible nodes, preferring balanced resource use, preferred affinities, images already present and even spreading, and the Pod is bound to the best node. If no node passes the filters, the Pod stays Pending, a FailedScheduling event records the reasons, and the scheduler retries whenever the cluster changes; with Pod priorities it may also preempt lower-priority Pods to make room.","title":"Filter, score, bind"},{"body":"nodeSelector is the simple form: every listed label must be present on the node with exactly that value. Node affinity is the expressive form. requiredDuringSchedulingIgnoredDuringExecution is a hard filter with operators such as In, NotIn, Exists and Gt; preferredDuringSchedulingIgnoredDuringExecution adds weighted preferences to the score. IgnoredDuringExecution means a running Pod stays put if the node's labels change later. Prefer well-known labels such as kubernetes.io/arch, topology.kubernetes.io/zone and node.kubernetes.io/instance-type where they exist. In the GopherForge lab terminal, nodeSelector, taints and tolerations are enforced; affinity and topologySpreadConstraints are accepted but its scheduler does not use them.","code":"spec:\n  nodeSelector:\n    kubernetes.io/arch: arm64\n  affinity:\n    nodeAffinity:\n      requiredDuringSchedulingIgnoredDuringExecution:\n        nodeSelectorTerms:\n        - matchExpressions:\n          - key: disk\n            operator: In\n            values: [\"ssd\", \"nvme\"]\n      preferredDuringSchedulingIgnoredDuringExecution:\n      - weight: 50\n        preference:\n          matchExpressions:\n          - key: topology.kubernetes.io/zone\n            operator: In\n            values: [\"zone-a\"]","language":"yaml","title":"Attracting Pods: nodeSelector and node affinity","walkthrough":"Both hard conditions must hold: the node runs arm64 and has disk set to ssd or nvme. Among the nodes that qualify, those in zone-a get extra score, but the Pod still runs elsewhere when zone-a is full. Several nodeSelectorTerms would be ORed, while the expressions inside one term are ANDed."},{"body":"A taint on a node repels every Pod that does not tolerate it. NoSchedule blocks new Pods, PreferNoSchedule only lowers the score, and NoExecute also evicts running Pods that do not tolerate it, optionally after tolerationSeconds. A toleration permits scheduling onto a tainted node; it does not attract the Pod there. To dedicate nodes to a workload, combine both: a taint keeps everyone else off, and a selector or affinity keeps the workload on. Multi-node kind clusters taint the control plane with node-role.kubernetes.io/control-plane:NoSchedule, and when a node fails the node lifecycle controller adds not-ready or unreachable NoExecute taints, which Pods tolerate for 300 seconds by default before they are evicted.","code":"kubectl taint nodes kind-worker2 dedicated=batch:NoSchedule\nkubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].key\nkubectl taint nodes kind-worker2 dedicated=batch:NoSchedule-","language":"bash","title":"Repelling Pods: taints and tolerations","walkthrough":"A taint is written key=value:effect. The custom-columns query lists the taint keys of every node, which is quicker than describing each one. A trailing minus removes the taint again, and kubectl taint nodes kind-worker2 dedicated- would remove every taint with that key."},{"body":"Three replicas on one node survive nothing that takes that node down. topologySpreadConstraints state the intent directly: with topologyKey: topology.kubernetes.io/zone and maxSkew: 1, the number of matching Pods in any two zones may differ by at most one. whenUnsatisfiable: DoNotSchedule makes the rule a filter, ScheduleAnyway a scoring preference. The scheduler also applies cluster-wide default constraints that softly spread Pods of one workload across nodes and zones, which is why a Deployment usually lands on several nodes without configuration. Pod anti-affinity can express never two on one node as well, but costs more to evaluate in large clusters. Pair spreading with a PodDisruptionBudget so that voluntary disruptions cannot take all replicas at once. The lab terminal accepts these constraints but does not enforce them.","code":"spec:\n  topologySpreadConstraints:\n  - maxSkew: 1\n    topologyKey: topology.kubernetes.io/zone\n    whenUnsatisfiable: DoNotSchedule\n    labelSelector:\n      matchLabels:\n        app: web\n  - maxSkew: 1\n    topologyKey: kubernetes.io/hostname\n    whenUnsatisfiable: ScheduleAnyway\n    labelSelector:\n      matchLabels:\n        app: web","language":"yaml","title":"Spreading replicas across failure domains","walkthrough":"The first constraint is hard: zones may differ by at most one web Pod, so a new replica goes to the emptier zone or waits. The second is soft: within that rule, the scheduler prefers nodes running fewer web Pods. labelSelector decides which Pods are counted, normally the workload's own."},{"body":"kubectl cordon marks a node unschedulable while its Pods keep running. kubectl drain cordons and then evicts Pods through the Eviction API, which honours PodDisruptionBudgets, so the node can be patched or removed; --ignore-daemonsets is needed because the DaemonSet controller would recreate its Pods there anyway. Controllers create replacements elsewhere, and if their constraints allow no other node, the replacements stay Pending. uncordon reopens the node. A FailedScheduling message counts nodes per reason, for example 0/3 nodes are available: 1 node(s) didn't match Pod's node affinity/selector, 1 node(s) had untolerated taint {dedicated: batch}, 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }. Each phrase names one filter, and together they account for every node.","title":"Cordon, drain and FailedScheduling messages"},{"body":"The cluster has a tainted control-plane node and two workers. You label kind-worker with disk=ssd and pin the fast Deployment there with a nodeSelector, taint kind-worker2 for batch work, watch a Deployment without a toleration fail to schedule, and add the toleration with a patch. Finally you drain kind-worker to see what a nodeSelector does when its only matching node goes away.","code":"cluster create --workers 2\nkubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].key\nkubectl label node kind-worker disk=ssd\ncat > fast.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: fast\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: fast\n  template:\n    metadata:\n      labels:\n        app: fast\n    spec:\n      nodeSelector:\n        disk: ssd\n      containers:\n      - name: web\n        image: gopherforge/web:v1\nEOF\nkubectl apply -f fast.yaml\nkubectl rollout status deploy/fast\nkubectl get pods -o wide\nkubectl taint nodes kind-worker2 dedicated=batch:NoSchedule\ncat > batch.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: batch\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: batch\n  template:\n    metadata:\n      labels:\n        app: batch\n    spec:\n      nodeSelector:\n        kubernetes.io/hostname: kind-worker2\n      containers:\n      - name: worker\n        image: gopherforge/web:v1\nEOF\nkubectl apply -f batch.yaml\nkubectl events --types=Warning\nkubectl patch deploy batch --patch '{\"spec\":{\"template\":{\"spec\":{\"tolerations\":[{\"key\":\"dedicated\",\"operator\":\"Equal\",\"value\":\"batch\",\"effect\":\"NoSchedule\"}]}}}}'\nkubectl rollout status deploy/batch\nkubectl drain kind-worker --ignore-daemonsets\nkubectl get pods -o wide\nkubectl uncordon kind-worker","language":"bash","title":"Try it in the lab terminal","walkthrough":"The TAINTS column shows node-role.kubernetes.io/control-plane on kind-control-plane only. All three fast Pods land on kind-worker. The batch Pods stay Pending, and events shows FailedScheduling: 1 node(s) didn't match Pod's node affinity/selector, 1 node(s) had untolerated taint {dedicated: batch}, plus the control-plane taint. After the patch the rollout finishes on kind-worker2. drain prints node/kind-worker cordoned, warns about ignored DaemonSet Pods and evicts the fast Pods; their replacements stay Pending with NODE <none>, since no other node has disk=ssd, until uncordon lets the scheduler place them again."}],"takeaway":"The scheduler filters nodes on requests, selectors, affinity, taints and spread constraints, then scores the rest. Selectors and affinity attract, taints repel and tolerations only permit, and a FailedScheduling message tells you which rule excluded each node.","title":"Scheduling: node selection, affinity, taints and tolerations, spreading and draining nodes","unitID":"k8s-workloads","wrongAnswers":["NoSchedule must be NoExecute to dedicate the nodes","Tolerations only apply to Pods created after the taint"]},{"conceptTag":"k8s.statefulsets-daemonsets","designGuide":{"cautions":["Claims outlive the StatefulSet and keep costing storage.","A DaemonSet skips tainted nodes unless it tolerates them."],"cost":"A persistent volume per replica with backups, an application that handles its own replication, and small DaemonSet requests on every node.","family":"kubernetes","flow":["Create a headless Service","StatefulSet with claim templates","Ordered start, stable DNS","DaemonSet for node agents"],"ratings":[],"strengths":["Members keep names, DNS records and volumes across restarts.","DaemonSets follow nodes as they join and leave."]},"hint":"StatefulSet storage belongs to an ordinal, not to a Pod. What would scaling back up need?","id":"k8s.statefulsets-daemonsets","introduction":"Deployments treat Pods as interchangeable: random names, new IPs, no memory of earlier replicas. Databases, queues and consensus systems need the opposite: each member keeps its name, its DNS record and its disk across restarts. Node agents need a third shape, exactly one Pod on every node. StatefulSets and DaemonSets provide those two guarantees.","nuance":"persistentVolumeClaimRetentionPolicy defaults to Retain for both whenScaled and whenDeleted, so data-db-1 and data-db-2 stay Bound and are reattached when those ordinals return. Set Delete to remove them.","objective":"Run a StatefulSet with a headless Service and volumeClaimTemplates, predict its ordering and storage behaviour, and run a DaemonSet that covers every node, tainted ones included.","question":"You scale a StatefulSet with volumeClaimTemplates from 3 replicas to 1. By default, what happens to the claims of db-1 and db-2?","references":["https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/","https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/","https://kubernetes.io/docs/concepts/services-networking/service/#headless-services","https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/"],"reviewAnswer":"They are kept, unless the retention policy says Delete","reviewPrompt":"StatefulSet scale-down: its PVCs?","sections":[{"body":"A StatefulSet named db with three replicas creates Pods db-0, db-1 and db-2. Each name is stable: if db-1 is deleted or its node fails, the replacement is again db-1, with the same DNS name and the same volume, although usually with a new IP. With the default podManagementPolicy: OrderedReady, Pods are created one at a time in ordinal order, each waiting until the previous one is Running and Ready, and removed in reverse order when you scale down. Rolling updates also go from the highest ordinal down, and a partition lets you update only ordinals at or above a number, as a canary. Parallel management drops the ordering when members do not depend on each other.","title":"What a StatefulSet guarantees"},{"body":"serviceName points at a headless Service, one with clusterIP: None. Instead of a virtual IP, its DNS name returns the addresses of the ready Pods, and each Pod gets its own record of the form <pod>.<service>.<namespace>.svc.cluster.local. volumeClaimTemplates make the controller create one PersistentVolumeClaim per ordinal, named <template>-<pod>, here data-redis-0 to data-redis-2, and mount it into that Pod only. The StatefulSet does not create the Service; it must exist for the per-Pod DNS records to work.","code":"apiVersion: v1\nkind: Service\nmetadata:\n  name: redis\nspec:\n  clusterIP: None\n  selector:\n    app: redis\n  ports:\n  - name: redis\n    port: 6379\n---\napiVersion: apps/v1\nkind: StatefulSet\nmetadata:\n  name: redis\nspec:\n  serviceName: redis\n  replicas: 3\n  selector:\n    matchLabels:\n      app: redis\n  template:\n    metadata:\n      labels:\n        app: redis\n    spec:\n      containers:\n      - name: redis\n        image: redis:7\n        ports:\n        - name: redis\n          containerPort: 6379\n        volumeMounts:\n        - name: data\n          mountPath: /data\n  volumeClaimTemplates:\n  - metadata:\n      name: data\n    spec:\n      accessModes: [\"ReadWriteOnce\"]\n      resources:\n        requests:\n          storage: 1Gi","language":"yaml","title":"Headless Service and volumeClaimTemplates","walkthrough":"The headless Service selects app: redis and names its port. The StatefulSet links to it with serviceName: redis. Each replica gets its own 1Gi ReadWriteOnce claim from the default StorageClass, standard in kind, mounted at /data where Redis writes its snapshots. Replication between the three Redis processes is not configured here: that is the application's job, not Kubernetes'."},{"body":"A claim created from volumeClaimTemplates belongs to the ordinal, not to a Pod. When redis-1 is deleted, the new redis-1 mounts data-redis-1 again, so whatever it wrote survives. With a node-local provisioner such as kind's local-path, the volume is pinned to one node and the Pod must return to it. Scaling down or deleting the StatefulSet keeps the claims by default, so scaling up again reattaches the old data; persistentVolumeClaimRetentionPolicy with whenScaled or whenDeleted set to Delete changes that. Deleting a claim releases its volume according to the reclaim policy, which is Delete for dynamically provisioned volumes: the data is gone. Keep backups, because a StatefulSet provides identity, not durability or replication.","title":"Volumes that outlive Pods"},{"body":"A DaemonSet runs one copy of its Pod on every node that matches its node selector and affinity and whose taints it tolerates. When a node joins it gets a Pod; when a node leaves, the Pod goes with it. kube-proxy and kind's kindnet network agent are DaemonSets, as are log shippers, node exporters and storage drivers. The controller adds tolerations for conditions such as node.kubernetes.io/not-ready and unreachable automatically, but not for the control-plane taint, so add that toleration when an agent must run there; kube-proxy simply tolerates every taint with operator: Exists. Updates roll node by node, one unavailable at a time by default. Keep requests small, since a DaemonSet's requests are taken from every node.","code":"apiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: node-agent\nspec:\n  selector:\n    matchLabels:\n      app: node-agent\n  template:\n    metadata:\n      labels:\n        app: node-agent\n    spec:\n      tolerations:\n      - key: node-role.kubernetes.io/control-plane\n        operator: Exists\n        effect: NoSchedule\n      containers:\n      - name: agent\n        image: busybox\n        command: [\"sh\", \"-c\", \"while true; do sleep 3600; done\"]\n        resources:\n          requests:\n            cpu: 10m\n            memory: 16Mi","language":"yaml","title":"DaemonSets: one Pod per eligible node","walkthrough":"The toleration lets the agent run on the tainted control-plane node as well as on the workers. The busybox loop keeps the container running, standing in for a real agent. The small requests matter because every node in the cluster pays them."},{"body":"The lab uses a cluster with two workers. Apply the Service and StatefulSet together, watch the ordered start, resolve a member by its stable DNS name from another member, delete one Pod and scale down. Then list the DaemonSets that kind itself runs in kube-system and add your own node agent that tolerates the control-plane taint, so that it covers all three nodes.","code":"cluster create --workers 2\ncat > redis.yaml <<'EOF'\napiVersion: v1\nkind: Service\nmetadata:\n  name: redis\nspec:\n  clusterIP: None\n  selector:\n    app: redis\n  ports:\n  - name: redis\n    port: 6379\n---\napiVersion: apps/v1\nkind: StatefulSet\nmetadata:\n  name: redis\nspec:\n  serviceName: redis\n  replicas: 3\n  selector:\n    matchLabels:\n      app: redis\n  template:\n    metadata:\n      labels:\n        app: redis\n    spec:\n      containers:\n      - name: redis\n        image: redis:7\n        ports:\n        - name: redis\n          containerPort: 6379\n        volumeMounts:\n        - name: data\n          mountPath: /data\n  volumeClaimTemplates:\n  - metadata:\n      name: data\n    spec:\n      accessModes: [\"ReadWriteOnce\"]\n      resources:\n        requests:\n          storage: 1Gi\nEOF\nkubectl apply -f redis.yaml\nkubectl get pods -l app=redis\nkubectl rollout status sts/redis\nkubectl get pvc\nkubectl exec redis-0 -- nslookup redis-2.redis\nkubectl delete pod redis-1\nkubectl wait --for=condition=Ready pod/redis-1 --timeout=60s\nkubectl scale sts redis --replicas=1\nkubectl get pods,pvc\nkubectl get ds -n kube-system\ncat > agent.yaml <<'EOF'\napiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: node-agent\nspec:\n  selector:\n    matchLabels:\n      app: node-agent\n  template:\n    metadata:\n      labels:\n        app: node-agent\n    spec:\n      tolerations:\n      - key: node-role.kubernetes.io/control-plane\n        operator: Exists\n        effect: NoSchedule\n      containers:\n      - name: agent\n        image: busybox\n        command: [\"sh\", \"-c\", \"while true; do sleep 3600; done\"]\n        resources:\n          requests:\n            cpu: 10m\n            memory: 16Mi\nEOF\nkubectl apply -f agent.yaml\nkubectl wait --for=condition=Ready pod -l app=node-agent --timeout=60s\nkubectl get pods -l app=node-agent -o wide","language":"bash","title":"Try it in the lab terminal","walkthrough":"Right after apply only redis-0 exists. rollout status waits for 3, 2, then 1 Pods and prints partitioned roll out complete: 3 new pods have been updated..., kubectl's usual wording for StatefulSets. Claims data-redis-0 to data-redis-2 are Bound, and nslookup redis-2.redis returns redis-2's Pod IP. The deleted redis-1 returns under the same name. After scaling to 1, redis-2 is Terminating first while redis-1 waits its turn, and all three claims stay Bound. kube-system runs kindnet and kube-proxy with DESIRED 3, and node-agent ends with one Running Pod on each of kind-control-plane, kind-worker and kind-worker2."}],"takeaway":"StatefulSets give each replica a stable name, DNS record and volume, start and stop replicas in order, and keep their claims after a scale-down. DaemonSets run one Pod per eligible node and must tolerate any taint on the nodes they are meant to cover.","title":"StatefulSets for stable identity and storage, DaemonSets for one Pod per node","unitID":"k8s-workloads","wrongAnswers":["They are deleted along with the Pods and their data","They are released and rebound to the next new Pod"]},{"conceptTag":"k8s.jobs-cronjobs","designGuide":{"cautions":["A run can happen twice or not at all; design for both.","Finished Jobs pile up without TTLs or history limits."],"cost":"Idempotent batch code, a retry budget and deadline per Job, and monitoring for failed and missed runs.","family":"kubernetes","flow":["Write an idempotent task","Job: completions, backoffLimit","Deadline and TTL","CronJob: schedule, Forbid"],"ratings":[],"strengths":["Retries, deadlines and history are declared, not scripted.","A CronJob can be run by hand with create job --from."]},"hint":"Allow, Forbid and Replace differ only in what they do when the previous Job has not finished yet.","id":"k8s.jobs-cronjobs","introduction":"Not every workload serves requests. Reports, migrations, imports and cleanups run, finish and exit, and a Deployment would restart them forever. A Job runs Pods until enough of them succeed and gives up after a set number of failures or a deadline; a CronJob creates Jobs on a schedule. Both retry, so the code they run must tolerate running more than once.","nuance":"Forbid does not start a scheduled run while the previous Job is active. Replace would stop the old Job, Allow would run both. The skipped run may still start late when the old Job ends, unless its startingDeadlineSeconds has passed.","objective":"Run Jobs with completions, parallelism, backoffLimit and activeDeadlineSeconds, schedule them with CronJobs and a concurrency policy, trigger a run by hand, and write batch code that is safe to retry.","question":"A CronJob runs every 10 minutes with concurrencyPolicy: Forbid. At 00:10 the run that started at 00:00 is still active. What happens at 00:10?","references":["https://kubernetes.io/docs/concepts/workloads/controllers/job/","https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/","https://kubernetes.io/docs/concepts/workloads/controllers/ttlafterfinished/","https://kubernetes.io/docs/tasks/job/pod-failure-policy/"],"reviewAnswer":"The new run is skipped; the active Job keeps running","reviewPrompt":"Forbid while a run is active?","sections":[{"body":"A Job creates Pods from its template until completions of them have exited with status 0, running at most parallelism at a time; both default to 1. completionMode: Indexed gives each Pod a JOB_COMPLETION_INDEX from 0 to completions minus 1, a simple way to shard work. The template must set restartPolicy to Never or OnFailure. With Never, a failed container leaves its Pod in Error and the Job creates a new Pod, so every failed attempt keeps its logs. With OnFailure, the kubelet restarts the container inside the same Pod, which is faster but keeps only the previous attempt's logs. A finished Job and its Pods stay until you delete them or ttlSecondsAfterFinished removes them.","title":"How a Job runs to completion"},{"body":"backoffLimit, 6 by default, is how many failures the Job tolerates; failed Pods and container restarts both count. Between attempts the controller waits with an exponential back-off of 10, 20, 40 seconds and so on, capped at six minutes. When the limit is exceeded, the Job gets the Failed condition with reason BackoffLimitExceeded and its running Pods are terminated. activeDeadlineSeconds bounds the whole run time regardless of retries and fails the Job with reason DeadlineExceeded, which protects you from a task that hangs forever. A podFailurePolicy can fail the Job at once on exit codes that retrying cannot fix, or ignore disruptions such as node drains.","code":"apiVersion: batch/v1\nkind: Job\nmetadata:\n  name: report\nspec:\n  completions: 4\n  parallelism: 2\n  backoffLimit: 3\n  activeDeadlineSeconds: 300\n  ttlSecondsAfterFinished: 3600\n  template:\n    spec:\n      restartPolicy: Never\n      containers:\n      - name: worker\n        image: gopherforge/worker:v1","language":"yaml","title":"Retries and deadlines","walkthrough":"Four successful Pods are needed, two run at a time, at most three failures are tolerated, and the whole Job must finish within five minutes. An hour after it finishes, the TTL controller deletes the Job together with its Pods, so completed runs do not pile up in the namespace."},{"body":"A CronJob creates a Job from jobTemplate whenever its schedule matches. The schedule has five fields, minute, hour, day of month, month and day of week, so */15 * * * * means every 15 minutes and 30 2 * * 1-5 means 02:30 on weekdays; macros such as @hourly and @daily work too. Without timeZone, the controller manager's time zone applies, usually UTC. concurrencyPolicy decides what happens if the previous run is still active: Allow runs both, Forbid skips the new one, Replace stops the old one. A run skipped by Forbid can still start late once the old Job ends, unless startingDeadlineSeconds has passed. startingDeadlineSeconds drops runs that could not start in time, for example after a control-plane outage. successfulJobsHistoryLimit (3) and failedJobsHistoryLimit (1) set how many finished Jobs are kept, and suspend: true pauses the schedule.","code":"apiVersion: batch/v1\nkind: CronJob\nmetadata:\n  name: nightly-report\nspec:\n  schedule: \"30 2 * * 1-5\"\n  timeZone: Europe/Berlin\n  concurrencyPolicy: Forbid\n  startingDeadlineSeconds: 600\n  successfulJobsHistoryLimit: 3\n  failedJobsHistoryLimit: 1\n  jobTemplate:\n    spec:\n      backoffLimit: 2\n      activeDeadlineSeconds: 3600\n      template:\n        spec:\n          restartPolicy: OnFailure\n          containers:\n          - name: worker\n            image: gopherforge/worker:v1","language":"yaml","title":"CronJobs: schedule, concurrency and history","walkthrough":"The report runs at 02:30 Berlin time on weekdays, across daylight-saving changes, and never overlaps a run that is still going. If the controller cannot start it within ten minutes of the scheduled time, that run is skipped rather than started late. Each run may retry twice and must finish within an hour."},{"body":"Jobs promise at least one attempt, not exactly one. A Pod can be retried after a partial run, a node failure can leave a Pod running while its replacement starts, and the CronJob documentation warns that a schedule can occasionally create two Jobs or none. Make every run idempotent: key the work by its scheduled period, record completion in the same transaction as the work, prefer upserts to blind inserts, and pass idempotency keys to external APIs. Exit non-zero on any failure so the Job retries, and with 0 only after the results are committed. Handle SIGTERM, which arrives on a drain, a deadline or a Replace.","code":"// runReport builds the report for one day at most once, however often it runs.\nfunc runReport(ctx context.Context, db *sql.DB, day string) error {\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\tres, err := tx.ExecContext(ctx,\n\t\t`INSERT INTO report_runs (day) VALUES ($1) ON CONFLICT (day) DO NOTHING`, day)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n, _ := res.RowsAffected(); n == 0 {\n\t\treturn nil // an earlier run already committed this day\n\t}\n\tif err := buildReport(ctx, tx, day); err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}","language":"go","title":"Write batch work that is safe to repeat","walkthrough":"The marker row and the report are committed together, so a crash before Commit leaves neither and the retry starts cleanly, while a duplicate run finds the marker and returns without doing the work twice. main calls it with the scheduled day and exits with status 1 on an error, leaving retries to backoffLimit."},{"body":"Run a Job that needs four completions two at a time, then a Job whose image always fails, then a CronJob that fires every minute. cluster tick 3m advances virtual time by three minutes, so the schedule fires without waiting. The last command starts a run from the CronJob's template immediately, which is how you test a CronJob or rerun a night that failed.","code":"kind create cluster\ncat > report.yaml <<'EOF'\napiVersion: batch/v1\nkind: Job\nmetadata:\n  name: report\nspec:\n  completions: 4\n  parallelism: 2\n  backoffLimit: 3\n  activeDeadlineSeconds: 300\n  template:\n    spec:\n      restartPolicy: Never\n      containers:\n      - name: worker\n        image: gopherforge/worker:v1\nEOF\nkubectl apply -f report.yaml\nkubectl get pods -l job-name=report\nkubectl wait --for=condition=Complete job/report --timeout=120s\nkubectl get job report\ncat > flaky.yaml <<'EOF'\napiVersion: batch/v1\nkind: Job\nmetadata:\n  name: flaky\nspec:\n  backoffLimit: 2\n  template:\n    spec:\n      restartPolicy: Never\n      containers:\n      - name: worker\n        image: gopherforge/worker:fail\nEOF\nkubectl apply -f flaky.yaml\nkubectl wait --for=condition=Failed job/flaky --timeout=180s\nkubectl get pods -l job-name=flaky\nkubectl events --for job/flaky\ncat > cleanup.yaml <<'EOF'\napiVersion: batch/v1\nkind: CronJob\nmetadata:\n  name: cleanup\nspec:\n  schedule: \"*/1 * * * *\"\n  concurrencyPolicy: Forbid\n  successfulJobsHistoryLimit: 2\n  failedJobsHistoryLimit: 1\n  jobTemplate:\n    spec:\n      backoffLimit: 1\n      activeDeadlineSeconds: 50\n      template:\n        spec:\n          restartPolicy: OnFailure\n          containers:\n          - name: worker\n            image: gopherforge/worker:v1\nEOF\nkubectl apply -f cleanup.yaml\ncluster tick 3m\nkubectl get cronjob,jobs\nkubectl create job cleanup-manual --from=cronjob/cleanup","language":"bash","title":"Try it in the lab terminal","walkthrough":"report starts two Pods named report-<id>, and once wait returns, get job shows Complete 4/4. flaky leaves three Pods in Error, the first attempt plus two retries, and its events end with BackoffLimitExceeded: Job has reached the specified backoff limit. After the tick, the CronJob's LAST SCHEDULE is seconds old and its Jobs are named cleanup-<number>, each Complete 1/1; in a real cluster the number is the scheduled time in minutes since the Unix epoch. create job --from prints job.batch/cleanup-manual created."}],"takeaway":"A Job retries Pods until enough succeed, within backoffLimit and activeDeadlineSeconds; a CronJob creates such Jobs on a schedule with an explicit concurrency policy. Because any run may happen twice, design batch work to be idempotent.","title":"Jobs and CronJobs: batch work with retries, deadlines and schedules","unitID":"k8s-workloads","wrongAnswers":["The active Job is stopped and a new one starts","Both Jobs run side by side until each finishes"]},{"conceptTag":"k8s.services","designGuide":{"cautions":["A wrong targetPort still lists endpoints and fails every connection.","Balancing is per connection, so long-lived connections stick to one pod."],"cost":"One extra object per workload, and the habit of checking endpoints before blaming the application.","family":"kubernetes","flow":["Label the pod template","Select it in the Service","Map port to targetPort","Check endpoints first"],"ratings":[],"strengths":["Clients use one name and one IP that outlive every pod.","Only ready pods receive new connections."]},"hint":"The Service exists and has endpoints, so the name and the selector work. Compare the port in each endpoint with the port the process opens.","id":"k8s.services","introduction":"Every pod gets its own IP address and loses it when the pod is replaced by a rollout, a crash or a node drain. Clients cannot chase those addresses. A Service gives a changing set of pods one stable virtual IP and one DNS name, and Kubernetes keeps the list of real backends current as pods come and go.","nuance":"Refused with endpoints present means packets reach the pod IP but nothing listens on that port: targetPort is wrong. A NetworkPolicy causes a timeout, and a DNS problem fails before any connection.","objective":"Expose a Deployment through a ClusterIP Service, trace a request from selector to endpoints to targetPort, and fix a wrong targetPort and a selector that matches no pods.","question":"Service web lists two endpoints and both pods are Ready, yet every curl to http://web from another pod gets \"Connection refused\". What is the most likely cause?","references":["https://kubernetes.io/docs/concepts/services-networking/service/","https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/","https://kubernetes.io/docs/reference/networking/virtual-ips/","https://kubernetes.io/docs/tasks/debug/debug-application/debug-service/"],"reviewAnswer":"targetPort differs from the port the container serves","reviewPrompt":"Ready endpoints, refused calls?","sections":[{"body":"The network plugin (CNI) gives each pod an IP from its node's pod range, 10.244.x.y in kind, and every pod can reach every other pod directly without NAT. That flat network is what makes Services possible, but a pod IP lives only as long as its pod. A Deployment replaces pods on every rollout, a failed node takes its pods with it, and the replacements come up with new addresses. A client that stored a pod IP keeps talking to an address that is gone or, worse, now belongs to a different pod. Hardcoding pod IPs in configuration, or resolving them once at startup, works in a demo and breaks on the first rollout. Clients need a name and an address that outlive any single pod.","title":"Pod IPs are real but short-lived"},{"body":"A Service has two jobs. Its selector picks the backend pods by label, and its ports say how traffic arrives and where it goes. port is what clients connect to on the Service's cluster IP; targetPort is the port inside the pod where the process listens. If you omit targetPort it defaults to port, a common silent mismatch when the app listens on 8080 and the Service on 80. targetPort may also be a name that refers to a named containerPort. Each pod then resolves the name itself, so an image that moves the app to another port only needs a new pod template, not a Service change. The API server allocates the ClusterIP from the service range, 10.96.x.y in kind, and the address stays fixed for the life of the Service.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - name: http\n          containerPort: 8080\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector:\n    app: web\n  ports:\n  - name: http\n    port: 80\n    targetPort: http","language":"yaml","title":"A Service object: selector, port and targetPort","walkthrough":"The pod template names its container port http, and the Service refers to that name instead of 8080. Clients use web:80 and each connection is sent to a pod IP on 8080. The Service selects on app: web only, so pods from any workload with that label become backends. A numeric targetPort works even if containerPort is not declared, but a named targetPort only resolves in pods that declare the name; a pod without it is left out of the endpoints."},{"body":"The Service object holds no pod addresses. The EndpointSlice controller in kube-controller-manager watches Services and pods and, for every Service with a selector, writes EndpointSlice objects listing each matching pod's IP, the resolved targetPort and its conditions: ready, serving and terminating. Only ready pods receive new connections, which is why a readiness probe controls traffic. A Service without a selector gets no automatic endpoints; that form is for backends you manage yourself. The older Endpoints API carries the same data in one object per Service and has been deprecated since Kubernetes 1.33, so kubectl get endpoints prints a deprecation warning on current clusters, and kubectl get endpointslices -l kubernetes.io/service-name=web is the modern view. In the GopherForge lab, kubectl get endpointslices -l kubernetes.io/service-name=web shows them, and kubectl get endpoints shows the same data in the older form.","title":"From selector to EndpointSlices"},{"body":"No network interface owns a ClusterIP and no process listens on it. kube-proxy runs on every node, watches Services and EndpointSlices, and programs the kernel, with iptables rules by default or nftables in the newer mode, so that a connection to 10.96.x.y:80 is rewritten (DNAT) to one ready pod's IP and targetPort. The choice is made once per connection, not per request: a client that keeps one HTTP/2 or gRPC connection open talks to a single pod for the life of that connection. The rewrite happens on the client's own node, so the client never sees the pod address. When a Service has no ready endpoints, kube-proxy installs a reject rule, and clients get an immediate connection refused instead of a hang.","title":"kube-proxy turns the virtual IP into a pod"},{"body":"A wrong targetPort looks healthy from the API: the Service exists, the pods are Running and Ready, and endpoints are listed. Every connection is still refused, because the endpoints point at a port where nothing listens. A selector that matches nothing fails differently: endpoints are <none>, usually because of a typo, a label set on the Deployment instead of the pod template, or a Service in another namespace than its pods. kubectl port-forward svc/web is the quick check from your laptop. It tunnels through the API server and the kubelet to one pod chosen when it starts, so it bypasses kube-proxy, does not balance load and does not follow a replaced pod. It is a debugging tool, not a way to serve users.","code":"kubectl get svc web -o wide\nkubectl get pods -l app=web --show-labels\nkubectl get endpoints web\nkubectl describe svc web","language":"bash","title":"Two classic bugs: wrong targetPort and an empty selector","walkthrough":"Read the four outputs together. The SELECTOR column of get svc must match the labels that --show-labels prints; if the -l query returns no pods, the selector is the bug. get endpoints lists pod-ip:port pairs: <none> means no ready pod matches, while a port that differs from the containerPort means a wrong targetPort. describe shows TargetPort and Endpoints side by side."},{"body":"Deploy two replicas of gopherforge/web:v1, which listens on 8080, and expose them with a deliberately wrong targetPort of 9090. A curl client pod stands in for another service in the cluster. Call the Service from it and see the failure, read the endpoints to find out why, and patch the Service. Then call it again from the pod, and reach the same Service from your own terminal through kubectl port-forward, the way you would check a Service on a real cluster from a laptop.","code":"kind create cluster\nkubectl create deployment web --image=gopherforge/web:v1 --replicas=2 --port=8080\nkubectl expose deployment web --port=80 --target-port=9090\nkubectl run client --image=curlimages/curl -- sleep 3600\nkubectl rollout status deploy/web\nkubectl wait --for=condition=Ready pod/client\nkubectl exec client -- curl -sS http://web\nkubectl get endpoints web\nkubectl get pods -l app=web -o wide\nkubectl patch svc web --patch '{\"spec\":{\"ports\":[{\"port\":80,\"targetPort\":8080}]}}'\nkubectl get endpoints web\nkubectl exec client -- curl -sS http://web\nkubectl port-forward svc/web 8080:80\ncurl -s http://localhost:8080/version","language":"bash","title":"Try it in the lab terminal","walkthrough":"get endpoints shows 10.244.0.10:9090,10.244.0.9:9090: both pods are listed, ready and wrong. The first curl from the client fails with \"Connection refused\" because nothing listens on 9090, and get pods -o wide confirms that those IPs belong to the web pods. After the patch the same IPs appear on :8080 and curl prints \"gopherforge web v1 served by web-<hash>-<id>\". port-forward reports \"Forwarding from 127.0.0.1:8080 -> 8080\", already resolved to the targetPort, and /version answers v1."}],"takeaway":"A Service is a selector plus a port mapping: the EndpointSlice controller turns the selector into ready pod addresses, and kube-proxy turns the ClusterIP into one of them per connection. When traffic fails, read the endpoints first: none means selector or readiness, the wrong port means targetPort.","title":"Services: a stable virtual IP and DNS name in front of changing pods","unitID":"k8s-networking","wrongAnswers":["A NetworkPolicy drops the traffic between client and pods","CoreDNS returns a stale IP address for the name web"]},{"conceptTag":"k8s.service-types","designGuide":{"cautions":["Without a load-balancer controller EXTERNAL-IP stays <pending>.","ExternalName changes DNS only; Host headers and TLS names still differ."],"cost":"A cloud load balancer per LoadBalancer Service, which is why HTTP apps usually share one through an Ingress or a Gateway.","family":"kubernetes","flow":["Inside only: ClusterIP","From a cloud LB: LoadBalancer","DNS alias: ExternalName","Every pod: clusterIP None"],"ratings":[],"strengths":["The types stack, so one Service serves inside and outside callers.","Headless and ExternalName solve discovery without any proxying."]},"hint":"Ask which Service type skips the virtual IP and publishes the pod addresses in DNS instead of hiding them behind kube-proxy.","id":"k8s.service-types","introduction":"A ClusterIP is reachable only from inside the cluster. Letting traffic in from outside, pointing an in-cluster name at an external host, or letting clients see every pod each needs a different Service type. The types stack: every LoadBalancer is also a NodePort, and every NodePort is also a ClusterIP.","nuance":"A headless Service (clusterIP: None) has no virtual IP: DNS returns each ready pod, and a StatefulSet gets records like db-0.db.ns.svc.cluster.local. ClusterIP and LoadBalancer hide pods behind one address.","objective":"Pick the right Service type for each job, reach a NodePort and a LoadBalancer from outside the cluster, and explain what externalTrafficPolicy changes.","question":"A StatefulSet of three database pods needs each member to be reachable under its own stable DNS name. Which Service should its serviceName point to?","references":["https://kubernetes.io/docs/concepts/services-networking/service/","https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/","https://kind.sigs.k8s.io/docs/user/loadbalancer/"],"reviewAnswer":"A headless Service with clusterIP: None","reviewPrompt":"Per-pod DNS for a StatefulSet?","sections":[{"body":"ClusterIP is the default and the right choice for anything only other pods call. type: NodePort keeps the ClusterIP and also reserves one port, from 30000-32767 by default, on every node. kube-proxy on each node forwards that port to the Service, so a client can use any node's IP, including a node that runs none of the pods; that node forwards the connection over the pod network. If you omit nodePort the API server picks a free one. Set it explicitly only when something outside needs a fixed number, and expect a conflict error if another Service already holds it. High ports on node addresses that change are awkward for users, so NodePorts mostly serve as plumbing that a load balancer or a test setup points at.","code":"apiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  type: NodePort\n  selector:\n    app: web\n  ports:\n  - port: 80\n    targetPort: 8080\n    nodePort: 30080","language":"yaml","title":"ClusterIP and NodePort","walkthrough":"Three ports, three meanings: nodePort 30080 is opened on every node's IP, port 80 is the ClusterIP port that pods use, and targetPort 8080 is where the container listens. kubectl get svc shows the pair as 80:30080/TCP. In the lab, kubectl create service nodeport web --tcp=80:8080 --node-port=30080 creates the same object with a port named 80-8080."},{"body":"type: LoadBalancer asks for an external load balancer, but Kubernetes itself does not create one. On AWS, GCP or Azure the cloud controller manager provisions a cloud load balancer, points it at the node ports (or straight at pod IPs on some clouds), and writes its address into status.loadBalancer.ingress, which kubectl shows as EXTERNAL-IP. On bare metal MetalLB fills that role; on kind, cloud-provider-kind does. Without such a controller the Service shows <pending> forever, the first thing to check when an EXTERNAL-IP never appears. In the GopherForge lab a simulated controller assigns 172.18.255.x addresses. Each LoadBalancer Service is usually a separate, billed cloud resource, so many HTTP services normally share one entry point through an Ingress or a Gateway instead.","title":"LoadBalancer: an external address from a controller"},{"body":"type: ExternalName has no selector, no ClusterIP and no proxying: CoreDNS answers the Service name with a CNAME to spec.externalName. Pods can call payments today and switch to an in-cluster Service later without a configuration change. Only DNS changes, so HTTP Host headers and TLS certificates must still match the external name, which often breaks HTTPS. A headless Service sets clusterIP: None. It keeps its selector and endpoints, but there is no virtual IP and kube-proxy ignores it; DNS returns the IPs of all ready pods instead. Use it when clients must reach individual pods: StatefulSet members with stable names, a database primary and its replicas, or gRPC clients that balance across pods themselves.","code":"apiVersion: v1\nkind: Service\nmetadata:\n  name: payments\nspec:\n  type: ExternalName\n  externalName: api.payments.example.com\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web-headless\nspec:\n  clusterIP: None\n  selector:\n    app: web\n  ports:\n  - port: 8080","language":"yaml","title":"ExternalName and headless Services","walkthrough":"payments is only a DNS alias: kubectl get svc shows api.payments.example.com as its EXTERNAL-IP and no ports. web-headless has None as its CLUSTER-IP, yet its endpoints are the same pod addresses that web uses; only the way clients reach them differs. nslookup web-headless from a pod returns one address per ready pod instead of a single virtual IP."},{"body":"For NodePort and LoadBalancer Services, externalTrafficPolicy decides what a node does with traffic from outside. Cluster, the default, lets every node accept and forward to any ready pod in the cluster: load spreads evenly, but the extra hop adds latency and the node source-NATs the packet, so the pod sees a node IP instead of the client's. Local delivers only to pods on the receiving node: the client IP is preserved and there is no second hop, but nodes without a local pod drop the traffic. Cloud load balancers learn which nodes to use through a health check on healthCheckNodePort, and they spread traffic per node, not per pod, so uneven pod placement means uneven load. Choose Local when you need real client IPs for logs or allow-lists.","title":"externalTrafficPolicy: Cluster or Local"},{"body":"Start a cluster with a control plane and two workers, run three web pods behind a NodePort, and reach it through two different node IPs, one of them the control plane, which runs no web pod at all. Then add a LoadBalancer Service for the same pods and call its external IP from your terminal. Finish with an ExternalName alias and a headless Service, and compare how kubectl get svc and the endpoints present them.","code":"cluster create --workers 2\nkubectl create deployment web --image=gopherforge/web:v1 --replicas=3 --port=8080\nkubectl create service nodeport web --tcp=80:8080 --node-port=30080\nkubectl rollout status deploy/web\nkubectl get nodes -o wide\nkubectl get pods -o wide\ncurl -s http://172.18.0.2:30080/\ncurl -s http://172.18.0.4:30080/version\nkubectl expose deployment web --name=web-lb --type=LoadBalancer --port=80 --target-port=8080\nkubectl get svc web-lb\ncurl -s http://172.18.255.200/\ncat > more-services.yaml <<'EOF'\napiVersion: v1\nkind: Service\nmetadata:\n  name: payments\nspec:\n  type: ExternalName\n  externalName: api.payments.example.com\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web-headless\nspec:\n  clusterIP: None\n  selector:\n    app: web\n  ports:\n  - port: 8080\nEOF\nkubectl apply -f more-services.yaml\nkubectl get svc\nkubectl get endpoints web-headless","language":"bash","title":"Try it in the lab terminal","walkthrough":"The nodes are 172.18.0.2 (control plane), 172.18.0.3 and 172.18.0.4, and get pods -o wide places the web pods only on the two workers. The curl to the control plane's 172.18.0.2:30080 still answers \"gopherforge web v1 served by web-<hash>-<id>\", because every node forwards its node port. web-lb gets EXTERNAL-IP 172.18.255.200 plus a node port of its own, shown as 80:<nodePort>/TCP, and curl to that IP reaches a pod. get svc then lists the ExternalName and the headless Service, whose endpoints are the three web pods on 8080."}],"takeaway":"Use ClusterIP for in-cluster callers, NodePort as plumbing, LoadBalancer when a controller can give you an external address, ExternalName for DNS aliases and headless Services when clients need every pod. externalTrafficPolicy: Local trades even spreading for the client source IP.","title":"Service types: NodePort, LoadBalancer, ExternalName and headless Services","unitID":"k8s-networking","wrongAnswers":["A LoadBalancer Service with one external IP","An ExternalName Service that names the pods"]},{"conceptTag":"k8s.dns","designGuide":{"cautions":["ndots:5 turns one external lookup into four or more queries.","Short names are namespace-relative and fail across namespaces."],"cost":"Two CoreDNS pods per cluster, extra queries for every outside call, and a node-local cache once DNS load matters.","family":"kubernetes","flow":["Same namespace: web","Other namespace: web.shop","One pod: db-0.db.shop","External: trailing dot"],"ratings":[],"strengths":["Names survive pod and IP churn without client configuration.","Headless records give stateful members stable identities."]},"hint":"Read the search line in the pod's resolv.conf. Which namespace is appended to a short name first?","id":"k8s.dns","introduction":"Pods find Services by name. CoreDNS answers those names from the Kubernetes API, and the kubelet writes every pod's resolv.conf so that short names work. When a call cannot connect, the name has often resolved differently than you expected, or not at all.","nuance":"NXDOMAIN means CoreDNS answered: no Service web exists in the caller's namespace. Short names expand with the pod's own namespace first, so a Service in shop needs web.shop or its full name.","objective":"Resolve Services and StatefulSet pods by short and fully qualified names across namespaces, explain the extra lookups that ndots:5 causes, and debug name resolution from inside a pod.","question":"A pod in namespace default runs nslookup web and gets NXDOMAIN, although kubectl get svc -n shop lists web with endpoints. Which name should the pod use?","references":["https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/","https://kubernetes.io/docs/tasks/administer-cluster/dns-debugging-resolution/","https://kubernetes.io/docs/tasks/administer-cluster/nodelocaldns/","https://coredns.io/plugins/kubernetes/"],"reviewAnswer":"web.shop, or web.shop.svc.cluster.local","reviewPrompt":"Service web in shop, from default?","sections":[{"body":"Cluster DNS is an ordinary Deployment: CoreDNS, two replicas in kube-system labelled k8s-app=kube-dns, behind a Service that is still called kube-dns for compatibility. That Service has a fixed ClusterIP, 10.96.0.10 in kind, and the kubelet writes it as the nameserver of every pod whose dnsPolicy is ClusterFirst, the default. CoreDNS's kubernetes plugin watches Services and EndpointSlices and answers names under cluster.local from memory; everything else is forwarded to the node's upstream resolvers. Its configuration, the Corefile, lives in the coredns ConfigMap in kube-system. Because DNS is just pods behind a Service, it fails like any workload: if both CoreDNS pods are down, or a policy blocks port 53, every name lookup in the cluster times out.","title":"CoreDNS and the kube-dns Service"},{"body":"A Service web in namespace shop gets an A record, web.shop.svc.cluster.local, that points at its ClusterIP; a headless Service gets one A record per ready pod instead. Named ports also get SRV records such as _http._tcp.web.shop.svc.cluster.local. When a StatefulSet's serviceName is a headless Service, each pod gets its own record, db-0.db.shop.svc.cluster.local, which follows the pod across restarts even though its IP changes. An ExternalName Service is a CNAME. Ordinary pods are not resolvable by name; only pods with hostname and subdomain set, as StatefulSets do. Namespaces matter: a short name resolves only in the caller's own namespace, so a pod in default must say web.shop to reach the Service in shop.","code":"apiVersion: v1\nkind: Service\nmetadata:\n  name: db\n  namespace: shop\nspec:\n  clusterIP: None\n  selector:\n    app: db\n  ports:\n  - name: redis\n    port: 6379\n---\napiVersion: apps/v1\nkind: StatefulSet\nmetadata:\n  name: db\n  namespace: shop\nspec:\n  serviceName: db\n  replicas: 2\n  selector:\n    matchLabels:\n      app: db\n  template:\n    metadata:\n      labels:\n        app: db\n    spec:\n      containers:\n      - name: redis\n        image: redis:7\n        ports:\n        - name: redis\n          containerPort: 6379","language":"yaml","title":"The names a Service gets","walkthrough":"The headless Service db (clusterIP: None) is what the StatefulSet names in serviceName. That pairing gives db-0 and db-1 stable names under db.shop.svc.cluster.local, while db.shop itself resolves to the addresses of both ready pods. Clients that need one specific member, such as a primary, connect to db-0.db.shop; clients that can use any member use db.shop."},{"body":"In a pod in namespace default, /etc/resolv.conf lists three search domains, default.svc.cluster.local, svc.cluster.local and cluster.local, and options ndots:5. A name with fewer than five dots is treated as relative: the resolver first tries it with each search domain appended and only then as written. That is what makes web and web.shop work. It also means that an external name such as api.github.com, with two dots, is first looked up as api.github.com.default.svc.cluster.local, then with .svc.cluster.local, then with .cluster.local: three NXDOMAIN answers before the real one, and resolvers usually send both A and AAAA queries for every try. For a service that calls outside APIs often, that multiplies CoreDNS load and adds latency to every new connection.","code":"kubectl exec client -- cat /etc/resolv.conf","language":"bash","title":"Search domains and ndots:5","walkthrough":"The search line starts with the pod's own namespace, which is why a short name is namespace-relative. The nameserver is the kube-dns ClusterIP. ndots:5 is high on purpose, so that names such as web.shop.svc still go through the search list; the price is paid by every external name with fewer than five dots."},{"body":"Write external hosts as fully qualified names with a trailing dot, api.github.com., and the resolver skips the search list; a few HTTP clients and servers mishandle the dot in Host headers or TLS, so test it. For a pod that mostly calls outside services, lower ndots with dnsConfig, as below, so names with two or more dots are tried as written first while short in-cluster names still use the search list. Cluster-wide, NodeLocal DNSCache runs a caching resolver on every node and takes load off CoreDNS. Do not lower ndots to 1 for callers that use names like web.shop: that name would be tried as an absolute name first, and .shop is a real top-level domain. The lab terminal accepts dnsConfig, but its resolver ignores the option; measure the effect on a real cluster.","code":"apiVersion: v1\nkind: Pod\nmetadata:\n  name: worker\nspec:\n  dnsConfig:\n    options:\n    - name: ndots\n      value: \"2\"\n  containers:\n  - name: worker\n    image: busybox\n    command: [\"sleep\", \"3600\"]","language":"yaml","title":"Cutting the extra lookups","walkthrough":"dnsConfig is merged into the resolv.conf the kubelet generates: the search list and the nameserver stay, and ndots becomes 2. Option values are strings, so the 2 is quoted. The same block in a Deployment's pod template applies to every replica."},{"body":"Test from inside the cluster, in the namespace of the failing client, because the answer depends on the caller's search list. busybox's nslookup covers most checks; for dig, the Kubernetes DNS debugging guide uses a dnsutils image. NXDOMAIN means CoreDNS answered and the name does not exist: check the namespace, the Service name and typos. A timeout means no answer at all: check that the CoreDNS pods are Running and Ready, that kube-dns has endpoints, and that no NetworkPolicy blocks egress to UDP and TCP port 53. If kubernetes.default resolves but your name does not, the problem is the name, not DNS. And a successful lookup proves nothing about the backend: a ClusterIP is returned even when the Service has no endpoints.","code":"kubectl get pods -n kube-system -l k8s-app=kube-dns\nkubectl get endpoints -n kube-system kube-dns\nkubectl logs -n kube-system -l k8s-app=kube-dns\nkubectl exec client -- nslookup kubernetes.default","language":"bash","title":"Debugging DNS from a pod","walkthrough":"Work from the server side to the client: two coredns pods Running, the kube-dns Service with endpoints on port 53, logs without errors, then a lookup of kubernetes.default, a name that exists in every cluster. If that lookup returns 10.96.0.1, DNS is healthy and the remaining question is the name you asked for."},{"body":"Put a web Service and a Redis StatefulSet with a headless Service in namespace shop, then resolve them from a busybox client in namespace default. Read the client's resolv.conf first, then try a short name that fails, a namespace-qualified name and a fully qualified one. Finish with the headless Service, which returns every pod, and the stable name of one StatefulSet pod. busybox ships nslookup and wget, which is all this needs.","code":"kind create cluster\nkubectl create namespace shop\nkubectl create deployment web -n shop --image=gopherforge/web:v1 --port=8080\nkubectl expose deployment web -n shop --port=80 --target-port=8080\ncat > db.yaml <<'EOF'\napiVersion: v1\nkind: Service\nmetadata:\n  name: db\n  namespace: shop\nspec:\n  clusterIP: None\n  selector:\n    app: db\n  ports:\n  - name: redis\n    port: 6379\n---\napiVersion: apps/v1\nkind: StatefulSet\nmetadata:\n  name: db\n  namespace: shop\nspec:\n  serviceName: db\n  replicas: 2\n  selector:\n    matchLabels:\n      app: db\n  template:\n    metadata:\n      labels:\n        app: db\n    spec:\n      containers:\n      - name: redis\n        image: redis:7\n        ports:\n        - name: redis\n          containerPort: 6379\nEOF\nkubectl apply -f db.yaml\nkubectl run client --image=busybox -- sleep 3600\nkubectl wait --for=condition=Ready pod/client\nkubectl exec client -- cat /etc/resolv.conf\nkubectl exec client -- nslookup web\nkubectl exec client -- nslookup web.shop\nkubectl exec client -- wget -qO- http://web.shop.svc.cluster.local/version\nkubectl rollout status statefulset/db -n shop\nkubectl exec client -- nslookup db.shop\nkubectl exec client -- nslookup db-0.db.shop.svc.cluster.local","language":"bash","title":"Try it in the lab terminal","walkthrough":"resolv.conf shows \"search default.svc.cluster.local svc.cluster.local cluster.local\", \"nameserver 10.96.0.10\" and \"options ndots:5\". nslookup web fails with \"** server can't find web: NXDOMAIN\", because the client lives in default and the Service in shop. web.shop resolves to web.shop.svc.cluster.local and its ClusterIP, and wget through the full name prints v1. Once the StatefulSet is ready, db.shop returns two addresses, one per pod, and db-0.db.shop.svc.cluster.local returns only the first pod's IP."}],"takeaway":"Service names resolve as name.namespace.svc.cluster.local, short names only within the caller's namespace, and headless Services expose pods directly. ndots:5 sends external names through three search domains first; use trailing dots, a lower ndots or a node-local cache where that cost matters.","title":"Cluster DNS: CoreDNS, service names, search domains and ndots","unitID":"k8s-networking","wrongAnswers":["The ClusterIP, because CoreDNS is unreachable","web.default, after restarting the CoreDNS pods"]},{"conceptTag":"k8s.ingress","designGuide":{"cautions":["Without a matching controller an Ingress is silently ignored.","Annotations and ImplementationSpecific paths are not portable."],"cost":"A controller to run, upgrade and patch, a pressing choice now that ingress-nginx is retired, plus a certificate per host.","family":"kubernetes","flow":["Run a controller","Pick its IngressClass","Route by host and path","Read 404 versus 503"],"ratings":[],"strengths":["One entry point and one load balancer for many HTTP Services.","Hosts, paths and TLS live next to the app in plain YAML."]},"hint":"The nginx page means the controller replied, not the app. Would an unmatched host produce a 503, or a different status?","id":"k8s.ingress","introduction":"A LoadBalancer per Service is expensive and knows nothing about HTTP. An Ingress describes HTTP routing, meaning hosts, paths and TLS, for many Services at once, and an ingress controller turns that description into proxy configuration. Without a controller an Ingress object does nothing at all.","nuance":"ingress-nginx answers 404 when no rule matches and 503 when a rule matches but its Service is missing or has no ready endpoints. / still works, so the host rule exists: check kubectl get endpoints api.","objective":"Write an Ingress with host and path rules for an IngressClass, route two Services behind one entry point, and tell a controller 404 from a controller 503.","question":"After a deploy, curl -H \"Host: shop.local\" http://localhost/api returns an nginx-branded 503 page, while / on the same host still works. What is the most likely state of the cluster?","references":["https://kubernetes.io/docs/concepts/services-networking/ingress/","https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/","https://kubernetes.io/blog/2025/11/11/ingress-nginx-retirement/","https://gateway-api.sigs.k8s.io/"],"reviewAnswer":"Rule matched; its Service has no ready endpoints","reviewPrompt":"Ingress controller answers 503?","sections":[{"body":"An Ingress is only data in the API server. A controller such as ingress-nginx, Traefik, HAProxy or a cloud load balancer controller watches Ingresses of its class and configures a proxy, which is itself exposed by a LoadBalancer or NodePort Service, or on kind by host ports 80 and 443. An IngressClass names the controller in spec.controller; an Ingress picks a class with spec.ingressClassName, and the annotation ingressclass.kubernetes.io/is-default-class marks the class used when that field is empty. An Ingress for a class that no controller watches is accepted and silently ignored. The Ingress API is stable but frozen, and new routing features go into the Gateway API. The community ingress-nginx controller, which the lab runs and many tutorials use, was retired in March 2026 and no longer receives security fixes.","title":"The resource and the controller"},{"body":"Each rule matches one host, or every host when host is omitted, and lists paths, each with a backend Service name and port. The controller proxies to the Service's endpoints, usually straight to pod IPs, bypassing kube-proxy. The backend port is the Service port, not the container port, and the Service must live in the Ingress's namespace. Requests keep their path: /api/orders reaches the api Service as /api/orders, so the application must serve under that prefix unless you configure a controller-specific rewrite. A host may be a wildcard that covers exactly one DNS label, such as *.shop.example.com.","code":"apiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: shop\nspec:\n  ingressClassName: nginx\n  rules:\n  - host: shop.local\n    http:\n      paths:\n      - path: /api\n        pathType: Prefix\n        backend:\n          service:\n            name: api\n            port:\n              number: 80\n      - path: /\n        pathType: Prefix\n        backend:\n          service:\n            name: web\n            port:\n              number: 80","language":"yaml","title":"Host and path rules","walkthrough":"One host, shop.local, with two paths: /api goes to the api Service on port 80 and everything else goes to web. Listing /api first only helps the reader, because the controller orders paths by length itself, so / never swallows /api. Both backends are named by Service and Service port, so moving pods or changing container ports never touches the Ingress."},{"body":"Prefix matches whole path elements split by slashes: /api matches /api, /api/ and /api/orders, but not /apiv2. Exact matches a single path, and /api does not match /api/. ImplementationSpecific leaves matching to the controller, which ingress-nginx treats as a prefix or, with an annotation, a regular expression; such manifests are less portable. When several paths match, the longest wins, and Exact beats Prefix at the same length, whatever the order in the YAML. A request that matches no rule goes to spec.defaultBackend if the Ingress sets one, and otherwise to the controller's built-in default backend, which for ingress-nginx answers 404.","title":"pathType: Prefix, Exact and ImplementationSpecific"},{"body":"spec.tls lists hosts and a Secret of type kubernetes.io/tls, holding tls.crt and tls.key, in the Ingress's namespace. The controller terminates TLS: it presents the certificate that matches the SNI name, decrypts, and forwards plain HTTP to the pods, which learn the original scheme from X-Forwarded-Proto. ingress-nginx also redirects HTTP to HTTPS for TLS hosts by default. cert-manager is the usual way to issue and renew these Secrets from Let's Encrypt or an internal CA. If the Secret is missing or does not cover the host, clients get the controller's self-signed fallback certificate, a classic cause of certificate errors right after a deploy. The lab has no TLS: it stores the tls section but serves plain HTTP on port 80 only.","code":"apiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: shop-tls\nspec:\n  ingressClassName: nginx\n  tls:\n  - hosts:\n    - shop.example.com\n    secretName: shop-example-com-tls\n  rules:\n  - host: shop.example.com\n    http:\n      paths:\n      - path: /\n        pathType: Prefix\n        backend:\n          service:\n            name: web\n            port:\n              number: 80","language":"yaml","title":"TLS termination","walkthrough":"The tls entry ties the host shop.example.com to the Secret shop-example-com-tls, and the rule below routes the same host; the host must appear in both places. Create the Secret with kubectl create secret tls NAME --cert=tls.crt --key=tls.key, or let cert-manager create and renew it from an annotation on the Ingress."},{"body":"An nginx-branded 404 page comes from the controller: no rule matched the Host header and path, or the Ingress uses a class this controller ignores. A plain 404 from the application, such as \"404 page not found\" from a Go server, means routing worked and the app does not serve that path, often because the prefix was not stripped. A 503 from the controller means a rule matched but its Service does not exist or has no ready endpoints. A 502 means the controller could not get a response from the pod, for example because of a wrong targetPort, and a 504 means the pod accepted the request but answered too slowly. The status code tells you what failed; the page body tells you who answered.","code":"curl -s -o /dev/null -w '%{http_code}\\n' -H 'Host: shop.local' http://localhost/api/orders\nkubectl get ingress shop\nkubectl get endpoints api web","language":"bash","title":"404 or 503: reading the controller's answers","walkthrough":"The first command prints only the status code, which is handy in scripts and loops. get ingress shows the class and the address the controller published; an empty ADDRESS usually means no controller has picked the Ingress up. get endpoints for both backends separates a 503 caused by no ready pods from one caused by a missing Service."},{"body":"Create a cluster with ingress-nginx, run gopherforge/web and an http-echo pod that plays the API, and route shop.local/ and shop.local/api through one Ingress. The lab's controller listens on localhost port 80, and curl -H 'Host: ...' chooses the virtual host, as you would against a real load balancer before DNS exists. Then send a request for a host no rule knows, and finally scale the API to zero to see the 503.","code":"cluster create --ingress\nkubectl get ingressclass\nkubectl create deployment web --image=gopherforge/web:v1 --replicas=2 --port=8080\nkubectl expose deployment web --port=80 --target-port=8080\nkubectl create deployment api --image=hashicorp/http-echo -- /http-echo -text=orders-api\nkubectl expose deployment api --port=80 --target-port=5678\ncat > shop-ingress.yaml <<'EOF'\napiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: shop\nspec:\n  ingressClassName: nginx\n  rules:\n  - host: shop.local\n    http:\n      paths:\n      - path: /api\n        pathType: Prefix\n        backend:\n          service:\n            name: api\n            port:\n              number: 80\n      - path: /\n        pathType: Prefix\n        backend:\n          service:\n            name: web\n            port:\n              number: 80\nEOF\nkubectl apply -f shop-ingress.yaml\nkubectl rollout status deploy/api\nkubectl get ingress shop\ncurl -s -H 'Host: shop.local' http://localhost/\ncurl -s -H 'Host: shop.local' http://localhost/api/orders\ncurl -s -H 'Host: blog.local' http://localhost/\nkubectl scale deploy/api --replicas=0\ncurl -s -H 'Host: shop.local' http://localhost/api/orders\nkubectl get endpoints api","language":"bash","title":"Try it in the lab terminal","walkthrough":"get ingressclass shows the class nginx with controller k8s.io/ingress-nginx, and get ingress shop lists HOSTS shop.local and ADDRESS localhost. With Host: shop.local, / answers \"gopherforge web v1 served by web-<hash>-<id>\" and /api/orders answers \"orders-api\" from http-echo. Host: blog.local matches no rule and gets nginx's \"404 Not Found\" page. Scaling api to zero leaves the rule in place but empties its endpoints, so the same request now gets \"503 Service Temporarily Unavailable\" from nginx, and get endpoints api shows <none>."}],"takeaway":"An Ingress is routing data; the controller of its IngressClass does the work. The longest matching path wins, Prefix matches whole path elements, and the error page tells you which hop failed: an nginx 404 means no rule matched, an nginx 503 means the rule matched but no ready pods back it.","title":"Ingress: route HTTP by host and path through an ingress controller","unitID":"k8s-networking","wrongAnswers":["No Ingress rule matches the host shop.local","The api container itself answered with HTTP 503"]},{"conceptTag":"k8s.network-policies","designGuide":{"cautions":["A CNI that does not enforce accepts policies and ignores them.","Egress deny without a DNS rule breaks every name lookup."],"cost":"A policy per flow, a CNI that enforces them, and a negative test whenever a policy changes.","family":"kubernetes","flow":["Default deny per namespace","Allow DNS egress","Allow each flow by label","Prove it with a timeout"],"ratings":[],"strengths":["Labels, not IPs, define who may talk, so rules survive churn.","Default deny limits what a compromised pod can reach."]},"hint":"Look at the from entry: it has a podSelector but no namespaceSelector. Which namespace are the matching pods taken from?","id":"k8s.network-policies","introduction":"Out of the box every pod can connect to every other pod in every namespace, so one compromised pod can reach your database. NetworkPolicies restrict that with allow-lists that the network plugin enforces. The rules are simple but not intuitive: there are no deny rules, and a policy changes the behaviour of the pods it selects, not of the sources it names.","nuance":"A from podSelector without a namespaceSelector matches pods in the policy's namespace only. Add a namespaceSelector in the same from item, such as kubernetes.io/metadata.name: web, to admit that namespace's frontends.","objective":"Isolate pods with NetworkPolicies, allow traffic by pod label, namespace and IP block, build a default-deny baseline that keeps DNS working, and verify enforcement from a client pod.","question":"A policy allows role=frontend pods into app=api pods. A frontend pod in another namespace, also labelled role=frontend, still times out. Why?","references":["https://kubernetes.io/docs/concepts/services-networking/network-policies/","https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/","https://github.com/kubernetes-sigs/kind/releases/tag/v0.24.0","https://network-policy-api.sigs.k8s.io/"],"reviewAnswer":"Pods in the policy's own namespace only","reviewPrompt":"Scope of a from podSelector alone?","sections":[{"body":"A pod that no NetworkPolicy selects is non-isolated: all traffic in and out is allowed. As soon as one policy with Ingress in its policyTypes selects a pod, that pod is isolated for ingress, and only connections allowed by at least one of the selecting policies get in. Egress works the same way for outgoing connections. Policies only add allowances: there are no deny rules and no ordering, and the union of all matching policies is what is allowed. Reply packets of an allowed connection always pass. A connection between two pods needs both ends to agree, egress from the source and ingress to the destination. Blocking one source while allowing everyone else needs cluster-scoped policies from the Network Policy API project or CNI-specific resources.","title":"Default allow, isolation and additive rules"},{"body":"This policy selects the pods labelled app=api and allows TCP 8080 only from pods labelled role=frontend in the same namespace; every other connection to api is dropped. Policies act on pod traffic after kube-proxy has translated the Service address, so ports lists the container port 8080, not the Service port 80, a very common mistake. Dropped packets are not rejected: clients see a connection timeout rather than connection refused, a useful signature when debugging. Source labels are evaluated continuously, so labelling or relabelling a pod changes what it may reach within moments, without restarting anything.","code":"apiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: api-allow-frontend\nspec:\n  podSelector:\n    matchLabels:\n      app: api\n  policyTypes:\n  - Ingress\n  ingress:\n  - from:\n    - podSelector:\n        matchLabels:\n          role: frontend\n    ports:\n    - protocol: TCP\n      port: 8080","language":"yaml","title":"An allow-list for one app","walkthrough":"The top-level podSelector chooses the protected pods; the from entry chooses who may connect. policyTypes: [Ingress] makes the intent explicit and leaves egress alone. A from podSelector without a namespaceSelector only matches pods in the policy's own namespace, so a role=frontend pod in another namespace is still blocked."},{"body":"Inside one from entry, a namespaceSelector and a podSelector together mean AND: pods with these labels in namespaces with those labels. Written as two separate list items they mean OR, which opens far more than intended, and the YAML differs by a single dash. Every namespace carries the label kubernetes.io/metadata.name with its own name, set by the API server, so you can select a namespace by name without labelling it yourself; an empty namespaceSelector {} means every namespace. ipBlock allows CIDR ranges, with optional except entries, and is meant for addresses outside the cluster, such as an office network. Pod IPs are ephemeral, and source NAT by a load balancer or by externalTrafficPolicy: Cluster may replace the client address you expected to match.","code":"apiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: api-allow-monitoring\nspec:\n  podSelector:\n    matchLabels:\n      app: api\n  policyTypes:\n  - Ingress\n  ingress:\n  - from:\n    - namespaceSelector:\n        matchLabels:\n          kubernetes.io/metadata.name: monitoring\n      podSelector:\n        matchLabels:\n          app: prometheus\n    ports:\n    - port: 8080","language":"yaml","title":"podSelector, namespaceSelector and ipBlock","walkthrough":"namespaceSelector and podSelector sit in the same list item, under one dash, so only pods labelled app=prometheus in the monitoring namespace may connect. Put a dash before podSelector and the rule would admit every pod in monitoring plus every app=prometheus pod in the api's own namespace."},{"body":"A namespace baseline usually starts with one policy whose podSelector is {}, selecting every pod, and no allow rules, which isolates every pod in the namespace; each app then gets small allow policies on top. Egress isolation catches people out: a pod that may not send to kube-dns cannot resolve any name, so every call fails with a DNS error long before it reaches the policy you meant to test. The baseline below therefore allows UDP and TCP 53 to the CoreDNS pods. Put defaults in place when a namespace is created; adding deny-all to a running namespace breaks every flow nobody wrote down. The GopherForge lab stores egress rules but enforces only ingress rules, so practise egress on a real cluster.","code":"apiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: default-deny-all\nspec:\n  podSelector: {}\n  policyTypes:\n  - Ingress\n  - Egress\n  egress:\n  - to:\n    - namespaceSelector:\n        matchLabels:\n          kubernetes.io/metadata.name: kube-system\n      podSelector:\n        matchLabels:\n          k8s-app: kube-dns\n    ports:\n    - protocol: UDP\n      port: 53\n    - protocol: TCP\n      port: 53","language":"yaml","title":"Default deny, egress and DNS","walkthrough":"One policy, two effects. podSelector {} with both policyTypes isolates every pod in the namespace in both directions, and with no ingress rules nothing may connect in. The single egress rule allows DNS to pods labelled k8s-app=kube-dns in kube-system over UDP and TCP, because large answers fall back to TCP. Every other connection now needs its own allow policy, on the client side and on the server side."},{"body":"The API server validates and stores NetworkPolicies but enforces nothing. The CNI plugin does, by programming iptables, nftables or eBPF on every node. Calico, Cilium and Antrea enforce policies; Flannel on its own does not, and on such a cluster a policy is accepted and has no effect, which is dangerous because it looks like protection. Managed clusters often need enforcement switched on explicitly, through a network policy option or add-on. kind has enforced standard NetworkPolicies out of the box since v0.24 through the kube-network-policies project, and the GopherForge lab models that enforcement for ingress rules. Always prove a policy with a negative test, a connection that must fail, and not only with one that must succeed.","title":"The network plugin does the enforcing"},{"body":"Run two api pods, which are gopherforge/web listening on 8080, and a curl client pod without any role label. Call the api before any policy exists, apply the allow-list from above and watch the same call time out, then give the client the label role=frontend and call again. Nothing restarts along the way: the policy and the label change, and the decision follows them. --max-time 5 keeps the blocked call from hanging.","code":"kind create cluster\nkubectl create deployment api --image=gopherforge/web:v1 --replicas=2 --port=8080\nkubectl expose deployment api --port=80 --target-port=8080\nkubectl run client --image=curlimages/curl -- sleep 3600\nkubectl rollout status deploy/api\nkubectl wait --for=condition=Ready pod/client\nkubectl exec client -- curl -sS --max-time 5 http://api/version\ncat > api-policy.yaml <<'EOF'\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: api-allow-frontend\nspec:\n  podSelector:\n    matchLabels:\n      app: api\n  policyTypes:\n  - Ingress\n  ingress:\n  - from:\n    - podSelector:\n        matchLabels:\n          role: frontend\n    ports:\n    - protocol: TCP\n      port: 8080\nEOF\nkubectl apply -f api-policy.yaml\nkubectl get networkpolicy\nkubectl exec client -- curl -sS --max-time 5 http://api/version\nkubectl label pod client role=frontend\nkubectl exec client -- curl -sS --max-time 5 http://api/version\nkubectl get pods --show-labels","language":"bash","title":"Try it in the lab terminal","walkthrough":"Before any policy the client gets v1 from http://api/version. After the apply, get networkpolicy lists api-allow-frontend with POD-SELECTOR app=api, and the same curl ends with \"curl: (28) Connection timed out after 5001 milliseconds\": the packets are dropped, not refused. kubectl label pod client role=frontend changes only the source's labels, not the policy, and the next curl prints v1 again. get pods --show-labels shows role=frontend,run=client on the client and no role label on the api pods."}],"takeaway":"Pods are open until a policy selects them; after that only the union of the allow rules gets through. Start namespaces with default deny plus DNS egress, write ports as container ports, and prove every policy with a connection that must time out.","title":"NetworkPolicies: default deny and label-based allow-lists for pod traffic","unitID":"k8s-networking","wrongAnswers":["Policies take effect only after the pods restart","The api pods must also carry role=frontend"]},{"conceptTag":"k8s.traffic-debugging","designGuide":{"cautions":["Readiness does not catch a version that is ready and wrong.","CPU limits throttle pods long before they report errors."],"cost":"Load tests and dashboards for p99, errors and saturation, plus the discipline to roll back before debugging.","family":"kubernetes","flow":["Scope the symptom","Walk name, entry, endpoints","Check load: p99 and CPU","Recent rollout? Undo first"],"ratings":[],"strengths":["A fixed order finds most faults in a few commands.","Refused, timeout, 404, 503 and 500 each point at a hop."]},"hint":"Latency and CPU are normal, so this is not saturation, and every pod is Ready. What changed at the moment the errors started?","id":"k8s.traffic-debugging","introduction":"\"The site is down\" can mean a failure at any hop: DNS, the Ingress, the Service, its endpoints, pod readiness, the container port or the code. Each hop fails with its own signature, and the fastest debugging walks the path in order instead of guessing. This lesson builds that order and practises it on a Service under load.","nuance":"A steady error rate that starts with a rollout, with normal latency and saturation, points at the new version. Ready pods keep getting traffic, so undo the rollout first and debug the image afterwards.","objective":"Follow a request from client to container port, read latency, saturation and error signals under load, and fix an overloaded Service and a bad release with scaling and kubectl rollout undo.","question":"Right after a rollout, about 25% of requests return HTTP 500 while latency and CPU look normal and all pods are Ready. What should you do first?","references":["https://kubernetes.io/docs/tasks/debug/debug-application/debug-service/","https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-back-a-deployment","https://kubernetes.io/docs/concepts/configuration/liveness-readiness-startup-probes/","https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-usage-monitoring/"],"reviewAnswer":"kubectl rollout undo, then investigate","reviewPrompt":"Errors began with a rollout?","sections":[{"body":"From outside, a request resolves a public name, reaches a load balancer or node port, and enters the ingress controller, which matches host and path, picks a pod from the Service's endpoints and connects to that pod's IP and container port. From inside, a pod resolves the Service name through CoreDNS and connects to the ClusterIP, and kube-proxy on its own node rewrites the destination to a ready pod. Every hop has a typical failure: NXDOMAIN for a wrong name or namespace, an nginx 404 when no rule matches, an nginx 503 or connection refused when there are no ready endpoints, refused despite endpoints for a wrong targetPort, a timeout for a NetworkPolicy or a dead node, and 5xx from the code itself.","title":"The path of one request"},{"body":"Three signals describe a service under load. Latency: watch the p99, not only the median, because queueing hits the tail first. Saturation: how close each pod is to its limit; a container at its CPU limit is throttled by the kernel's CFS quota, so it slows down long before it fails, and kubectl top pods shows usage pinned near the limit. Errors: the share of 5xx responses, timeouts and refused connections. Under growing load they move in a typical order: p99 climbs, then the median, then errors appear as queues overflow and the app or a proxy sheds load with 503. A bad release looks different: latency and saturation stay normal, and errors sit at a steady percentage from the moment the new pods became ready.","title":"Latency, saturation and errors"},{"body":"In the GopherForge lab terminal, traffic run sends simulated requests from a client inside the cluster while virtual time advances, so controllers, probes and rollouts keep working during the run. Each row covers one interval: REQ/S is the offered rate per second, OK, 5XX and FAILED count the requests of that interval, P50 and P99 are latencies, and READY PODS is ready over all endpoints behind the Service. The summary splits responses by status, shows how requests spread over pods and prints hints. FAILED means no HTTP answer at all, a refused or timed-out connection, which points at endpoints, ports or policies rather than at the code. Load tools for real clusters, such as k6, hey or vegeta, report the same quantities.","code":"traffic run svc/web --rps 400 --duration 20s\nkubectl top pods","language":"bash","title":"Reading traffic run","walkthrough":"Against one pod with a 250m CPU limit, the first interval shows 400 OK and 400 503, and from +4s every row shows 0 OK and 800 503 with P50 around 233ms while READY PODS stays 1/1. The pod is ready and saturated, not broken. The summary reads \"Total 8000 requests · 5.0% ok\" and suggests kubectl top pods, which shows the pod at 240m of its 250m limit."},{"body":"A rolling update replaces pods while traffic flows. The readiness probe decides when a new pod joins the endpoints, so with a probe on a real readiness endpoint no connection reaches a container that is still starting; without a probe, a pod counts as ready as soon as its process starts. maxSurge and maxUnavailable, 25% each by default, bound how much capacity is in flight, so size replicas to carry the load with one pod missing. Requests and limits matter for traffic too: the CPU limit caps how much each pod can serve before it saturates, and the request is what the scheduler and an HPA reason about. Readiness only protects against pods that are not ready; a version that is ready and wrong still gets its share of the traffic.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - name: http\n          containerPort: 8080\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: http\n          periodSeconds: 2\n        resources:\n          requests:\n            cpu: 250m\n          limits:\n            cpu: 250m\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector:\n    app: web\n  ports:\n  - port: 80\n    targetPort: http","language":"yaml","title":"Readiness keeps a rollout clean under load","walkthrough":"The Deployment starts with one replica, a CPU request and limit of 250m, and a readiness probe on /readyz every two seconds through the named port http. The Service uses targetPort: http, so the port number lives in one place. This is the starting point of the lab: deliberately one small pod, so that saturation is easy to see."},{"body":"Walk the path in order and stop at the first surprise. 1. Scope: one client or all, one path or all, since when, and what changed, from kubectl rollout history and recent events. 2. Name: nslookup from a pod in the caller's namespace. 3. Entry: through an Ingress, an nginx 404 means no rule and a 503 means no ready endpoints. 4. Service: kubectl get endpoints; empty means selector or readiness, a wrong port means targetPort. 5. Pods: readiness, restarts, events and logs. 6. Policy: timeouts instead of refusals suggest a NetworkPolicy or a dead node. 7. Load: kubectl top pods and the p99; saturated pods need more replicas or an HPA. 8. Release: errors that start with a rollout mean kubectl rollout undo first and investigation second.","code":"kubectl get pods -l app=web -o wide\nkubectl get endpoints web\nkubectl describe svc web\nkubectl get events --types=Warning\nkubectl logs deploy/web --tail=20\nkubectl top pods\nkubectl rollout history deploy/web","language":"bash","title":"A triage checklist","walkthrough":"Run these top to bottom against the web Deployment: pods and their nodes, the endpoints the Service really uses, the port mapping, warning events, recent logs, CPU usage against limits, and the revision history that rollout undo walks back through. Most incidents are explained before the last line."},{"body":"Start from the single small pod above and send it 400 requests per second, more than a 250m CPU limit can serve. Confirm the saturation with kubectl top, scale out, then roll out v2 under the same load and watch readiness keep errors at zero. Then ship gopherforge/web:v2-bug, which fails a quarter of its requests while passing every probe, read the error signature, and roll it back.","code":"kind create cluster\ncat > web.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - name: http\n          containerPort: 8080\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: http\n          periodSeconds: 2\n        resources:\n          requests:\n            cpu: 250m\n          limits:\n            cpu: 250m\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector:\n    app: web\n  ports:\n  - port: 80\n    targetPort: http\nEOF\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\ntraffic run svc/web --rps 400 --duration 20s\nkubectl top pods\nkubectl scale deploy/web --replicas=4\nkubectl rollout status deploy/web\nkubectl set image deploy/web web=gopherforge/web:v2\ntraffic run svc/web --rps 400 --duration 30s\nkubectl set image deploy/web web=gopherforge/web:v2-bug\ntraffic run svc/web --rps 400 --duration 30s\nkubectl rollout undo deploy/web\ntraffic run svc/web --rps 400 --duration 20s","language":"bash","title":"Try it in the lab terminal","walkthrough":"One pod at 400 req/s ends with \"Total 8000 requests · 5.0% ok\", mostly 503s, and kubectl top pods shows 240m against the 250m limit. With four replicas, the v2 rollout runs under the same load: READY PODS moves through 3/5 and 4/5 to 4/4 and the run reads \"Total 12000 requests · 100.0% ok\". The v2-bug rollout passes readiness, yet the 5XX column climbs to about a quarter of each interval and the run ends near 77.5% ok with \"500 2633\". After rollout undo the 500s fade as the bad pods drain, and the last rows show no errors."}],"takeaway":"Walk the request path in order: name, entry, endpoints, readiness, policy, load, release. Saturation shows as a rising p99 and 503s and is fixed with capacity; a bad release shows as a steady error rate from the rollout on and is fixed first with kubectl rollout undo.","title":"Debugging traffic end to end: latency, saturation, errors and rollbacks","unitID":"k8s-networking","wrongAnswers":["Scale the Deployment out to spread the load","Restart CoreDNS to clear stale Service records"]},{"conceptTag":"k8s.configmaps","designGuide":{"cautions":["Environment variables never change in a running container.","A missing ConfigMap or key blocks the container from starting."],"cost":"One more object per service, plus a deliberate rollout or a hashed name whenever its content changes.","family":"kubernetes","flow":["Create the ConfigMap","Reference it via env or volume","Validate config at startup","Roll pods when it changes"],"ratings":[],"strengths":["One image runs in every environment with different settings.","Mounted files refresh in place without restarting pods."]},"hint":"Ask when the kubelet resolves valueFrom for an environment variable, and whether anything in the pod template has changed since.","id":"k8s.configmaps","introduction":"A container image should be the same artifact in every environment; what differs between staging and production is configuration. A ConfigMap keeps that configuration in the cluster as key-value pairs that pods read as environment variables or as files. How a pod reads it decides what happens when the ConfigMap is missing and when it changes.","nuance":"Env values are resolved once, when a container is created. Editing the ConfigMap leaves the pod template unchanged, so nothing rolls. rollout restart changes a template annotation and replaces the pods; mounted files would refresh.","objective":"Store non-secret settings in a ConfigMap, consume them as environment variables or files, diagnose a missing ConfigMap or key, and roll pods so that they pick up a change.","question":"You change LOG_LEVEL in the ConfigMap that a Deployment reads through env valueFrom. An hour later its pods still log at info. What makes them use the new value?","references":["https://kubernetes.io/docs/concepts/configuration/configmap/","https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/","https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/","https://12factor.net/config"],"reviewAnswer":"Restart it, for example kubectl rollout restart","reviewPrompt":"Running pod, changed env value?","sections":[{"body":"A ConfigMap is a namespaced object with a data map of UTF-8 strings and an optional binaryData map for base64-encoded bytes. Keys may contain letters, digits, dashes, underscores and dots, so a key can be a variable name such as LOG_LEVEL or a file name such as app.yaml whose value is a whole file. The object is stored in etcd and limited to 1 MiB, and a pod can only reference ConfigMaps in its own namespace. ConfigMaps are not for credentials: anyone who can read the object sees every value, which is what Secrets are for. kubectl create configmap builds one from --from-literal, --from-file or --from-env-file; in Git you keep the manifest.","code":"apiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: api-config\ndata:\n  DATABASE_URL: postgres://app@db:5432/app\n  LOG_LEVEL: info\n  app.yaml: |\n    listen: :8080\n    features:\n      search: true","language":"yaml","title":"What a ConfigMap holds","walkthrough":"Two keys hold single values meant for environment variables. The app.yaml key uses a YAML block scalar (|), so its value is a multi-line file that a volume mount can turn into /etc/api/app.yaml. Nothing in the object says how it will be consumed; each pod that references it decides that."},{"body":"env with valueFrom.configMapKeyRef sets one variable from one key and lets you choose its name. envFrom imports every key of a ConfigMap as a variable, optionally with a prefix; it is convenient, but it hides which variables a container depends on, and a key someone adds later appears at the next container start without review. A configMap volume writes each key as a file under the mount path, or only the keys listed in items. Both env forms are resolved by the kubelet once, when the container is created. Mounted files behave differently: after the ConfigMap changes, the kubelet refreshes them in place, typically within a minute, by swapping a symlink so readers never see half a file. Files mounted with subPath are never refreshed.","code":"apiVersion: v1\nkind: Pod\nmetadata:\n  name: api\nspec:\n  containers:\n  - name: api\n    image: gopherforge/api:v1\n    env:\n    - name: DATABASE_URL\n      valueFrom:\n        configMapKeyRef:\n          name: api-config\n          key: DATABASE_URL\n    envFrom:\n    - configMapRef:\n        name: api-flags\n        optional: true\n    volumeMounts:\n    - name: config\n      mountPath: /etc/api\n      readOnly: true\n  volumes:\n  - name: config\n    configMap:\n      name: api-config\n      items:\n      - key: app.yaml\n        path: app.yaml","language":"yaml","title":"Three ways to consume it","walkthrough":"DATABASE_URL comes from one named key of api-config. envFrom adds every key of a second ConfigMap, api-flags, and optional: true lets the container start even when that ConfigMap does not exist. The volume projects only the app.yaml key, as the read-only file /etc/api/app.yaml; without items, every key would become a file in that directory."},{"body":"A pod is scheduled even if a ConfigMap it references does not exist; the failure appears on the node. For env and envFrom the kubelet cannot build the environment, so the container is never started: kubectl get pods shows CreateContainerConfigError, and the events say Error: configmap \"api-config\" not found, or couldn't find key DATABASE_URL in ConfigMap default/api-config when only the key is missing. For a volume the pod stays in ContainerCreating with FailedMount events such as MountVolume.SetUp failed for volume \"config\" : configmap \"api-files\" not found. Both recover on their own once the ConfigMap or key appears, because the kubelet keeps retrying. Mark a reference optional: true only when the application has a sensible default without it.","title":"When the ConfigMap or a key is missing"},{"body":"Because environment variables are fixed when the container is created, editing a ConfigMap changes nothing in running pods that read it through env. kubectl rollout restart deploy/api writes a kubectl.kubernetes.io/restartedAt annotation into the pod template, and that template change makes the Deployment roll out new pods, which read the current values. Many teams make the change explicit instead: Kustomize's configMapGenerator appends a hash of the content to the name, so new content means a new name, a changed pod template and an ordinary rollout that can also be rolled back. Setting immutable: true goes further. The API server rejects any change to its data, so a new version is a new object, and the kubelet stops watching it, which reduces API server load in large clusters.","code":"apiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: api-config-7d4f9c\nimmutable: true\ndata:\n  DATABASE_URL: postgres://app@db:5432/app\n  LOG_LEVEL: info","language":"yaml","title":"Changes need a rollout; immutable ConfigMaps make that explicit","walkthrough":"The suffix stands for a content hash, so the next version is another object rather than an edit. Pods keep the old values until their template points at the new name, and nothing can change an immutable ConfigMap underneath running pods. Delete an old version only when no ReplicaSet you might roll back to still references it."},{"body":"The twelve-factor rule is to read configuration from the environment and treat it as input that is validated at startup. A Go service should gather everything it needs into one struct, apply defaults only where a default is genuinely safe, and exit with a clear message when a required value is missing. Failing at startup is useful: Kubernetes shows it as CrashLoopBackOff with the reason in kubectl logs, and a rolling update with a broken configuration stalls because the new pods never become ready, while the old pods keep serving. Files from a ConfigMap volume suit structured configuration that is too large for variables; read them at startup and, if you reload them, watch the directory rather than the file because of the symlink swap.","code":"type Config struct {\n\tDatabaseURL string\n\tLogLevel    slog.Level\n\tAddr        string\n}\n\nfunc LoadConfig() (Config, error) {\n\tcfg := Config{LogLevel: slog.LevelInfo, Addr: \":8080\"}\n\tcfg.DatabaseURL = os.Getenv(\"DATABASE_URL\")\n\tif cfg.DatabaseURL == \"\" {\n\t\treturn cfg, errors.New(\"DATABASE_URL is required (set it from a ConfigMap or Secret)\")\n\t}\n\tif v, ok := os.LookupEnv(\"LOG_LEVEL\"); ok {\n\t\tif err := cfg.LogLevel.UnmarshalText([]byte(v)); err != nil {\n\t\t\treturn cfg, fmt.Errorf(\"LOG_LEVEL: %w\", err)\n\t\t}\n\t}\n\tif v := os.Getenv(\"ADDR\"); v != \"\" {\n\t\tcfg.Addr = v\n\t}\n\treturn cfg, nil\n}","language":"go","title":"Twelve-factor configuration in a Go service","walkthrough":"DATABASE_URL has no safe default, so its absence is an error, worded like the message the lab image prints. LOG_LEVEL is optional but must parse: slog.Level accepts names such as info and debug, and a typo fails startup instead of silently logging at the wrong level. main calls LoadConfig once, logs the error and exits with a non-zero status."},{"body":"Run gopherforge/api:v1 without any configuration and watch it crash, then give it a ConfigMap and confirm the variables inside the container. Finally change LOG_LEVEL and roll the Deployment so that the new value reaches the pods. cluster tick 20s advances the lab clock so the crash loop has time to show; on a real cluster you would simply wait. Read the log before fixing anything: the message names the missing variable.","code":"kind create cluster\nkubectl create deployment api --image=gopherforge/api:v1\ncluster tick 20s\nkubectl get pods\nkubectl logs deploy/api\nkubectl create configmap api-config --from-literal=DATABASE_URL=postgres://app@db:5432/app --from-literal=LOG_LEVEL=info\nkubectl set env deploy/api --from=configmap/api-config\nkubectl rollout status deploy/api\nkubectl exec deploy/api -- env\nkubectl logs deploy/api\nkubectl create configmap api-config --from-literal=DATABASE_URL=postgres://app@db:5432/app --from-literal=LOG_LEVEL=debug --dry-run=client -o yaml | kubectl apply -f -\nkubectl rollout restart deploy/api\nkubectl rollout status deploy/api\nkubectl exec deploy/api -- printenv LOG_LEVEL","language":"bash","title":"Try it in the lab terminal","walkthrough":"After 20 seconds api-<hash>-<id> is in CrashLoopBackOff with 2 restarts, and the log says err=\"DATABASE_URL is required (set it from a ConfigMap or Secret)\". set env --from=configmap/api-config changes the pod template, so a new pod rolls out; exec env lists DATABASE_URL and LOG_LEVEL=info, and the log now shows msg=\"connected\". The dry-run pipe into kubectl apply is a repeatable way to edit a ConfigMap (a real cluster also warns once that the object lacked apply's annotation). The running pod keeps info until rollout restart replaces it; printenv in the new pod prints debug."}],"takeaway":"ConfigMaps carry non-secret settings into pods as variables or files; env values are fixed when a container starts, so a change needs a rollout, while mounted files refresh in place. A missing ConfigMap or key holds the container in CreateContainerConfigError or FailedMount until it appears.","title":"ConfigMaps: settings for pods through env, envFrom and mounted files","unitID":"k8s-config","wrongAnswers":["Wait longer for the kubelet to resync the values","Apply the unchanged Deployment manifest again"]},{"conceptTag":"k8s.secrets","designGuide":{"cautions":["Base64 hides nothing from anyone with read access.","Pod creation and exec rights also expose Secrets."],"cost":"RBAC reviews, an encryption provider for etcd, and application code that never prints a credential.","family":"kubernetes","flow":["Create the Secret outside Git","Grant narrow RBAC","Mount as file or secretKeyRef","Encrypt etcd, redact logs"],"ratings":[],"strengths":["Credentials stay out of images and ConfigMaps.","Mounted Secrets rotate without rebuilding or restarting."]},"hint":"Encoding and encryption differ. Which one needs a key, and does encryption at rest change what the API server returns to an authorized reader?","id":"k8s.secrets","introduction":"Passwords, API tokens and TLS keys must not be baked into images or ConfigMaps. A Secret is the Kubernetes object for them, and it looks protected because its values appear as gibberish. That gibberish is base64, which anyone can decode; the real protection comes from who may read the object, how etcd stores it, and what your application does with the value.","nuance":"Base64 is reversible by anyone. Encryption at rest protects etcd files and backups, but the API server decrypts for every authorized request, so only RBAC on get, list and watch keeps the password from this user.","objective":"Create Secrets from literals or stringData, deliver them as variables or files, and name the controls that actually keep them confidential: RBAC, encryption at rest, external managers and careful logging.","question":"A developer has get on secrets in the production namespace. What keeps the database password in db-credentials from them?","references":["https://kubernetes.io/docs/concepts/configuration/secret/","https://kubernetes.io/docs/concepts/security/secrets-good-practices/","https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/","https://kubernetes.io/docs/tasks/inject-data-application/distribute-credentials-secure/"],"reviewAnswer":"Anyone with get on secrets: base64 is no key","reviewPrompt":"Who can read a Secret's value?","sections":[{"body":"A Secret is a namespaced object like a ConfigMap, with a type that tells tools which keys to expect: Opaque for arbitrary data, kubernetes.io/tls with tls.crt and tls.key, kubernetes.io/dockerconfigjson for image pull credentials, kubernetes.io/basic-auth, kubernetes.io/ssh-auth and the legacy kubernetes.io/service-account-token. Values under data are base64-encoded so that binary content such as a keystore survives JSON and YAML. That is encoding, not encryption: base64 -d reverses it without any key. kubectl create secret tls and kubectl create secret docker-registry build the typed variants on a real cluster; the GopherForge lab simulates only kubectl create secret generic. Like a ConfigMap, a Secret is limited to 1 MiB.","code":"echo -n 's3cr3t-Pa55' | base64\necho 'czNjcjN0LVBhNTU=' | base64 -d","language":"bash","title":"Secret types, and base64 as encoding","walkthrough":"The first line prints czNjcjN0LVBhNTU=. echo -n matters: without it the newline is encoded too, and a password with a trailing newline is a classic cause of authentication failures. The second line turns the value straight back into s3cr3t-Pa55, as anyone who can read the Secret can."},{"body":"In a manifest, stringData accepts plain text and the API server encodes it into data on write; when a key appears in both, stringData wins. That makes manifests easy to write and just as easy to leak: a Secret manifest committed to Git is a committed password. Keep real values out of the repository and create Secrets from a pipeline, from an encrypted form such as Sealed Secrets or SOPS that only the cluster or the pipeline can decrypt, or from an external secret manager. kubectl create secret generic --from-literal avoids a file on disk, but the value lands in your shell history; --from-file reads it from a file instead.","code":"apiVersion: v1\nkind: Secret\nmetadata:\n  name: db-credentials\ntype: Opaque\nstringData:\n  POSTGRES_USER: app\n  POSTGRES_PASSWORD: s3cr3t-Pa55","language":"yaml","title":"Writing Secrets declaratively","walkthrough":"After kubectl apply, kubectl get secret db-credentials -o yaml shows the values encoded under data, as YXBw and czNjcjN0LVBhNTU=, and no stringData field. On a real cluster, client-side kubectl apply also stores the whole manifest, plain text included, in the kubectl.kubernetes.io/last-applied-configuration annotation; kubectl apply --server-side does not."},{"body":"secretKeyRef works exactly like configMapKeyRef, including CreateContainerConfigError when the Secret or key is missing. Variables are convenient but travel far: child processes inherit them, crash reporters and debug endpoints dump them, and kubectl exec ... env prints them for anyone allowed to exec. A secret volume writes each key as a file on a tmpfs, so the value never touches the node's disk; defaultMode restricts the file permissions, and the kubelet refreshes the files when the Secret is rotated, unless they are mounted with subPath. Prefer files for credentials your code can reread, and variables for images that expect them, such as postgres. Many images also accept a _FILE variant, like POSTGRES_PASSWORD_FILE.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: db\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: db\n  template:\n    metadata:\n      labels:\n        app: db\n    spec:\n      containers:\n      - name: postgres\n        image: postgres:16\n        env:\n        - name: POSTGRES_PASSWORD\n          valueFrom:\n            secretKeyRef:\n              name: db-credentials\n              key: POSTGRES_PASSWORD\n        volumeMounts:\n        - name: creds\n          mountPath: /run/secrets/db\n          readOnly: true\n      volumes:\n      - name: creds\n        secret:\n          secretName: db-credentials\n          defaultMode: 0400","language":"yaml","title":"Environment variable or mounted file","walkthrough":"POSTGRES_PASSWORD is read from the db-credentials key once, at container start. The same Secret is mounted read-only at /run/secrets/db, one file per key, with mode 0400. kubectl describe pod shows the reference, not the value: <set to the key 'POSTGRES_PASSWORD' in secret 'db-credentials'>."},{"body":"RBAC decides. get on secrets reads one value, and list or watch return every Secret in the namespace with its data, so treat list as read access to all of them. Less obviously, anyone who can create pods or Deployments in a namespace can mount any Secret there and read it from inside the container, and anyone allowed to create pods/exec can print the environment of running pods. By default the API server writes Secrets to etcd unencrypted, so etcd backups contain them too; an EncryptionConfiguration with a KMS v2 provider encrypts them at rest with a key held outside the cluster. External Secrets Operator or the Secrets Store CSI Driver fetch values from Vault or a cloud secret manager, which then owns rotation and auditing.","title":"Who can read a Secret"},{"body":"Most leaks are not attacks; they are log lines. A startup message that prints the whole configuration, an error that wraps a connection string, or a panic that dumps a struct all end up in a log system that far more people can read than the Secret. In Go, url.URL.Redacted replaces the password in a URL, and a small type that implements fmt.Stringer and slog.LogValuer makes the safe output the default wherever the value is printed. Errors leak too: url.Parse quotes its input in the error text, so logging that error logs the password. The lab's gopherforge/api image follows this rule: when it logs its database URL, asterisks replace the password.","code":"// Secret holds a credential and never prints it.\ntype Secret string\n\nfunc (Secret) String() string       { return \"[REDACTED]\" }\nfunc (Secret) LogValue() slog.Value { return slog.StringValue(\"[REDACTED]\") }\n\nfunc logDatabase(logger *slog.Logger, raw string) {\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\tlogger.Error(\"DATABASE_URL is not a valid URL\") // err would echo raw\n\t\treturn\n\t}\n\tlogger.Info(\"connecting\", \"database\", u.Redacted())\n}","language":"go","title":"Keep secrets out of logs","walkthrough":"A Secret value prints as [REDACTED] through fmt's %s and %v and through slog; code that needs the credential converts it explicitly with string(s). logDatabase logs postgres://app:xxxxx@db:5432/app via Redacted, and on a parse error logs a fixed message instead of err, whose text would contain the whole input."},{"body":"Start postgres:16 without a password and read why it crashes, then create a Secret and decode it yourself to see how little base64 hides. Wire the Secret into the Deployment with kubectl set env, let the rollout replace the crashing pod, and read the variable from inside the container. The last two commands ask the authorizer what the namespace's default ServiceAccount may do with Secrets and with exec, which is the access that matters.","code":"kind create cluster\nkubectl create deployment db --image=postgres:16\ncluster tick 20s\nkubectl get pods\nkubectl logs deploy/db\nkubectl create secret generic db-credentials --from-literal=POSTGRES_PASSWORD='s3cr3t-Pa55'\nkubectl get secret db-credentials -o yaml\nkubectl get secret db-credentials -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d\nkubectl set env deploy/db --from=secret/db-credentials\nkubectl rollout status deploy/db\nkubectl logs deploy/db\nkubectl exec deploy/db -- printenv POSTGRES_PASSWORD\nkubectl auth can-i get secrets --as=system:serviceaccount:default:default\nkubectl auth can-i create pods/exec --as=system:serviceaccount:default:default","language":"bash","title":"Try it in the lab terminal","walkthrough":"db-<hash>-<id> is in CrashLoopBackOff, and its log says You must specify POSTGRES_PASSWORD to a non-empty value for the superuser. The Secret's YAML shows type Opaque and POSTGRES_PASSWORD: czNjcjN0LVBhNTU=, and the jsonpath and base64 -d pipe prints s3cr3t-Pa55 with no key at all. After set env and the rollout, the log ends with database system is ready to accept connections, and printenv prints the password in clear text: exec access is secret access. The last two checks print no, because the default ServiceAccount may neither get Secrets nor exec into pods."}],"takeaway":"A Secret is a namespaced object whose base64 values anyone with read access can decode. Protect it with narrow RBAC on get, list, watch, pod creation and exec, encryption at rest, values kept out of Git and logs, and file mounts where the application can read them.","title":"Secrets: credentials for pods, and why base64 is not protection","unitID":"k8s-config","wrongAnswers":["The base64 encoding, which needs the cluster key","Encryption at rest, which kubectl cannot reverse"]},{"conceptTag":"k8s.volumes-pvc","designGuide":{"cautions":["The Delete reclaim policy erases data with the claim.","ReadWriteOnce volumes cannot be shared across nodes."],"cost":"Provisioned disks cost money until their claims, and with Retain their PVs, are deleted.","family":"kubernetes","flow":["Pick a lifetime: pod or beyond","Choose class and access mode","Claim storage with a PVC","Check the reclaim policy"],"ratings":[],"strengths":["Pods request storage without knowing the backend.","Claims and their data survive pod replacement."]},"hint":"Read the claim's events, not only the pod's. Which object must exist before a provisioner can create a volume for a claim?","id":"k8s.volumes-pvc","introduction":"Everything a container writes to its own filesystem disappears when the container is replaced. Volumes give pods storage with a defined lifetime: some last as long as the pod, others outlive every pod that ever used them. Most storage incidents come from not knowing which lifetime you asked for, or from a claim that can never be bound.","nuance":"Dynamic provisioning needs the StorageClass the claim names. If it does not exist the claim stays Pending with ProvisioningFailed, and the scheduler cannot place a pod whose claim is unbound. Fix storageClassName or create the class.","objective":"Choose between ephemeral and persistent volumes, request storage with a PersistentVolumeClaim, read binding and provisioning status, and diagnose a pod stuck Pending on its claim.","question":"A pod stays Pending with \"pod has unbound immediate PersistentVolumeClaims\", and its claim shows ProvisioningFailed events. What is the likely cause?","references":["https://kubernetes.io/docs/concepts/storage/volumes/","https://kubernetes.io/docs/concepts/storage/persistent-volumes/","https://kubernetes.io/docs/concepts/storage/storage-classes/","https://kubernetes.io/docs/concepts/storage/dynamic-provisioning/"],"reviewAnswer":"The claim names a StorageClass that does not exist","reviewPrompt":"PVC event: class not found?","sections":[{"body":"A container's writable layer is discarded when the container restarts, so a crash loop also wipes every file it wrote. An emptyDir volume is created empty when the pod is assigned to a node, survives container restarts, is shared by all containers in the pod, and is deleted when the pod leaves the node for any reason. It suits caches, scratch space and files handed from an init container or sidecar to the main container. medium: Memory puts it on tmpfs, which is fast but counts against the containers' memory limits, and sizeLimit lets the kubelet evict a pod whose emptyDir grows too large. None of this survives the pod being replaced or rescheduled; for that you need a PersistentVolume.","title":"Ephemeral storage: the container layer and emptyDir"},{"body":"A PersistentVolume (PV) is a cluster-scoped object that represents real storage: a cloud disk, an NFS export, a directory on a node. A PersistentVolumeClaim (PVC) is a namespaced request for storage with a size and an access mode, and a pod refers only to the claim. A StorageClass names a provisioner and its parameters. With dynamic provisioning, a claim that names a class makes the provisioner create a matching PV, and the two are bound one to one. A claim without storageClassName gets the default class, marked by the storageclass.kubernetes.io/is-default-class annotation, while storageClassName: \"\" opts out and binds only to a pre-created PV. kind installs one default class, standard, backed by the local-path provisioner.","code":"apiVersion: storage.k8s.io/v1\nkind: StorageClass\nmetadata:\n  name: retained\nprovisioner: rancher.io/local-path\nreclaimPolicy: Retain\nvolumeBindingMode: WaitForFirstConsumer\n---\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: reports\nspec:\n  storageClassName: retained\n  accessModes: [\"ReadWriteOnce\"]\n  resources:\n    requests:\n      storage: 2Gi","language":"yaml","title":"PersistentVolume, PersistentVolumeClaim and StorageClass","walkthrough":"The class uses kind's local-path provisioner but keeps volumes after their claim is deleted. The claim asks that class for 2Gi of ReadWriteOnce storage. Because of WaitForFirstConsumer it stays Pending until a pod that uses it is scheduled; only then is a PV created on that pod's node and bound to the claim."},{"body":"Access modes describe how a volume may be attached, not file permissions. ReadWriteOnce (RWO) allows read-write mounting by one node, so several pods on that node can share it; ReadOnlyMany (ROX) allows many nodes to mount it read-only; ReadWriteMany (RWX) needs a shared filesystem such as NFS, CephFS or a cloud file service; ReadWriteOncePod (RWOP) restricts the volume to a single pod in the whole cluster and works only with CSI drivers. Block-storage classes usually offer RWO only. The reclaim policy decides what happens to a dynamically provisioned PV when its claim is deleted: Delete removes the volume and its data, while Retain keeps both and moves the PV to Released, where an administrator must recover or clean up the data before the storage is reused.","title":"Access modes and reclaim policy"},{"body":"With volumeBindingMode: Immediate a volume is provisioned as soon as the claim exists, possibly in a zone or on a node where the pod can never run. WaitForFirstConsumer delays provisioning until the scheduler has placed a pod that uses the claim, so the volume is created where that pod lands; until then the claim is Pending with the event waiting for first consumer to be created before binding, which is normal. Abnormal cases have recognisable messages. A pod whose claim does not exist fails scheduling with persistentvolumeclaim \"data\" not found. A claim that names a missing StorageClass collects ProvisioningFailed events, and its pod reports pod has unbound immediate PersistentVolumeClaims. A claim still used by a pod keeps the kubernetes.io/pvc-protection finalizer and stays Terminating until that pod is gone.","title":"WaitForFirstConsumer and claims stuck Pending"},{"body":"A StatefulSet's volumeClaimTemplates create one claim per replica, named from the template, the set and the ordinal: data-cache-0, data-cache-1. When cache-0 is replaced or rescheduled it gets the same claim and therefore the same data back. By default neither deleting the pods nor deleting the StatefulSet removes these claims, which protects a database from a careless delete and also leaves storage you keep paying for. persistentVolumeClaimRetentionPolicy, stable since Kubernetes 1.32, can set whenDeleted and whenScaled to Delete for data that is disposable. Scaling down and back up with the default Retain reattaches the existing claims.","code":"apiVersion: apps/v1\nkind: StatefulSet\nmetadata:\n  name: cache\nspec:\n  serviceName: cache\n  replicas: 2\n  selector:\n    matchLabels:\n      app: cache\n  persistentVolumeClaimRetentionPolicy:\n    whenDeleted: Retain\n    whenScaled: Delete\n  template:\n    metadata:\n      labels:\n        app: cache\n    spec:\n      containers:\n      - name: redis\n        image: redis:7\n        volumeMounts:\n        - name: data\n          mountPath: /data\n  volumeClaimTemplates:\n  - metadata:\n      name: data\n    spec:\n      accessModes: [\"ReadWriteOnce\"]\n      resources:\n        requests:\n          storage: 1Gi","language":"yaml","title":"StatefulSet claims outlive their pods","walkthrough":"Each replica gets its own 1Gi claim from the default class, mounted at /data: data-cache-0 and data-cache-1. whenScaled: Delete removes the claim of a replica that a scale-down removes, while whenDeleted: Retain keeps every claim if the StatefulSet itself is deleted, so recreating the set finds its data again."},{"body":"Inspect the StorageClass kind installs, then apply a claim together with a pod that uses it, plus an emptyDir for scratch files. A second claim names a StorageClass that does not exist, so its pod cannot be scheduled; read the events of both objects to see where each part of the problem is reported. Finally delete the pod and then the claim, and watch what the Delete reclaim policy does to the volume.","code":"kind create cluster\nkubectl get storageclass\ncat > data.yaml <<'EOF'\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: data\nspec:\n  accessModes: [\"ReadWriteOnce\"]\n  resources:\n    requests:\n      storage: 1Gi\n---\napiVersion: v1\nkind: Pod\nmetadata:\n  name: writer\nspec:\n  containers:\n  - name: app\n    image: busybox\n    command: [\"sleep\", \"3600\"]\n    volumeMounts:\n    - name: data\n      mountPath: /data\n    - name: scratch\n      mountPath: /tmp/scratch\n  volumes:\n  - name: data\n    persistentVolumeClaim:\n      claimName: data\n  - name: scratch\n    emptyDir: {}\nEOF\nkubectl apply -f data.yaml\nkubectl wait --for=condition=Ready pod/writer\nkubectl get pvc,pv\ncat > fast.yaml <<'EOF'\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: fast-data\nspec:\n  storageClassName: fast-ssd\n  accessModes: [\"ReadWriteOnce\"]\n  resources:\n    requests:\n      storage: 5Gi\n---\napiVersion: v1\nkind: Pod\nmetadata:\n  name: fast-writer\nspec:\n  containers:\n  - name: app\n    image: busybox\n    command: [\"sleep\", \"3600\"]\n    volumeMounts:\n    - name: data\n      mountPath: /data\n  volumes:\n  - name: data\n    persistentVolumeClaim:\n      claimName: fast-data\nEOF\nkubectl apply -f fast.yaml\ncluster tick 10s\nkubectl events --for pvc/fast-data\nkubectl events --for pod/fast-writer\nkubectl delete pod writer\nkubectl get pvc data\nkubectl delete pvc data\ncluster tick 30s\nkubectl get pv","language":"bash","title":"Try it in the lab terminal","walkthrough":"get storageclass shows standard (default), provisioner rancher.io/local-path, reclaim policy Delete and WaitForFirstConsumer. Once writer is Ready, get pvc,pv shows data Bound to a generated pvc-<uid> volume of 1Gi, RWO, claimed by default/data. fast-writer stays Pending: the claim's events say ProvisioningFailed, storageclass.storage.k8s.io \"fast-ssd\" not found, and the pod's say pod has unbound immediate PersistentVolumeClaims. Deleting writer leaves the claim Bound, because claims outlive pods. Deleting the claim lets the Delete policy remove the volume, so the last command prints No resources found."}],"takeaway":"Use emptyDir for data that may vanish with the pod and a PersistentVolumeClaim for data that must outlive it. Check the StorageClass, access mode and reclaim policy before relying on a volume, and read the claim's events when a pod stays Pending.","title":"Volumes and persistent storage: emptyDir, PersistentVolumeClaims and StorageClasses","unitID":"k8s-config","wrongAnswers":["The node has no disk space left for the image","Another pod already holds the ReadWriteOnce volume"]},{"conceptTag":"k8s.namespaces-quotas","designGuide":{"cautions":["Namespaces do not isolate network traffic by default.","Deleting a namespace deletes every object in it."],"cost":"A namespace template per team, with RBAC, quota, LimitRange and policies, kept in Git and applied consistently.","family":"kubernetes","flow":["Namespace per team or env","RoleBinding for the team","Quota plus LimitRange","Guard namespace deletion"],"ratings":[],"strengths":["Teams reuse names without colliding.","RBAC, quotas and policies attach at one boundary."]},"hint":"Namespaces own the objects inside them. What is the namespace controller doing while a namespace shows Terminating?","id":"k8s.namespaces-quotas","introduction":"One cluster usually serves several teams, services and environments, and all of them want a Deployment called web. Namespaces give each group its own space for names, permissions and policies. They are not a security boundary on their own and some objects ignore them entirely, so it pays to know exactly what they divide.","nuance":"Deletion cascades: the namespace turns Terminating, the namespace controller deletes every object in it, and the namespace disappears once empty. Bound PVs follow their reclaim policy, so with Delete the data goes too.","objective":"Use namespaces to scope names, access and policy, tell which objects are cluster-wide, cap a team's consumption with ResourceQuota and LimitRange, and delete a namespace knowing what goes with it.","question":"You run kubectl delete namespace staging. What happens to the Deployments, Secrets and PersistentVolumeClaims inside it?","references":["https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/","https://kubernetes.io/docs/concepts/policy/resource-quotas/","https://kubernetes.io/docs/concepts/policy/limit-range/","https://kubernetes.io/docs/tasks/administer-cluster/namespaces/"],"reviewAnswer":"All deleted; Terminating until the namespace is empty","reviewPrompt":"Delete a namespace: its objects?","sections":[{"body":"A namespaced object's name only has to be unique within its namespace and kind, so team-a/web and team-b/web are different Deployments. Roles and RoleBindings grant access within one namespace, NetworkPolicies select pods in it, ResourceQuotas and LimitRanges apply to it, and Services get DNS names that include it, such as web.team-b.svc.cluster.local. Pods can reach Services in other namespaces by those names, because namespaces do not isolate the network unless NetworkPolicies say so. kubectl works in the namespace of your current context, default unless you changed it; -n picks another and -A lists across all of them. A new cluster has default, kube-system, kube-public and kube-node-lease, and kind adds local-path-storage. Keep your workloads out of default and kube-system.","title":"What a namespace scopes"},{"body":"Some kinds describe the cluster itself and have no namespace: Nodes, PersistentVolumes, StorageClasses, IngressClasses, Namespaces, ClusterRoles, ClusterRoleBindings, PriorityClasses and CustomResourceDefinitions. kubectl ignores -n for them, and access to them needs a ClusterRole granted through a ClusterRoleBinding. That is why a PersistentVolumeClaim belongs to a namespace while the PV it binds does not, and why a team allowed to create StorageClasses can affect every other team. kubectl api-resources prints every kind with a NAMESPACED column, and kubectl api-resources --namespaced=false on a real cluster lists only the cluster-scoped ones. When you design per-team access, list these kinds explicitly and decide who may change each of them.","title":"What is not namespaced"},{"body":"A ResourceQuota caps what one namespace may consume in total: the sums of CPU and memory requests and limits, requested storage, and object counts such as pods, services or persistentvolumeclaims. The quota admission plugin checks every create and rejects a pod that would exceed it with Forbidden: exceeded quota. Once a quota tracks requests.cpu or limits.memory, every new pod must declare those values or it is rejected too. Because a Deployment's pods are created by its ReplicaSet, the rejection appears as FailedCreate events on the ReplicaSet while the Deployment itself was accepted, a classic source of confusion. On a real cluster kubectl describe quota shows used against hard for each resource. In the GopherForge lab terminal ResourceQuota is enforced for pods, CPU and memory, as the admission plugin does.","code":"apiVersion: v1\nkind: ResourceQuota\nmetadata:\n  name: team-a-quota\n  namespace: team-a\nspec:\n  hard:\n    requests.cpu: \"4\"\n    requests.memory: 8Gi\n    limits.cpu: \"8\"\n    limits.memory: 16Gi\n    pods: \"50\"\n    persistentvolumeclaims: \"10\"\n    requests.storage: 100Gi","language":"yaml","title":"ResourceQuota: a budget per namespace","walkthrough":"team-a may request 4 CPUs and 8Gi of memory in total, with twice that in limits, and run 50 pods with 10 claims totalling 100Gi. Only pods that have not finished count, so a completed Job frees its share. Size a quota from expected load plus headroom for rolling updates, which briefly run extra pods."},{"body":"A LimitRange constrains individual containers, pods or claims in one namespace. For containers it sets default limits and defaultRequest values that admission fills in when a manifest omits them, min and max bounds that reject outliers, and optionally a maxLimitRequestRatio. Together with a quota it means a developer who forgets resources still gets a pod that fits the budget instead of a Forbidden error. Defaults apply only when a pod is created; changing a LimitRange never touches running pods. The GopherForge lab terminal fills in LimitRange defaults for new containers; practise its min and max bounds on a real cluster.","code":"apiVersion: v1\nkind: LimitRange\nmetadata:\n  name: container-defaults\n  namespace: team-a\nspec:\n  limits:\n  - type: Container\n    defaultRequest:\n      cpu: 100m\n      memory: 128Mi\n    default:\n      cpu: 500m\n      memory: 256Mi\n    max:\n      cpu: \"2\"\n      memory: 2Gi","language":"yaml","title":"LimitRange: defaults and bounds per container","walkthrough":"A container in team-a without resources gets requests of 100m CPU and 128Mi and limits of 500m and 256Mi. A container whose limit exceeds 2 CPUs or 2Gi is rejected at admission with a message that names the maximum."},{"body":"A common layout gives each team, or each team and environment, its own namespace with a RoleBinding for the team, a quota, a LimitRange and default-deny NetworkPolicies, all generated from one template so every team looks the same. Labels on namespaces, such as team=payments, let NetworkPolicies and admission policies select them. Deleting a namespace deletes everything in it: Deployments, Services, Secrets and PVCs, and through the reclaim policy possibly the data. The namespace shows Terminating while the namespace controller removes its contents, and it can hang there when an object carries a finalizer whose controller is gone or an aggregated API is unavailable; the namespace's status conditions name the cause. Grant delete on namespaces to very few people.","title":"Per-team namespaces, and deleting one"},{"body":"Create two team namespaces and deploy a Deployment with the same name into both, then look across namespaces with -A and a label selector. Switch the default namespace of your kubeconfig context so that commands without -n go to team-a. Finally delete team-b without waiting, catch it in the Terminating state, advance the lab clock and confirm that its Deployment and pods went with it.","code":"kind create cluster\nkubectl get namespaces\nkubectl create namespace team-a\nkubectl create namespace team-b\nkubectl create deployment web --image=nginx -n team-a\nkubectl create deployment web --image=nginx:1.27 --replicas=2 -n team-b\nkubectl rollout status deploy/web -n team-b\nkubectl get pods -A -l app=web\nkubectl get pods\nkubectl config set-context --current --namespace=team-a\nkubectl get deploy\nkubectl delete namespace team-b --wait=false\nkubectl get ns team-b\ncluster tick 30s\nkubectl get ns team-b\nkubectl get pods -A -l app=web","language":"bash","title":"Try it in the lab terminal","walkthrough":"get namespaces lists default, kube-node-lease, kube-public, kube-system and local-path-storage. Both namespaces accept a Deployment named web, and get pods -A -l app=web shows one pod in team-a and two in team-b in a NAMESPACE column, while a plain get pods answers No resources found in default namespace. After set-context, get deploy without -n lists team-a's web. --wait=false returns at once, so get ns team-b catches STATUS Terminating; 30 seconds later it reports namespaces \"team-b\" not found, and only team-a's pod is left."}],"takeaway":"Namespaces scope names, RBAC, policies and quotas, but not nodes, PVs, StorageClasses or cluster roles, and not the network by default. Give each team a namespace with a quota and a LimitRange, and treat deleting a namespace as deleting everything in it.","title":"Namespaces, ResourceQuotas and LimitRanges: dividing one cluster between teams","unitID":"k8s-config","wrongAnswers":["They are moved into the default namespace","The delete is refused while objects remain"]},{"conceptTag":"k8s.rbac","designGuide":{"cautions":["list on secrets, pod create and exec reveal Secrets.","ClusterRoleBindings grant rights in every namespace."],"cost":"A ServiceAccount, Role and RoleBinding per workload, reviewed whenever the code starts calling a new API.","family":"kubernetes","flow":["One ServiceAccount per workload","Role with only needed verbs","RoleBinding in its namespace","Verify with auth can-i --as"],"ratings":[],"strengths":["A leaked token can do only what its Role lists.","auth can-i turns permissions into testable checks."]},"hint":"Look at where the RoleBinding lives. In which namespaces can a RoleBinding grant anything, even when its roleRef is a ClusterRole?","id":"k8s.rbac","introduction":"Every request to the API server, from kubectl or from a controller running in a pod, is first authenticated to an identity and then authorized against rules. Role-based access control (RBAC) is how you write those rules. Done well, a compromised pod or a leaked kubeconfig can do little; done badly, everything quietly runs as cluster-admin.","nuance":"RBAC is additive and namespaced: a binding in shop grants nothing in orders. Add a RoleBinding in orders, to the same ClusterRole if you want to reuse it; RBAC changes apply on the next request, no restart needed.","objective":"Tell authentication from authorization, grant a ServiceAccount exactly the verbs it needs with a Role and RoleBinding, verify the result with kubectl auth can-i, and call the API from Go with the pod's own identity.","question":"A controller running as ServiceAccount shop:inventory gets \"forbidden\" listing pods in namespace orders, though its RoleBinding in shop grants list on pods. Why?","references":["https://kubernetes.io/docs/reference/access-authn-authz/rbac/","https://kubernetes.io/docs/concepts/security/service-accounts/","https://kubernetes.io/docs/concepts/security/rbac-good-practices/","https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/"],"reviewAnswer":"Only the RoleBinding's own namespace","reviewPrompt":"Scope of a RoleBinding's rights?","sections":[{"body":"Authentication answers who is calling. Kubernetes has no User object: people arrive with a client certificate, whose CN is the user name and whose O fields are groups, or with an OIDC token from an identity provider. kind writes a certificate for kubernetes-admin into your kubeconfig, and kubectl auth whoami shows it. Workloads use ServiceAccounts, namespaced objects the API server does store; a pod runs as one, default unless serviceAccountName says otherwise, and receives a short-lived, audience-bound token under /var/run/secrets/kubernetes.io/serviceaccount that the kubelet refreshes. Its user name is system:serviceaccount:NAMESPACE:NAME. Authorization then decides whether that identity may perform this verb on this resource; in kind the Node and RBAC authorizers decide, and admission control runs only after a request is authorized.","title":"Authentication, then authorization"},{"body":"A Role holds rules for one namespace; a ClusterRole has the same shape but is cluster-scoped, so it can cover nodes and other cluster-wide kinds or be reused in many namespaces. Each rule names apiGroups (\"\" is the core group with pods, services and secrets; apps holds deployments), resources including subresources such as pods/log and pods/exec, optional resourceNames, and verbs: get, list, watch, create, update, patch, delete and deletecollection. Rules only add permissions; there is no deny, so anything not granted is refused. Some grants are stronger than they look: list on secrets returns their values, create on pods lets a user run any image as any ServiceAccount of the namespace, and the escalate, bind and impersonate verbs let a subject climb past its own rights.","code":"apiVersion: rbac.authorization.k8s.io/v1\nkind: Role\nmetadata:\n  name: pod-reader\n  namespace: shop\nrules:\n- apiGroups: [\"\"]\n  resources: [\"pods\", \"pods/log\"]\n  verbs: [\"get\", \"list\", \"watch\"]\n- apiGroups: [\"apps\"]\n  resources: [\"deployments\"]\n  resourceNames: [\"inventory\"]\n  verbs: [\"get\"]","language":"yaml","title":"Roles: verbs on resources","walkthrough":"The first rule lets the subject read pods and their logs in shop, including watch, which client-go informers need. The second allows get on the one Deployment named inventory and on nothing else. Names cannot restrict create or deletecollection, and they restrict list or watch only when the request filters on metadata.name."},{"body":"A RoleBinding grants a Role, or a ClusterRole, to subjects inside its own namespace; binding a ClusterRole this way is how one definition, such as the built-in view or edit role, is reused namespace by namespace. A ClusterRoleBinding grants a ClusterRole in every namespace and on cluster-scoped resources, which an application rarely needs. Subjects are users, groups or ServiceAccounts, and a ServiceAccount subject must name its namespace. roleRef cannot be changed after creation, so you delete and recreate a binding to point it elsewhere. Changes take effect on the next request; nothing has to restart.","code":"apiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n  name: inventory-pod-reader\n  namespace: shop\nsubjects:\n- kind: ServiceAccount\n  name: inventory\n  namespace: shop\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: Role\n  name: pod-reader","language":"yaml","title":"Bindings connect subjects to roles","walkthrough":"The binding lives in shop, so it grants permissions only there, even if roleRef named a ClusterRole. Its subject is the inventory ServiceAccount of shop. kubectl create rolebinding inventory-pod-reader --role=pod-reader --serviceaccount=shop:inventory -n shop creates the same object."},{"body":"Give each workload its own ServiceAccount with no permissions, then add only the verbs its code calls. kubectl auth can-i asks the authorizer directly and exits with status 0 for yes and 1 for no, so it works in scripts and CI. --as=system:serviceaccount:shop:inventory impersonates the ServiceAccount, which needs the impersonate permission cluster admins have. A missing verb shows up in the application as a 403: pods is forbidden: User \"system:serviceaccount:shop:inventory\" cannot list resource \"pods\" in API group \"\" in the namespace \"orders\". Pods that never call the API should set automountServiceAccountToken: false, so a compromised container has no token to steal. Never grant to broad groups such as system:authenticated or system:serviceaccounts, and review who holds cluster-admin, secrets access and pods/exec.","title":"Least privilege, checked with kubectl auth can-i"},{"body":"Inside a pod, client-go's rest.InClusterConfig builds a configuration from the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT variables, the mounted CA certificate and the token file, which it rereads so that rotated tokens keep working. The program then has exactly the rights of its ServiceAccount, set with serviceAccountName in the pod template. Read the pod's namespace from the mounted namespace file instead of hard-coding it, and treat a 403 as a deployment error that deserves a clear log line: it means the Role lacks a verb, not that the cluster is down, and retrying will not help.","code":"import (\n\t\"context\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\n\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/rest\"\n)\n\nconst nsFile = \"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"\n\nfunc listPods(ctx context.Context) error {\n\tcfg, err := rest.InClusterConfig() // token, CA and API address of this pod\n\tif err != nil {\n\t\treturn err // not running in a pod\n\t}\n\tcs, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tns, err := os.ReadFile(nsFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpods, err := cs.CoreV1().Pods(string(ns)).List(ctx, metav1.ListOptions{})\n\tif apierrors.IsForbidden(err) {\n\t\treturn fmt.Errorf(\"ServiceAccount may not list pods: %w\", err)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range pods.Items {\n\t\tslog.Info(\"pod\", \"name\", p.Name, \"phase\", p.Status.Phase)\n\t}\n\treturn nil\n}","language":"go","title":"A Go service with its ServiceAccount","walkthrough":"InClusterConfig fails outside a cluster, the signal to fall back to a kubeconfig during local development. The List call is exactly what the pod-reader Role allows, so it succeeds in shop. apierrors.IsForbidden separates an RBAC problem from network or server errors, so the log names the missing permission instead of the program retrying forever."},{"body":"Check which identity your kubeconfig uses, create a ServiceAccount that has no permissions, and ask the authorizer about it with kubectl auth can-i --as. Grant it get and list on pods in its own namespace with a Role and a RoleBinding, then ask again about listing, deleting, another namespace and Secrets. Finally run a Deployment whose pods use that ServiceAccount, the identity a client-go program inside them would have.","code":"kind create cluster\nkubectl auth whoami\nkubectl create namespace shop\nkubectl create serviceaccount inventory -n shop\nkubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:inventory\nkubectl create role pod-reader --verb=get,list --resource=pods -n shop\nkubectl create rolebinding inventory-pod-reader --role=pod-reader --serviceaccount=shop:inventory -n shop\nkubectl get role pod-reader -n shop -o yaml\nkubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:inventory\nkubectl auth can-i delete pods -n shop --as=system:serviceaccount:shop:inventory\nkubectl auth can-i list pods -n default --as=system:serviceaccount:shop:inventory\nkubectl auth can-i get secrets -n shop --as=system:serviceaccount:shop:inventory\ncat > inventory.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: inventory\n  namespace: shop\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: inventory\n  template:\n    metadata:\n      labels:\n        app: inventory\n    spec:\n      serviceAccountName: inventory\n      containers:\n      - name: inventory\n        image: busybox\n        command: [\"sleep\", \"3600\"]\nEOF\nkubectl apply -f inventory.yaml\nkubectl get pods -n shop -o custom-columns=NAME:.metadata.name,SERVICEACCOUNT:.spec.serviceAccountName","language":"bash","title":"Try it in the lab terminal","walkthrough":"auth whoami prints Username kubernetes-admin, the certificate identity kind created for you. The new ServiceAccount starts with no rights, so the first can-i prints no and exits with status 1. The Role's YAML shows one rule: apiGroups \"\", resources pods, verbs get and list. can-i then prints yes for list pods in shop, and no for delete pods, for list pods in default and for get secrets in shop. The pod inventory-<hash>-<id> shows SERVICEACCOUNT inventory, so a client-go program inside it would get exactly these answers."}],"takeaway":"Authentication establishes who is calling; RBAC decides what that identity may do, through additive rules bound per namespace. Give each workload its own ServiceAccount, grant only the verbs its code uses, and prove it with kubectl auth can-i --as.","title":"RBAC: ServiceAccounts, Roles and bindings for least-privilege API access","unitID":"k8s-config","wrongAnswers":["ServiceAccounts may never read other namespaces","The pod must restart before new rules apply"]},{"conceptTag":"k8s.debugging-pods","designGuide":{"cautions":["Events expire after an hour, so collect them early.","The current log of a restarting container hides the crash; use --previous."],"cost":"A minute of reading per pod, plus log and event retention that outlives the pods themselves.","family":"kubernetes","flow":["get: read STATUS and READY","describe: Events at the bottom","logs --previous for crashes","exec and events to confirm"],"ratings":[],"strengths":["The same five commands diagnose almost every pod failure.","Waiting reasons and exit codes narrow the cause before you read any code."]},"hint":"The container you can read now is a new instance that has not crashed yet. Ask which flag reads the log of the instance before it.","id":"k8s.debugging-pods","introduction":"A broken pod always says why, but the answer is spread over its status, its events, the logs of the current and the previous container, and the state inside it. Opening the logs first misses pods that never started, and exec cannot reach a container that keeps restarting. A fixed triage order finds the cause in minutes and works the same during an incident at 3 a.m.","nuance":"The kubelet keeps the log of the previous container instance; kubectl logs --previous prints it, panic included. The current log belongs to a fresh container, and exec cannot enter a container that is not running.","objective":"Find out why a pod is not working by reading its STATUS, the Events in describe, the current and previous logs, the container from inside and the namespace events, and fix the most common failures.","question":"A pod is in CrashLoopBackOff, and kubectl logs shows only a startup line from the container that is waiting to restart. Which command shows the output of the run that crashed?","references":["https://kubernetes.io/docs/tasks/debug/debug-application/debug-pods/","https://kubernetes.io/docs/tasks/debug/debug-application/determine-reason-pod-failure/","https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/","https://kubernetes.io/docs/reference/kubectl/generated/kubectl_events/"],"reviewAnswer":"kubectl logs POD --previous","reviewPrompt":"Why did a crashed container die?","sections":[{"body":"kubectl get pods computes STATUS from the pod phase and the state of its containers, so it names the most specific problem it can find. Pending means the pod is not scheduled yet or its images are not pulled; ContainerCreating means volumes and images are being prepared. ErrImagePull, ImagePullBackOff and CreateContainerConfigError are waiting reasons: the container never started. CrashLoopBackOff, Error and OOMKilled describe a container that started and then ended. Running only says that a process exists; READY 0/1 means a readiness probe is failing and Services send the pod no traffic. RESTARTS counts how often the kubelet restarted a container and when it last did, as in \"2 (12s ago)\". Add -o wide for the node and pod IP: several broken pods on one node point at the node, not at the application.","title":"What the STATUS column is telling you"},{"body":"Work from the outside in. get tells you which pods are affected and how. describe shows each container's State and Last State with Reason and Exit Code, its probes and mounts, and at the bottom the Events: scheduling, image pulls, probe failures and back-offs, oldest first. logs prints what the current container wrote; when the container is restarting, --previous prints the run that crashed, which is usually the one you need. exec runs a command in a running container to check environment variables, files and DNS from the pod's point of view. events --for lists the events of one object with their age, and events --types=Warning shows every warning in the namespace at once. The API server keeps events for one hour by default, so read them early.","code":"kubectl get pods -o wide\nkubectl describe pod -l app=web\nkubectl logs deploy/web --tail=50\nkubectl logs deploy/web --previous\nkubectl exec deploy/web -- printenv\nkubectl events --for pod/needs-config\nkubectl events --types=Warning","language":"bash","title":"The triage order","walkthrough":"logs and exec accept deploy/web and pick one of the Deployment's pods, which saves copying generated names; describe accepts -l to describe every matching pod. On a real cluster, kubectl debug -it POD --image=busybox --target=web adds an ephemeral debugging container to a pod whose image has no shell, such as a distroless Go image; kubectl debug is not available in the lab terminal."},{"body":"Pending with a FailedScheduling event means no node passed the scheduler's filters, and the message counts why: \"0/3 nodes are available: 3 Insufficient cpu\" (lower the requests or add capacity), an untolerated taint, a nodeSelector or affinity that no node matches, or \"pod has unbound immediate PersistentVolumeClaims\" (check kubectl get pvc and its StorageClass). ErrImagePull is a failed pull; ImagePullBackOff is the kubelet waiting before the next try, up to five minutes apart. The Failed event says which problem you have: \"not found\" is a typo in the name or tag, \"unauthorized\" or \"pull access denied\" is a private registry without imagePullSecrets, and \"no match for platform\" is the wrong CPU architecture. CreateContainerConfigError means a referenced ConfigMap, Secret or key does not exist, or runAsNonRoot meets an image that runs as root. The kubelet keeps retrying, so creating the missing object fixes the pod without deleting it.","title":"Pods that never start"},{"body":"CrashLoopBackOff means the container keeps exiting and the kubelet waits 10 s, 20 s, 40 s and so on, up to five minutes, before each restart; the delay resets after ten minutes of clean running. While it waits, the current log may show nothing useful, so read --previous. Last State gives the exit code: 1 is an ordinary failure such as log.Fatal or os.Exit(1), 2 is an unrecovered Go panic, 137 is 128 + 9, a SIGKILL, and 143 is 128 + 15, a SIGTERM the process obeyed. 137 with Reason OOMKilled means the container went over its memory limit: raise the limit, fix the leak, and set GOMEMLIMIT below the limit so the Go garbage collector works harder before the kernel kills the process. 137 without OOMKilled usually means a failed liveness probe or an expired grace period. Running with READY 0/1 is a failing readiness probe: the Unhealthy event names the probe and the status code it got.","title":"Pods that start and then fail"},{"body":"Break things on purpose, then diagnose each with the triage order: a Deployment whose image tag does not exist, one whose image panics at start, and a pod that reads an environment variable from a ConfigMap that nobody created. cluster tick 30s gives the kubelet time to retry and back off a few times. Then fix the two problems that configuration can fix, and confirm that the variable arrived inside the container.","code":"kind create cluster\nkubectl create deployment typo --image=nginx:1.99\nkubectl create deployment crash --image=gopherforge/web:v3-crash\ncat > needs-config.yaml <<'EOF'\napiVersion: v1\nkind: Pod\nmetadata:\n  name: needs-config\nspec:\n  containers:\n  - name: app\n    image: gopherforge/web:v2\n    env:\n    - name: LOG_LEVEL\n      valueFrom:\n        configMapKeyRef:\n          name: app-config\n          key: log-level\nEOF\nkubectl apply -f needs-config.yaml\ncluster tick 30s\nkubectl get pods\nkubectl describe pod -l app=typo\nkubectl logs deploy/crash --previous\nkubectl get pod -l app=crash -o jsonpath='{.items[0].status.containerStatuses[0].lastState.terminated.exitCode}'\nkubectl events --for pod/needs-config\nkubectl set image deploy/typo nginx=nginx:1.27\nkubectl create configmap app-config --from-literal=log-level=debug\nkubectl rollout status deploy/typo\nkubectl get pods\nkubectl exec needs-config -- printenv LOG_LEVEL","language":"bash","title":"Try it in the lab terminal","walkthrough":"After the tick, get pods shows crash-<hash>-<id> in CrashLoopBackOff with \"2 (12s ago)\", needs-config in CreateContainerConfigError and typo-<hash>-<id> in ImagePullBackOff. The typo pod's Events include Failed to pull image \"nginx:1.99\" ... not found. logs --previous prints the panic, a nil pointer dereference in main.loadConfig, and the exit code is 2, Go's code for a panic. events --for shows Error: configmap \"app-config\" not found (x6). After set image and the new ConfigMap, typo and needs-config run and printenv prints debug; crash stays broken until its code is fixed."}],"takeaway":"Read STATUS, then the Events at the bottom of describe, then logs --previous, then exec and events. Waiting reasons point at scheduling, images or configuration; exit codes and OOMKilled point at the process itself.","title":"Debug failing pods: get, describe, logs, exec and events in order","unitID":"k8s-operations","wrongAnswers":["kubectl logs POD --tail=1000, the longer current log","kubectl exec POD -- cat, the log file inside the pod"]},{"conceptTag":"k8s.autoscaling","designGuide":{"cautions":["Without CPU requests the HPA cannot scale at all.","Re-applying spec.replicas from CI fights the autoscaler."],"cost":"Accurate requests, a running metrics-server, and spare node capacity for the first minutes of a spike.","family":"kubernetes","flow":["Set CPU requests","Create HPA: target, min, max","Watch get hpa and its events","Tune behavior if needed"],"ratings":[],"strengths":["Replica count follows load without anyone running kubectl scale.","The formula is simple enough to predict and to review."]},"hint":"Utilization is a percentage. Ask what the HPA divides the measured usage by, and which field of the container spec supplies that number.","id":"k8s.autoscaling","introduction":"Load changes faster than anyone can run kubectl scale, and a fixed replica count is either too small at the peak or wasted at night. The HorizontalPodAutoscaler adjusts a Deployment's replica count from observed metrics. It only works when the pods declare CPU requests, metrics are flowing, and its reaction speed matches how fast the service can take on load.","nuance":"Utilization is usage divided by the CPU request. If a container in the targeted pods has no request, the HPA cannot compute a percentage, shows <unknown> and records FailedGetResourceMetric. Limits play no part.","objective":"Create an autoscaling/v2 HorizontalPodAutoscaler on CPU utilization, predict its replica count from the formula, tune how fast it scales up and down, and place the Vertical Pod Autoscaler and the cluster autoscaler next to it.","question":"You add an HPA with a 50% CPU target, and kubectl get hpa keeps showing cpu: <unknown>/50%, although kubectl top pods shows usage. What is missing?","references":["https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/","https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/","https://kubernetes.io/docs/concepts/workloads/autoscaling/"],"reviewAnswer":"A CPU request on every container in the pods","reviewPrompt":"CPU-based HPA needs what on pods?","sections":[{"body":"The kubelet measures CPU and memory per container. metrics-server collects them from every kubelet, every 15 seconds by default, and serves them through the resource metrics API, metrics.k8s.io, which kubectl top and the HPA read. kind does not install metrics-server: on a real kind cluster you apply its release manifest and add --kubelet-insecure-tls, while the GopherForge lab has it enabled. CPU utilization is usage divided by the pod's CPU request: a pod requesting 100m that uses 50m is at 50%, whatever its limit. If a container in the targeted pods has no CPU request, the HPA cannot compute a percentage: TARGETS shows cpu: <unknown>/50% and a FailedGetResourceMetric event says \"missing request for cpu in container web\". Custom and external metrics, such as queue length, need an adapter like Prometheus Adapter or KEDA.","title":"Where the numbers come from"},{"body":"Every 15 seconds the controller computes desiredReplicas = ceil(currentReplicas x currentUtilization / targetUtilization) and clamps it between minReplicas and maxReplicas. One pod using 240% of its request with a 50% target gives ceil(1 x 240 / 50) = 5. Five pods at 49% give ceil(4.9) = 5, and a ratio within the 10% tolerance changes nothing anyway, which prevents flapping. Pods without metrics are treated conservatively, as fully busy when scaling down and idle when scaling up, and pods that are not ready yet count as idle when scaling up. Scaling takes time, because metrics lag a scrape and new pods must pull, start and pass readiness, so keep headroom with a target of 50 to 70%. Do not set spec.replicas in a manifest that CI re-applies to an autoscaled Deployment: every apply resets the count the HPA chose.","title":"The formula and the 15-second loop"},{"body":"Without a behavior field the HPA scales up at once, adding at most 100% of the current replicas or 4 pods per 15 seconds, whichever is more. It scales down only to the highest recommendation of the last 300 seconds: the scale-down stabilization window, which stops it from removing pods during a short lull. behavior overrides each direction with a stabilizationWindowSeconds and a list of policies that limit change per period; selectPolicy picks the policy allowing the most change (Max, the default), the least (Min), or Disabled to forbid that direction. A service that starts slowly wants fast scale-up and gentle scale-down; a queue consumer may want both fast.","code":"apiVersion: autoscaling/v2\nkind: HorizontalPodAutoscaler\nmetadata:\n  name: web\nspec:\n  scaleTargetRef:\n    apiVersion: apps/v1\n    kind: Deployment\n    name: web\n  minReplicas: 2\n  maxReplicas: 10\n  metrics:\n  - type: Resource\n    resource:\n      name: cpu\n      target:\n        type: Utilization\n        averageUtilization: 60\n  behavior:\n    scaleDown:\n      stabilizationWindowSeconds: 120\n      policies:\n      - type: Percent\n        value: 50\n        periodSeconds: 60\n    scaleUp:\n      policies:\n      - type: Pods\n        value: 4\n        periodSeconds: 15","language":"yaml","title":"behavior: how fast up, how slowly down","walkthrough":"This HPA keeps 2 to 10 replicas at an average of 60% of the CPU request. It scales down only after the recommendation has stayed lower for 120 seconds, and then removes at most half of the pods per minute, rounded so that 5 pods become 3, then 2. Scale-up may add 4 pods every 15 seconds with no stabilization window. kubectl autoscale creates the same object without behavior."},{"body":"The Vertical Pod Autoscaler is a separate project in the kubernetes/autoscaler repository that you install with its own CRD. Its recommender watches usage history and computes requests for each container; its updater evicts pods whose requests are far from the recommendation; its admission webhook writes the recommended requests into pods as they are created. updateMode Off only publishes recommendations, a safe way to size requests for a new service; Initial applies them when pods are created; Recreate evicts pods to apply them; recent releases add InPlaceOrRecreate, which uses in-place pod resize, beta and enabled by default in Kubernetes 1.33 and 1.34. Do not let VPA and an HPA both act on the CPU or memory of the same pods: VPA raises requests, utilization drops, and the HPA removes pods.","title":"Vertical Pod Autoscaler"},{"body":"The HPA adds pods; something must add nodes for them. The cluster autoscaler watches for pods that stay Pending because no node has room, simulates the scheduler against each node group (a cloud auto scaling group or node pool), and grows a group whose new node would fit them. It removes a node when its pods' requests stay below half of its capacity for ten minutes and every pod can move elsewhere, respecting PodDisruptionBudgets; the annotation cluster-autoscaler.kubernetes.io/safe-to-evict: \"false\" on a pod keeps its node. It decides from requests, never from actual usage, so pods without requests make it blind. A new node takes minutes, so an HPA on top of a cluster autoscaler needs spare capacity for the first burst. Karpenter is an alternative that picks instance types per pending pod. The lab's nodes are fixed unless you run cluster node add.","title":"Cluster autoscaler"},{"body":"Give the Deployment a CPU request, attach an HPA with a 50% target, send 400 requests per second in the background and advance the clock to watch it scale up. Then stop the traffic and advance past the 300-second stabilization window to watch it scale back down. The --cpu=50% flag replaced --cpu-percent=50, which kubectl 1.34 deprecates; both create the same autoscaling/v2 object.","code":"kind create cluster\nkubectl create deployment web --image=gopherforge/web:v2\nkubectl set resources deploy/web --requests=cpu=100m,memory=64Mi --limits=memory=128Mi\nkubectl expose deploy/web --port=80 --target-port=8080\nkubectl autoscale deploy/web --cpu=50% --min=1 --max=8\nkubectl rollout status deploy/web\nkubectl get hpa\ntraffic start svc/web --rps 400\ncluster tick 2m\nkubectl get hpa\ntraffic status\nkubectl events --for hpa/web\ntraffic stop all\ncluster tick 6m\nkubectl get hpa\nkubectl events --for hpa/web","language":"bash","title":"Try it in the lab terminal","walkthrough":"Before the load, get hpa shows cpu: 1%/50% and 1 replica. Two minutes later it shows cpu: 49%/50% and 5 replicas, and the HPA's events hold one SuccessfulRescale: \"New size: 5; reason: cpu resource utilization (percentage of request) above target\". traffic status counts 6533 responses with status 503 among 48000: the single pod was overloaded until the new pods became ready. Six minutes after traffic stop, get hpa is back at 1 replica and a second event reads \"New size: 1; reason: ... below target\", about five minutes after the load ended."}],"takeaway":"An HPA scales on usage as a percentage of requests, so every container needs a CPU request. It scales up within seconds and down only after a 300-second window; set behavior when those defaults do not fit the service.","title":"Autoscale pods on CPU with the HorizontalPodAutoscaler, VPA and cluster autoscaler","unitID":"k8s-operations","wrongAnswers":["A CPU limit on every container in the pods","A Service that selects the Deployment's pods"]},{"conceptTag":"k8s.node-failures","designGuide":{"cautions":["Default failover takes about six minutes, and StatefulSet pods wait longer.","A budget that allows no disruption blocks every drain."],"cost":"Spare capacity of at least one node, replicas spread over nodes and zones, and a PodDisruptionBudget per service.","family":"kubernetes","flow":["Node misses heartbeats: NotReady","Taints added, pods not ready","Evicted after tolerationSeconds","Controller creates replacements"],"ratings":[],"strengths":["Controller-owned pods recover from node loss without a human.","PodDisruptionBudgets keep drains and upgrades within a safe pace."]},"hint":"The node is tainted within a minute. Ask what every pod carries that lets it stay on a node with that taint, and for how long.","id":"k8s.node-failures","introduction":"Nodes fail: a kernel panic, a lost network link, a cloud instance retired underneath you. Kubernetes recovers by itself, but after deliberate delays and only for pods that a controller owns. Planned maintenance takes a different path, the Eviction API, and that is where PodDisruptionBudgets decide how many pods may go at once.","nuance":"Admission gives every pod tolerations for the not-ready and unreachable NoExecute taints with tolerationSeconds: 300. Pods stay bound for five minutes after the taint, then are evicted and their ReplicaSet replaces them.","objective":"Explain the timeline from a lost node to rescheduled pods, protect planned maintenance with a PodDisruptionBudget, drain a node safely, and spread replicas so that one node or zone cannot take a service down.","question":"A worker node loses power. Its Deployment pods are replaced about six minutes later, not at once. What sets most of that delay?","references":["https://kubernetes.io/docs/concepts/architecture/nodes/","https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/","https://kubernetes.io/docs/concepts/workloads/pods/disruptions/","https://kubernetes.io/docs/tasks/administer-cluster/safely-drain-node/"],"reviewAnswer":"300 seconds, from the default NoExecute tolerations","reviewPrompt":"Unreachable node: pods stay?","sections":[{"body":"Each kubelet renews a Lease in the kube-node-lease namespace every 10 seconds as its heartbeat. The node lifecycle controller in kube-controller-manager checks every 5 seconds; when a node has not reported for the node monitor grace period, 50 seconds by default, it sets the node's Ready condition to Unknown with \"Kubelet stopped posting node status\", which kubectl shows as NotReady. It taints the node with node.kubernetes.io/unreachable twice: effect NoSchedule, so nothing new lands there, and effect NoExecute, which starts the eviction clock. It also marks the node's pods as not ready, so EndpointSlices drop them and Services stop routing to them. The control plane cannot tell a dead node from a network partition: the containers may still be running, and writing.","title":"From missed heartbeats to NotReady"},{"body":"The DefaultTolerationSeconds admission plugin gives every pod two tolerations, for node.kubernetes.io/not-ready and node.kubernetes.io/unreachable with effect NoExecute and tolerationSeconds: 300. So pods stay bound to a lost node for five minutes in case it comes back; then the taint eviction controller deletes them. The deletion cannot complete without the kubelet, so on a real cluster the old pod shows Terminating until the node returns or its Node object is deleted. A ReplicaSet does not count terminating pods and creates a replacement at once. A StatefulSet waits, because two pods with one identity could corrupt data; once you know the machine is off, the node.kubernetes.io/out-of-service taint releases its pods and volumes. A bare pod is simply gone. Shorter tolerationSeconds in a pod template give faster failover. The GopherForge lab evicts after 30 seconds; cluster config eviction=60s changes that.","title":"Taint-based eviction and the 300-second default"},{"body":"Draining a node for an upgrade, the cluster autoscaler removing a node, or rotating a node pool are voluntary disruptions. They evict pods through the Eviction API, which checks every PodDisruptionBudget that selects the pod. A PDB sets minAvailable or maxUnavailable, as a count or a percentage, and its status shows how many disruptions are allowed now. When an eviction would break the budget, the API refuses with 429 and \"Cannot evict pod as it would violate the pod's disruption budget\", and the caller retries later. A PDB does not protect against node failures, kubectl delete pod or a Deployment rollout, which has its own maxUnavailable. Two traps: minAvailable equal to the replica count, or maxUnavailable: 0, blocks every drain forever, and pods that are already unhealthy can block a drain unless unhealthyPodEvictionPolicy: AlwaysAllow lets them go.","code":"apiVersion: policy/v1\nkind: PodDisruptionBudget\nmetadata:\n  name: web\nspec:\n  maxUnavailable: 1\n  unhealthyPodEvictionPolicy: AlwaysAllow\n  selector:\n    matchLabels:\n      app: web","language":"yaml","title":"Voluntary disruptions and PodDisruptionBudgets","walkthrough":"maxUnavailable: 1 keeps working when the Deployment is scaled, unlike a fixed minAvailable that can end up equal to the replica count. kubectl get pdb shows MAX UNAVAILABLE 1 and ALLOWED DISRUPTIONS 1 while all pods are healthy. AlwaysAllow lets a drain evict pods that are running but not ready, which lose nothing by moving; the default, IfHealthyBudget, evicts them only while the budget is satisfied."},{"body":"kubectl cordon marks a node unschedulable: its STATUS becomes Ready,SchedulingDisabled and running pods stay. kubectl drain cordons the node and evicts every pod, honouring PodDisruptionBudgets and each pod's grace period, and retries refused evictions every 5 seconds. It stops without --ignore-daemonsets when DaemonSet pods are present, because their controller would put them straight back; --delete-emptydir-data accepts that emptyDir contents are lost; --force is needed for pods without a controller, which nothing will recreate. After maintenance, kubectl uncordon makes the node schedulable again. Kubernetes never moves running pods back by itself, so a recovered node fills up only as new pods are created; the descheduler project can rebalance.","code":"kubectl cordon kind-worker2\nkubectl drain kind-worker2 --ignore-daemonsets --delete-emptydir-data --timeout=120s\nkubectl get nodes\nkubectl uncordon kind-worker2","language":"bash","title":"Cordon, drain and uncordon","walkthrough":"Without --timeout, drain waits as long as a budget blocks it, which is how a cluster upgrade hangs at 3 a.m. With a timeout it fails, the node stays cordoned until someone looks, and the evictions it completed stay done. get nodes shows the drained node as Ready,SchedulingDisabled until uncordon."},{"body":"Three replicas on one node fail together. topologySpreadConstraints keep the number of matching pods per topology domain within maxSkew of each other: topologyKey kubernetes.io/hostname spreads across nodes, topology.kubernetes.io/zone across zones. whenUnsatisfiable: DoNotSchedule is a hard rule that leaves a pod Pending; ScheduleAnyway only prefers. By default node taints are ignored when counting, so a tainted control-plane node or a cordoned node counts as an empty domain and can block a hard rule; nodeTaintsPolicy: Honor leaves such nodes out. matchLabelKeys with pod-template-hash computes the spread per ReplicaSet, so the new pods of a rollout are spread too. Spreading happens only at scheduling time; Kubernetes itself never moves pods later when the balance drifts.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      tolerations:\n      - key: node.kubernetes.io/unreachable\n        operator: Exists\n        effect: NoExecute\n        tolerationSeconds: 60\n      - key: node.kubernetes.io/not-ready\n        operator: Exists\n        effect: NoExecute\n        tolerationSeconds: 60\n      topologySpreadConstraints:\n      - maxSkew: 1\n        topologyKey: kubernetes.io/hostname\n        whenUnsatisfiable: DoNotSchedule\n        nodeTaintsPolicy: Honor\n        matchLabelKeys:\n        - pod-template-hash\n        labelSelector:\n          matchLabels:\n            app: web\n      - maxSkew: 1\n        topologyKey: topology.kubernetes.io/zone\n        whenUnsatisfiable: ScheduleAnyway\n        labelSelector:\n          matchLabels:\n            app: web\n      containers:\n      - name: web\n        image: gopherforge/web:v2","language":"yaml","title":"Spread replicas across nodes and zones","walkthrough":"The hard hostname rule puts the three replicas on three different workers, and the soft zone rule prefers different zones. The two tolerations replace the 300-second defaults, so pods leave an unreachable node about 110 seconds after its last heartbeat: 50 seconds of grace plus 60. The price is that a network blip of that length now moves every pod off the node."},{"body":"Start a cluster with three workers and run three replicas, one per node. Fail one node and watch it turn NotReady, its pod lose readiness, and a replacement appear after the lab's eviction delay. Then bring the node back, protect the Deployment with a PodDisruptionBudget that keeps two pods available, and drain another node to see the budget pace the evictions.","code":"cluster create --workers 3\nkubectl create deployment web --image=gopherforge/web:v2 --replicas=3\nkubectl rollout status deploy/web\nkubectl get pods -o wide\ncluster node fail kind-worker\ncluster tick 15s\nkubectl get nodes\nkubectl get pods -o wide\ncluster tick 30s\nkubectl get pods -o wide\ncluster node recover kind-worker\ncat > pdb.yaml <<'EOF'\napiVersion: policy/v1\nkind: PodDisruptionBudget\nmetadata:\n  name: web\nspec:\n  minAvailable: 2\n  selector:\n    matchLabels:\n      app: web\nEOF\nkubectl apply -f pdb.yaml\nkubectl drain kind-worker3 --ignore-daemonsets\nkubectl get pods -o wide\nkubectl uncordon kind-worker3","language":"bash","title":"Try it in the lab terminal","walkthrough":"The pods start one per worker. The lab marks a failed node NotReady at once instead of after 50 seconds, so fifteen seconds later kind-worker is NotReady and its pod shows 0/1 Running: still bound, but out of the Service. After the lab's 30-second eviction delay a replacement web-<hash>-<id> runs on kind-worker3; on a real cluster the old pod would linger as Terminating. Recovering kind-worker moves nothing back. The drain evicts one pod from kind-worker3, then prints \"Cannot evict pod as it would violate the pod's disruption budget\" and retries until the replacement is Ready; both new pods land on the empty kind-worker."}],"takeaway":"A lost node is tainted after about 50 seconds and its pods are evicted after their 300-second tolerations; only controller-owned pods come back. Planned drains go through the Eviction API, where a PodDisruptionBudget keeps enough replicas running.","title":"When a node dies: NotReady, eviction, PodDisruptionBudgets and safe drains","unitID":"k8s-operations","wrongAnswers":["300 seconds, from the scheduler's retry back-off","300 seconds, from the pods' termination grace period"]},{"conceptTag":"k8s.kustomize-helm","designGuide":{"cautions":["Labels written into selectors break immutable Deployment selectors.","Helm values files grow until the templates are hard to review."],"cost":"A directory per environment and a CI step that renders and diffs the manifests before they reach a cluster.","family":"kubernetes","flow":["Plain manifests in a base","One overlay per environment","Render and review in CI","apply -k or a GitOps controller"],"ratings":[],"strengths":["Each overlay states exactly what differs per environment.","Kustomize needs no extra tool because it ships inside kubectl."]},"hint":"One transformer matches containers by image name and replaces only the parts you give it: the name, the tag or the digest.","id":"k8s.kustomize-helm","introduction":"The same application runs in dev, staging and production with different image tags, replica counts, namespaces and settings. Copying the YAML for each environment drifts within weeks. Kustomize patches a shared base without templates and is built into kubectl; Helm renders a templated chart from values and tracks every release it installs.","nuance":"The images transformer finds every container whose image is gopherforge/web and sets its tag to v2, or a digest. namePrefix renames objects, and a generated ConfigMap never changes a container's image.","objective":"Build per-environment manifests from a shared base with Kustomize transformers and kubectl apply -k, explain Helm charts, values and releases, and choose between them and a GitOps controller.","question":"Your staging overlay must run gopherforge/web:v2 while the base Deployment says v1, without copying the Deployment. What do you add to the overlay's kustomization.yaml?","references":["https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/","https://kubectl.docs.kubernetes.io/references/kustomize/","https://helm.sh/docs/intro/using_helm/"],"reviewAnswer":"images, with name and newTag","reviewPrompt":"Overlay field for an image tag?","sections":[{"body":"A base is a directory of plain manifests plus a kustomization.yaml that lists them. An overlay is another directory whose kustomization.yaml lists the base under resources and adds the changes for one environment. Kustomize renders base plus changes into ordinary YAML, and kubectl apply -k DIR, long form --kustomize DIR, applies the result. Nothing in the base knows about environments, and each overlay is short enough to review on one screen. The GopherForge lab terminal follows a resources entry such as ../../base too; the lab below keeps the manifests and the kustomization in one directory to stay short.","code":"# base/kustomization.yaml lists deployment.yaml and service.yaml.\n# overlays/production/kustomization.yaml:\napiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n- ../../base\nnamespace: production\nnamePrefix: prod-\nlabels:\n- pairs:\n    env: production\nimages:\n- name: gopherforge/web\n  newTag: v2\nreplicas:\n- name: web\n  count: 4\nconfigMapGenerator:\n- name: web-config\n  literals:\n  - LOG_LEVEL=warn","language":"yaml","title":"Bases and overlays","walkthrough":"The overlay pulls in the base, moves every object into the production namespace, renames web to prod-web, labels everything env=production, sets the image tag to v2 and runs four replicas. configMapGenerator creates a ConfigMap whose name ends in a hash of its content, so changing LOG_LEVEL renames it, updates the Deployment that refers to it and rolls the pods. kubectl kustomize overlays/production prints the rendered YAML without applying it; that command is not available in the lab."},{"body":"namespace sets metadata.namespace on every namespaced object; the namespace itself must exist or be one of the resources. namePrefix and nameSuffix rename objects and the references Kustomize knows about, such as a Service named in an Ingress or a ConfigMap used by a pod, but never label values, so selectors keep matching. labels adds labels to object metadata; includeSelectors: true also writes them into selectors, and the older commonLabels always does, which breaks a live Deployment because its selector is immutable. images replaces the name, tag or digest of matching containers. replicas sets the count of Deployments, ReplicaSets and StatefulSets by name. patches applies strategic-merge or JSON 6902 patches for everything else, such as resources or probes per environment. The order of fields in kustomization.yaml does not matter.","title":"What each transformer does"},{"body":"A Helm chart is a directory of templates written in Go text/template with Sprig functions, a values.yaml with defaults and a Chart.yaml with metadata and dependencies. helm upgrade --install renders the templates with your values files and --set flags, applies the result and records a release: a named, numbered revision stored as a Secret in the release's namespace. helm rollback deploys an earlier revision as a new one, and helm uninstall deletes what the release created. helm template renders locally without touching a cluster, which is how CI reviews a chart. Charts are published in chart repositories or OCI registries. The GopherForge lab terminal simulates Helm as well: after helm repo add lab https://charts.lab.example, helm create, template, install, upgrade, history, rollback and uninstall work against its cluster.","code":"helm create web\nhelm template web ./web --set image.repository=gopherforge/web --set image.tag=v2\nhelm upgrade --install web ./web -n staging --create-namespace -f values-staging.yaml\nhelm history web -n staging\nhelm rollback web 1 -n staging\nhelm upgrade --install metrics-server metrics-server --repo https://kubernetes-sigs.github.io/metrics-server/ -n kube-system","language":"bash","title":"Helm: charts, values and releases","walkthrough":"helm create scaffolds a chart whose Deployment template reads image.repository and image.tag. helm template prints the rendered manifests to read or diff. upgrade --install creates the release on the first run and upgrades it afterwards. history lists the revisions, and rollback 1 redeploys the first as a new revision. The last line installs metrics-server from its official chart repository."},{"body":"Use Kustomize for your own services: the base is the YAML you would write anyway, overlays are short, and a reviewer sees the exact change. Use Helm to install third-party software, which is usually published as a chart, and when you distribute a configurable package to other teams. The two combine: render a chart with helm template into a base and adjust it with an overlay. Each has a typical failure. Charts grow a values file that exposes every field until the templates are hard to review, and Helm installs CRDs from a chart's crds directory but never upgrades them. Overlays grow patches that duplicate the base, and labels written into selectors break immutable Deployment selectors. In both cases render in CI and review the rendered output, not only the source.","title":"Choosing Kustomize or Helm"},{"body":"GitOps moves the apply step into the cluster. A controller such as Argo CD or Flux watches a Git repository that holds Kustomize directories or Helm releases, renders them, compares the result with the live objects and applies the difference. It reports drift when someone changes the cluster by hand, can revert it (self-heal) and can delete objects that were removed from Git (prune). CI then only builds and pushes images and commits the new tag to an overlay; nothing outside the cluster needs credentials to apply. Git history becomes the audit log, and a rollback is a revert commit. Argo CD models a deployed directory as an Application; Flux uses Kustomization and HelmRelease objects.","title":"GitOps with Argo CD or Flux"},{"body":"Write a Deployment and a Service, then a kustomization.yaml that puts them in a staging namespace, prefixes their names, labels them and swaps the image tag. Apply the directory with kubectl apply --kustomize, the long form of -k, check from inside the cluster that the renamed Service reaches the new image, apply again to see that nothing changes, and remove everything the kustomization created.","code":"kind create cluster\nmkdir -p staging\ncat > staging/deployment.yaml <<'EOF'\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 2\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n      - name: web\n        image: gopherforge/web:v1\n        ports:\n        - containerPort: 8080\nEOF\ncat > staging/service.yaml <<'EOF'\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector:\n    app: web\n  ports:\n  - port: 80\n    targetPort: 8080\nEOF\ncat > staging/kustomization.yaml <<'EOF'\napiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nnamespace: staging\nnamePrefix: staging-\nlabels:\n- pairs:\n    env: staging\nresources:\n- deployment.yaml\n- service.yaml\nimages:\n- name: gopherforge/web\n  newTag: v2\nEOF\nkubectl create namespace staging\nkubectl apply --kustomize staging\nkubectl rollout status deploy/staging-web -n staging\nkubectl get deploy,svc -n staging --show-labels\nkubectl get deploy staging-web -n staging -o jsonpath='{.spec.template.spec.containers[0].image}'\nkubectl run probe -n staging --rm -it --image=busybox --restart=Never -- wget -qO- http://staging-web/version\nkubectl apply --kustomize staging\nkubectl delete --kustomize staging","language":"bash","title":"Try it in the lab terminal","walkthrough":"The first apply prints deployment.apps/staging-web created and service/staging-web created. --show-labels shows env=staging on both objects; without includeTemplates the pods do not get it. The jsonpath prints gopherforge/web:v2 although deployment.yaml says v1, and wget to http://staging-web/version answers v2: the renamed Service still selects app=web. The second apply reports unchanged for both objects, and delete --kustomize removes exactly what the kustomization produced."}],"takeaway":"Keep one base of plain manifests and one short overlay per environment, applied with kubectl apply -k. Use Helm for third-party charts, render everything in CI, and let a GitOps controller apply what Git says.","title":"Package manifests per environment with Kustomize overlays, Helm charts and GitOps","unitID":"k8s-operations","wrongAnswers":["namePrefix, set to gopherforge/web:v2","configMapGenerator, with IMAGE=gopherforge/web:v2"]},{"conceptTag":"k8s.client-go","designGuide":{"cautions":["Modifying a cached object corrupts what every other reader sees.","Two replicas without leader election fight over the same objects."],"cost":"A few hundred lines of Go per controller, or controller-runtime as a dependency, plus RBAC for everything it watches.","family":"kubernetes","flow":["rest.Config and clientset","Shared informer and lister","Handlers enqueue keys","Workers reconcile from cache"],"ratings":[],"strengths":["One watch per resource type serves every handler in the process.","Level-triggered reconcile recovers from missed events and restarts."]},"hint":"An informer already keeps an up-to-date copy of every Deployment in memory. Ask which object reads that copy without calling the API server.","id":"k8s.client-go","introduction":"Every controller in a cluster, including the one that runs Deployments, is a Go program built on client-go. A loop that calls List every few seconds overloads the API server and still misses short-lived changes. Informers, listers and workqueues let a controller react to every change from a local cache while its load on the API server stays small and bounded.","nuance":"A lister reads the informer's local cache, kept current by one shared List and Watch, so reconcile costs no API calls. A stored event object may be stale when its key is processed, and a watch per call multiplies load.","objective":"Build a clientset from in-cluster or kubeconfig credentials, watch objects through a shared informer and lister, reconcile keys from a rate-limited workqueue, and shut a Go service down cleanly on SIGTERM.","question":"Your controller calls Deployments(ns).List on the API server in every reconcile and is throttled with 429 responses as the cluster grows. Where should reconcile read Deployments from instead?","references":["https://github.com/kubernetes/client-go","https://pkg.go.dev/k8s.io/client-go/tools/cache","https://kubernetes.io/docs/concepts/architecture/controller/","https://book.kubebuilder.io/"],"reviewAnswer":"The informer's lister: the shared local cache","reviewPrompt":"Where reconcile reads its objects?","sections":[{"body":"A rest.Config holds the API server address, the credentials and the client's limits. Inside a pod, rest.InClusterConfig reads the ServiceAccount token and CA from /var/run/secrets/kubernetes.io/serviceaccount and the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT variables; outside, clientcmd loads a kubeconfig the way kubectl does. kubernetes.NewForConfig returns a typed clientset: cs.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{}) returns an *appsv1.Deployment. The dynamic client handles any resource as unstructured data, which suits CRDs without generated types. client-go limits itself to 5 requests per second with bursts of 10 unless you raise QPS and Burst, and the API server adds API Priority and Fairness, answering 429 when a client floods it. Use the client-go minor version that matches the cluster: v0.34 for Kubernetes 1.34.","code":"func newClientset(kubeconfig string) (*kubernetes.Clientset, error) {\n\tcfg, err := rest.InClusterConfig()\n\tif errors.Is(err, rest.ErrNotInCluster) {\n\t\tcfg, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.QPS, cfg.Burst = 20, 40\n\tcfg.UserAgent = \"web-controller\"\n\treturn kubernetes.NewForConfig(cfg)\n}","language":"go","title":"Config, clientset and rate limits","walkthrough":"The function prefers in-cluster credentials and falls back to a kubeconfig file only when the process is not running in a pod, so the same binary works in both places. Raising QPS and Burst suits a controller that starts with many reads, and a UserAgent makes its requests recognisable in API server audit logs and metrics."},{"body":"A List returns a snapshot with a resourceVersion, and a Watch from that version streams ADDED, MODIFIED and DELETED events. Watches end on timeouts, and a version that is too old gets 410 Gone, so a correct client relists and watches again without losing changes. An informer does exactly that and keeps an indexed local cache. A SharedInformerFactory shares one List and Watch per resource type among every handler in the process, and a lister reads from the cache without any API call. Handlers must return quickly and should only enqueue a key. Objects in the cache are shared: never modify them, DeepCopy first. Start the factory and wait for the caches to sync before doing work, or the controller acts on an empty view of the cluster.","code":"factory := informers.NewSharedInformerFactory(cs, 10*time.Minute)\ndeployments := factory.Apps().V1().Deployments()\nlister := deployments.Lister()\nqueue := workqueue.NewTypedRateLimitingQueue(\n\tworkqueue.DefaultTypedControllerRateLimiter[string]())\n\nenqueue := func(obj any) {\n\tif key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj); err == nil {\n\t\tqueue.Add(key)\n\t}\n}\ndeployments.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\tAddFunc:    enqueue,\n\tUpdateFunc: func(_, obj any) { enqueue(obj) },\n\tDeleteFunc: enqueue,\n})\n\nfactory.Start(ctx.Done())\nfor typ, synced := range factory.WaitForCacheSync(ctx.Done()) {\n\tif !synced {\n\t\treturn fmt.Errorf(\"cache for %v did not sync\", typ)\n\t}\n}","language":"go","title":"From List and Watch to shared informers","walkthrough":"The ten-minute resync period re-delivers every cached object as an update, a safety net for side effects that went missing. DeletionHandlingMetaNamespaceKeyFunc also handles the tombstone a handler receives when a delete happened while the watch was down. Keys are namespace/name strings such as default/web, so the queue holds names, never stale copies of objects."},{"body":"The workqueue sits between handlers and workers. It deduplicates, so ten updates to default/web while the key waits become one reconcile, and it never hands one key to two workers at once. Reconcile is level-triggered: it ignores what the event said, reads the current object from the lister, compares desired with actual state and takes one step towards desired. NotFound from the lister means the object was deleted. On error the key goes back with AddRateLimited, using per-item exponential backoff from 5 ms to 1000 s under an overall limit of 10 per second; on success Forget resets that backoff. Run several workers in goroutines, and when the controller has more than one replica, use leader election on a Lease so that only one of them acts.","code":"func runWorker(ctx context.Context, queue workqueue.TypedRateLimitingInterface[string], lister appslisters.DeploymentLister) {\n\tfor {\n\t\tkey, shutdown := queue.Get()\n\t\tif shutdown {\n\t\t\treturn\n\t\t}\n\t\tif err := reconcile(ctx, lister, key); err != nil {\n\t\t\tqueue.AddRateLimited(key)\n\t\t} else {\n\t\t\tqueue.Forget(key)\n\t\t}\n\t\tqueue.Done(key)\n\t}\n}\n\nfunc reconcile(ctx context.Context, lister appslisters.DeploymentLister, key string) error {\n\tns, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn nil\n\t}\n\td, err := lister.Deployments(ns).Get(name)\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil // deleted: clean up whatever you created for it\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif d.Status.ReadyReplicas < *d.Spec.Replicas {\n\t\tlog.Printf(\"%s: %d of %d ready\", key, d.Status.ReadyReplicas, *d.Spec.Replicas)\n\t}\n\treturn nil\n}","language":"go","title":"The workqueue and the reconcile loop","walkthrough":"Done must follow every Get, or the key stays marked as in progress and is never processed again. A malformed key returns nil because retrying cannot fix it. This reconcile only reports Deployments with fewer ready replicas than desired; a real controller would create, update or delete objects at that point, always computing the change from the current state."},{"body":"Writing informers, queues and leader election by hand teaches how controllers work, but most new controllers use controller-runtime. Its Manager owns a shared cache, clients, leader election, metrics and health endpoints; you implement Reconcile(ctx, req) (ctrl.Result, error) for one key and declare which objects trigger it. Kubebuilder and the Operator SDK scaffold such projects, generate CRD manifests and RBAC rules from Go markers, and add webhooks. A CustomResourceDefinition adds a new resource type to the API server, such as kind: Website, with an OpenAPI v3 schema that validates objects, one or more versions, and a status subresource that the controller writes. The API server stores and serves these objects; a controller gives them behaviour. A CRD plus a controller that encodes operational knowledge, such as backups or failover, is called an operator.","title":"controller-runtime, operators and CRDs"},{"body":"When a pod is deleted by a rollout, a drain or a scale-down, the kubelet runs the preStop hook, sends SIGTERM to the container's main process, and sends SIGKILL when terminationGracePeriodSeconds runs out: 30 by default, counted from the start of preStop. At the same moment the pod leaves the EndpointSlices, and kube-proxy and ingress controllers need a few seconds to notice, so new requests still arrive. A short preStop sleep covers that window; the sleep action is stable in Kubernetes 1.34 and needs no sleep binary in the image. Then the Go process stops accepting connections and finishes in-flight requests with http.Server.Shutdown, within the grace period that remains. Make the Go binary PID 1 with the exec form of ENTRYPOINT; the shell form runs sh -c as PID 1, which often does not pass SIGTERM on.","code":"func serve(srv *http.Server) error {\n\tctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)\n\tdefer stop()\n\n\terrc := make(chan error, 1)\n\tgo func() { errc <- srv.ListenAndServe() }()\n\n\tselect {\n\tcase err := <-errc:\n\t\treturn err\n\tcase <-ctx.Done():\n\t}\n\tshutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\treturn srv.Shutdown(shutdownCtx)\n}","language":"go","title":"Graceful shutdown on SIGTERM","walkthrough":"signal.NotifyContext cancels ctx on SIGTERM. Shutdown closes the listeners, waits for active requests and returns when they finish or after 20 seconds, inside a 30-second grace period that already spent 5 seconds in preStop. A controller shuts down the same way: cancelling its context stops the informers, queue.ShutDown ends the workers, and leader election with ReleaseOnCancel hands over the Lease at once."},{"body":"Watch the Deployment and ReplicaSet controllers run the loop described above. Follow the owner references from pod to ReplicaSet to Deployment, change the desired state with scale, destroy actual state by deleting the pods and then the ReplicaSet, and read the events each controller records as it converges. This is the loop your own controller would implement: observe, compare, act, repeat.","code":"kind create cluster\nkubectl create deployment web --image=gopherforge/web:v2 --replicas=2\nkubectl rollout status deploy/web\nkubectl get pods -o custom-columns=POD:.metadata.name,OWNER-KIND:.metadata.ownerReferences[0].kind,OWNER:.metadata.ownerReferences[0].name\nkubectl get rs -o jsonpath='{.items[0].metadata.ownerReferences[0].kind}/{.items[0].metadata.ownerReferences[0].name}{\"\\n\"}'\nkubectl scale deploy/web --replicas=4\nkubectl get rs\nkubectl delete pod -l app=web\nkubectl get rs\nkubectl wait --for=condition=Ready pod -l app=web --timeout=60s\nkubectl get events --sort-by=.lastTimestamp | grep -E 'ScalingReplicaSet|SuccessfulCreate'\nkubectl delete rs -l app=web\ncluster tick 10s\nkubectl get rs,pods","language":"bash","title":"Try it in the lab terminal","walkthrough":"custom-columns shows each pod owned by ReplicaSet web-<hash>, and the jsonpath shows that ReplicaSet owned by Deployment/web. After the scale, get rs shows DESIRED 4, CURRENT 4, READY 2. After all four pods are deleted, READY is 0 but CURRENT is already 4 again. The events show both controllers at work: ScalingReplicaSet \"from 2 to 4\" from the Deployment controller, then six SuccessfulCreate events from the ReplicaSet controller, four of them after the delete. Even a deleted ReplicaSet comes back: the Deployment controller recreates it under the same name, a hash of the pod template, and ten seconds later it has four Running pods."}],"takeaway":"Build controllers from a shared informer, a lister and a rate-limited workqueue, and reconcile each key from the current state, not from the event. On SIGTERM, drain in-flight work before the grace period ends.","title":"Talk to the Kubernetes API from Go with client-go, informers and workqueues","unitID":"k8s-operations","wrongAnswers":["From a new Watch opened for each reconcile call","From the object stored with the queued event"]},{"conceptTag":"k8s.production-checklist","designGuide":{"cautions":["Hard spread rules can leave pods Pending on small clusters.","readOnlyRootFilesystem breaks apps that write outside mounted volumes."],"cost":"A longer manifest, spare capacity for surge and spread, and a review step for every new service.","family":"kubernetes","flow":["Pin image, set requests and probes","Spread replicas, add a PDB","Non-root, read-only, no token","Roll out, load test, watch"],"ratings":[],"strengths":["Each item prevents a failure seen in real outages.","The checklist can be reviewed line by line in a pull request."]},"hint":"Ask which setting forbids the Deployment controller from removing an old pod before a new one is Ready, and what decides Ready.","id":"k8s.production-checklist","introduction":"Most Kubernetes outages are not exotic: an image tag that moved, a pod without requests evicted first under memory pressure, a rollout that sent traffic to pods that were not ready, a token with more rights than the app needed. A checklist turns those incidents into review items that every Deployment passes before it ships.","nuance":"With maxUnavailable: 0 the controller removes an old pod only after a surge pod is Ready. A pod failing its readiness probe never counts, so the rollout stalls at one extra pod while the old ReplicaSet keeps serving.","objective":"Review a Deployment against a production checklist and write one that pins its image, sizes its resources, probes its health, survives disruptions, runs with least privilege and shuts down cleanly.","question":"The new image of your Deployment never passes its readiness probe. With which settings does the rollout stall while every old pod keeps serving traffic?","references":["https://kubernetes.io/docs/concepts/security/pod-security-standards/","https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/","https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/","https://kubernetes.io/docs/concepts/security/security-checklist/"],"reviewAnswer":"maxUnavailable: 0, maxSurge: 1 and a readiness probe","reviewPrompt":"Rollout keeping full capacity?","sections":[{"body":"Pin the image to a version tag and, where your registry and tooling allow, to a digest: gopherforge/web:v2@sha256:... cannot change under you, and latest makes rollbacks meaningless. Give every container CPU and memory requests: the scheduler places pods by them, the HPA divides by them, and pods without them are evicted first. Set a memory limit so that a leak ends in a visible OOMKilled instead of a starving node; many teams leave CPU limits off because throttling hurts latency. In Go, set GOMEMLIMIT to about 90% of the memory limit; since Go 1.25, GOMAXPROCS follows a CPU limit automatically. Probe with intent: a startupProbe for slow starts, a readinessProbe that checks the process can serve, and a livenessProbe only for deadlocks. Never let liveness check a database: an outage there would restart every pod.","title":"Image, resources and probes"},{"body":"Run at least two replicas, three if one may be down during maintenance, and spread them with topologySpreadConstraints across nodes and, on real clusters, zones. Add a PodDisruptionBudget with maxUnavailable: 1 so that drains and upgrades take one pod at a time. Roll out with maxSurge: 1 and maxUnavailable: 0: capacity never drops, and a version that never becomes ready stalls while the old pods keep serving. progressDeadlineSeconds turns a stall into a ProgressDeadlineExceeded condition that CI can fail on, and revisionHistoryLimit keeps old ReplicaSets to roll back to. Shut down gracefully with a preStop sleep of a few seconds while endpoints update, SIGTERM handling in the code, and a terminationGracePeriodSeconds longer than both. Add an HPA when load varies, and then drop replicas from what CI applies.","title":"Availability: replicas, spread, budgets and rollouts"},{"body":"runAsNonRoot makes the kubelet refuse to start a container as UID 0: an image whose user is root, with no runAsUser set, fails with CreateContainerConfigError instead of running as root; a numeric runAsUser picks the UID explicitly. Set readOnlyRootFilesystem and mount an emptyDir where the app writes, disable allowPrivilegeEscalation, drop ALL capabilities and use the RuntimeDefault seccomp profile: this meets the Pod Security Standards restricted profile, which a namespace enforces with the label pod-security.kubernetes.io/enforce: restricted. Give the app its own ServiceAccount with automountServiceAccountToken: false unless it calls the API, and then a Role with only the verbs it needs. Add a default-deny NetworkPolicy per namespace and allow what each app needs; policies take effect only with a network plugin that enforces them, such as Calico or Cilium.","code":"apiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: default-deny-ingress\nspec:\n  podSelector: {}\n  policyTypes:\n  - Ingress\n---\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: web-allow-http\nspec:\n  podSelector:\n    matchLabels:\n      app.kubernetes.io/name: web\n  policyTypes:\n  - Ingress\n  ingress:\n  - ports:\n    - protocol: TCP\n      port: 8080","language":"yaml","title":"Least privilege: securityContext, ServiceAccount, NetworkPolicy","walkthrough":"The first policy selects every pod in the namespace and allows no ingress. The second allows TCP 8080 to the web pods from any source, as an Ingress controller in another namespace needs; add a from list with namespaceSelector or podSelector when only known clients may call. Egress stays open until a policy lists Egress in policyTypes, and from then on DNS to kube-dns must be allowed explicitly."},{"body":"A ResourceQuota per namespace caps total requests, limits and object counts, so one team's runaway autoscaler cannot take the whole cluster; a LimitRange supplies default requests for containers that forget them. The lab terminal applies LimitRange defaults and enforces ResourceQuota for pods, CPU and memory. Observe every service the same way: structured JSON logs on stdout, for example with log/slog; rate, error and duration metrics exposed for Prometheus; traces through OpenTelemetry with trace IDs in the logs; and alerts on symptoms users feel rather than on CPU. Back up what Git cannot recreate: etcd snapshots with etcdctl snapshot save on self-managed control planes, and volumes plus objects created at runtime with a tool such as Velero. A backup that has never been restored is a hope, so rehearse the restore.","title":"Namespace guardrails, observability and backups"},{"body":"The manifest applies every item of the checklist to gopherforge/web:v2. In production you would also pin the digest your registry reports for v2, so that the tag cannot move, and add an HPA if the load varies. The lab file below adds the ServiceAccount the pods run as, the Service in front of them and the PodDisruptionBudget that paces drains.","code":"apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app.kubernetes.io/name: web\nspec:\n  replicas: 3\n  revisionHistoryLimit: 5\n  progressDeadlineSeconds: 300\n  strategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxSurge: 1\n      maxUnavailable: 0\n  selector:\n    matchLabels:\n      app.kubernetes.io/name: web\n  template:\n    metadata:\n      labels:\n        app.kubernetes.io/name: web\n    spec:\n      serviceAccountName: web\n      automountServiceAccountToken: false\n      terminationGracePeriodSeconds: 30\n      securityContext:\n        runAsNonRoot: true\n        runAsUser: 10001\n        runAsGroup: 10001\n        seccompProfile:\n          type: RuntimeDefault\n      topologySpreadConstraints:\n      - maxSkew: 1\n        topologyKey: kubernetes.io/hostname\n        whenUnsatisfiable: DoNotSchedule\n        nodeTaintsPolicy: Honor\n        matchLabelKeys:\n        - pod-template-hash\n        labelSelector:\n          matchLabels:\n            app.kubernetes.io/name: web\n      containers:\n      - name: web\n        image: gopherforge/web:v2\n        ports:\n        - name: http\n          containerPort: 8080\n        env:\n        - name: GOMEMLIMIT\n          value: 115MiB\n        resources:\n          requests:\n            cpu: 100m\n            memory: 64Mi\n          limits:\n            memory: 128Mi\n        startupProbe:\n          httpGet:\n            path: /healthz\n            port: http\n          periodSeconds: 2\n          failureThreshold: 30\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: http\n          periodSeconds: 5\n        livenessProbe:\n          httpGet:\n            path: /healthz\n            port: http\n          periodSeconds: 10\n        lifecycle:\n          preStop:\n            sleep:\n              seconds: 5\n        securityContext:\n          allowPrivilegeEscalation: false\n          readOnlyRootFilesystem: true\n          capabilities:\n            drop: [\"ALL\"]\n        volumeMounts:\n        - name: tmp\n          mountPath: /tmp\n      volumes:\n      - name: tmp\n        emptyDir:\n          sizeLimit: 64Mi","language":"yaml","title":"The complete Deployment","walkthrough":"Three replicas at most one apart per node, with tainted nodes left out of the count; a surge-only rollout with a five-minute progress deadline; requests of 100m and 64Mi, a 128Mi limit and GOMEMLIMIT at 115MiB; a startup probe that allows 60 seconds, readiness on /readyz and liveness on /healthz; a 5-second preStop sleep inside a 30-second grace period; and a non-root, read-only container without capabilities or a ServiceAccount token, writing only to a size-limited /tmp."},{"body":"Start three workers so that the spread rule has room, create a namespace and make it the context's default, apply the full file with the ServiceAccount, Deployment, Service and PodDisruptionBudget, and put the service under load. Then ship a broken release, watch the readiness probe and the rollout strategy keep the service up, roll back, and check the ServiceAccount's rights.","code":"cluster create --workers 3\nkubectl create namespace shop\nkubectl config set-context --current --namespace=shop\ncat > web.yaml <<'EOF'\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: web\nautomountServiceAccountToken: false\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app.kubernetes.io/name: web\nspec:\n  replicas: 3\n  revisionHistoryLimit: 5\n  progressDeadlineSeconds: 300\n  strategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxSurge: 1\n      maxUnavailable: 0\n  selector:\n    matchLabels:\n      app.kubernetes.io/name: web\n  template:\n    metadata:\n      labels:\n        app.kubernetes.io/name: web\n    spec:\n      serviceAccountName: web\n      automountServiceAccountToken: false\n      terminationGracePeriodSeconds: 30\n      securityContext:\n        runAsNonRoot: true\n        runAsUser: 10001\n        runAsGroup: 10001\n        seccompProfile:\n          type: RuntimeDefault\n      topologySpreadConstraints:\n      - maxSkew: 1\n        topologyKey: kubernetes.io/hostname\n        whenUnsatisfiable: DoNotSchedule\n        nodeTaintsPolicy: Honor\n        matchLabelKeys:\n        - pod-template-hash\n        labelSelector:\n          matchLabels:\n            app.kubernetes.io/name: web\n      containers:\n      - name: web\n        image: gopherforge/web:v2\n        ports:\n        - name: http\n          containerPort: 8080\n        env:\n        - name: GOMEMLIMIT\n          value: 115MiB\n        resources:\n          requests:\n            cpu: 100m\n            memory: 64Mi\n          limits:\n            memory: 128Mi\n        startupProbe:\n          httpGet:\n            path: /healthz\n            port: http\n          periodSeconds: 2\n          failureThreshold: 30\n        readinessProbe:\n          httpGet:\n            path: /readyz\n            port: http\n          periodSeconds: 5\n        livenessProbe:\n          httpGet:\n            path: /healthz\n            port: http\n          periodSeconds: 10\n        lifecycle:\n          preStop:\n            sleep:\n              seconds: 5\n        securityContext:\n          allowPrivilegeEscalation: false\n          readOnlyRootFilesystem: true\n          capabilities:\n            drop: [\"ALL\"]\n        volumeMounts:\n        - name: tmp\n          mountPath: /tmp\n      volumes:\n      - name: tmp\n        emptyDir:\n          sizeLimit: 64Mi\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector:\n    app.kubernetes.io/name: web\n  ports:\n  - name: http\n    port: 80\n    targetPort: http\n---\napiVersion: policy/v1\nkind: PodDisruptionBudget\nmetadata:\n  name: web\nspec:\n  maxUnavailable: 1\n  selector:\n    matchLabels:\n      app.kubernetes.io/name: web\nEOF\nkubectl apply -f web.yaml\nkubectl rollout status deploy/web\nkubectl get pods -o wide\ntraffic run svc/web --rps 200 --duration 30s\nkubectl set image deploy/web web=gopherforge/web:v2-broken\ntraffic run svc/web --rps 200 --duration 30s\nkubectl rollout status deploy/web --timeout=10s\nkubectl rollout undo deploy/web\nkubectl rollout status deploy/web\nkubectl auth can-i list secrets --as=system:serviceaccount:shop:web","language":"bash","title":"Try it in the lab terminal","walkthrough":"The apply creates four objects, and get pods -o wide shows one pod each on kind-worker, kind-worker2 and kind-worker3. The first traffic run ends with Total 6000 requests, 100.0% ok, about a third per pod. With v2-broken the surge pod never passes /readyz, so the timeline shows READY PODS 3/4 and still 100.0% ok: maxUnavailable: 0 kept every old pod. rollout status --timeout=10s fails with \"1 out of 3 new replicas have been updated\", rollout undo restores v2, and auth can-i answers no."}],"takeaway":"A production Deployment pins its image, declares requests and a memory limit, probes with intent, spreads two or more replicas under a PodDisruptionBudget, rolls out without losing capacity, runs as non-root without a token, and shuts down within its grace period.","title":"A production checklist for Deployments, applied to gopherforge/web:v2 in the lab","unitID":"k8s-operations","wrongAnswers":["maxUnavailable: 1 with maxSurge: 0 and a liveness probe","Recreate strategy with a startup probe and a long grace period"]}],"revision":"2026-12-01.1","schemaVersion":1,"solutions":{},"units":[{"id":"k8s-foundations","lessons":[{"conceptTags":["k8s.architecture"],"explanation":"Kubernetes is easy to treat as a black box until something does not start; then you need to know which component was supposed to act. A cluster is a store of desired state plus independent control loops that keep moving reality towards it. This lesson maps those parts, follows one Deployment from kubectl to running containers, and builds a local cluster with kind to look at them.","id":"k8s.architecture","objective":"Name the control-plane and node components, trace a kubectl apply from the API request to a running container, and inspect the nodes and system pods of a kind cluster.","task":{"reading":{}},"title":"How a cluster works: control plane, nodes and reconciliation loops"},{"conceptTags":["k8s.kubectl-contexts"],"explanation":"Every kubectl command goes to one API server, as one user, in one namespace, and all three come from a file you rarely look at. The most expensive kubectl mistakes are seldom wrong commands; they are right commands sent to the wrong cluster or namespace. This lesson explains kubeconfig, contexts and namespaces, and the habits that keep production out of reach of a command meant for your laptop.","id":"k8s.kubectl-contexts","objective":"Read a kubeconfig, list, create and switch contexts, set a default namespace, and use -n, -A and explicit contexts so that commands reach the cluster and namespace you intend.","task":{"reading":{}},"title":"kubeconfig, contexts and namespaces: know where every kubectl command goes"},{"conceptTags":["k8s.objects-yaml"],"explanation":"Everything in Kubernetes is an object stored by the API server, and every object has the same shape. Once you can read that shape you can write manifests without copying them blindly, find any field with kubectl explain, and query live state precisely instead of scanning tables. The API server is strict about the shape too: a misspelt field is an error, not something it quietly ignores.","id":"k8s.objects-yaml","objective":"Write a manifest from scratch or from a dry-run scaffold, tell spec from status, choose between labels and annotations, look fields up with kubectl explain, read live state with jsonpath and recognise strict validation errors.","task":{"reading":{}},"title":"Anatomy of an object: apiVersion, kind, metadata, spec and status"},{"conceptTags":["k8s.pods"],"explanation":"A Pod is the smallest thing Kubernetes schedules: one or more containers that always run together on one node and share a network identity. Most debugging starts by reading a pod's state, and the STATUS column that kubectl prints mixes three different things. This lesson separates them, shows how restart policy changes what a failure looks like, and explains why you will rarely create a Pod yourself.","id":"k8s.pods","objective":"Run and inspect pods, tell the pod phase from container states and the STATUS column, choose a restartPolicy, use logs and exec, and explain why controllers rather than people should create pods.","task":{"reading":{}},"title":"Pods: shared containers, phases, container states and restart policy"},{"conceptTags":["k8s.labels-selectors"],"explanation":"Kubernetes has no fixed links between a ReplicaSet and its pods or between a Service and its backends; they find each other through labels, and the match is evaluated continuously. That makes the system flexible, because changing one label can pull a pod out of rotation. It also makes it fragile when two selectors overlap or a label changes by accident.","id":"k8s.labels-selectors","objective":"Label objects, query them with equality-based and set-based selectors, explain how ReplicaSets and Services choose pods by label, and predict what relabelling a pod does.","task":{"reading":{}},"title":"Labels and selectors: how controllers and Services find their pods"},{"conceptTags":["k8s.declarative-apply"],"explanation":"Imperative commands such as kubectl create and kubectl scale are quick, but they leave no record of what the cluster should look like, and nobody can review or reproduce them. Declarative management keeps the desired state in files, in git, and lets kubectl apply work out what to change. This lesson shows how apply decides, how it corrects drift, and how kustomize produces variants of the same manifests without copying them.","id":"k8s.declarative-apply","objective":"Manage objects from version-controlled manifests with kubectl apply, interpret created, configured and unchanged, apply and delete whole directories, and produce per-environment variants with kustomize.","task":{"reading":{}},"title":"Declarative configuration with kubectl apply, manifest directories and kustomize"}],"summary":"Control plane and nodes, kubeconfig contexts and namespaces, the anatomy of an object, Pods, labels and selectors, declarative apply and kustomize.","title":"Kubernetes foundations: the cluster and kubectl","translationNote":"Every lesson ends in the DevOps terminal's simulated cluster: kubectl, kind and traffic behave like a real cluster, offline. The same commands work against kind or any cluster you own."},{"id":"k8s-workloads","lessons":[{"conceptTags":["k8s.deployments-replicasets"],"explanation":"A Pod you create by hand is gone for good when someone deletes it or its node dies. A Deployment declares how many identical Pods you want and what they look like; a ReplicaSet keeps that many running, and the Deployment manages ReplicaSets so that the template can change safely. Knowing which object owns which is what lets you read kubectl output and fix a stuck workload.","id":"k8s.deployments-replicasets","objective":"Create a Deployment, trace its ReplicaSet and Pods through labels and owner references, read the READY, UP-TO-DATE and AVAILABLE columns, and watch the controllers scale and replace Pods.","task":{"reading":{}},"title":"Deployments, ReplicaSets and Pods: the controller chain behind every replica"},{"conceptTags":["k8s.rolling-updates"],"explanation":"Changing a Deployment's Pod template starts a rollout: a new ReplicaSet grows while the old one shrinks. How fast that happens, how much spare capacity it needs and how much serving capacity it may lose are all settings. Just as important is what happens when the new version never becomes ready: Kubernetes stops, keeps the old Pods serving, and leaves the decision to roll back to you.","id":"k8s.rolling-updates","objective":"Configure a Deployment's update strategy, predict how many Pods exist during a rollout, follow and steer it with kubectl rollout, and recover from a release that never becomes ready.","task":{"reading":{}},"title":"Rolling updates: maxSurge, maxUnavailable, rollout history, undo and stalled rollouts"},{"conceptTags":["k8s.probes"],"explanation":"Kubernetes knows only that a container's process is running. Whether the application can serve traffic yet, and whether it is still making progress, it learns from probes that the kubelet runs on the node. Each probe answers a different question and triggers a different action, and confusing them is one of the most common causes of self-inflicted downtime.","id":"k8s.probes","objective":"Choose the right probe for each question, configure its timing, implement /readyz and /healthz handlers in a Go service, and avoid the probe settings that cause outages.","task":{"reading":{}},"title":"Readiness, liveness and startup probes: routing traffic and restarting stuck containers"},{"conceptTags":["k8s.resources-qos"],"explanation":"Without resource settings, the scheduler places Pods as if they cost nothing and the node discovers the truth under load. Requests tell the scheduler what to reserve; limits tell the kernel where to stop a container. CPU and memory behave very differently at that limit: one slows down, the other is killed.","id":"k8s.resources-qos","objective":"Set requests and limits deliberately, predict how the scheduler and the kernel use them, recognise CPU throttling and OOMKilled containers, and know which QoS class each workload gets.","task":{"reading":{}},"title":"Resource requests and limits, CPU throttling, OOMKills and QoS classes"},{"conceptTags":["k8s.scheduling"],"explanation":"Every new Pod starts without a node. The scheduler picks one, and if it cannot, the Pod waits in Pending with an event that explains why, node by node. Most scheduling problems are constraints you wrote yourself: a selector no node matches, a taint nobody tolerates, or requests that do not fit. Knowing the vocabulary turns that event into a one-line diagnosis.","id":"k8s.scheduling","objective":"Explain how the scheduler filters and scores nodes, steer Pods with nodeSelector and affinity, keep them off nodes with taints, and read FailedScheduling messages after a cordon, a drain or a bad constraint.","task":{"reading":{}},"title":"Scheduling: node selection, affinity, taints and tolerations, spreading and draining nodes"},{"conceptTags":["k8s.statefulsets-daemonsets"],"explanation":"Deployments treat Pods as interchangeable: random names, new IPs, no memory of earlier replicas. Databases, queues and consensus systems need the opposite: each member keeps its name, its DNS record and its disk across restarts. Node agents need a third shape, exactly one Pod on every node. StatefulSets and DaemonSets provide those two guarantees.","id":"k8s.statefulsets-daemonsets","objective":"Run a StatefulSet with a headless Service and volumeClaimTemplates, predict its ordering and storage behaviour, and run a DaemonSet that covers every node, tainted ones included.","task":{"reading":{}},"title":"StatefulSets for stable identity and storage, DaemonSets for one Pod per node"},{"conceptTags":["k8s.jobs-cronjobs"],"explanation":"Not every workload serves requests. Reports, migrations, imports and cleanups run, finish and exit, and a Deployment would restart them forever. A Job runs Pods until enough of them succeed and gives up after a set number of failures or a deadline; a CronJob creates Jobs on a schedule. Both retry, so the code they run must tolerate running more than once.","id":"k8s.jobs-cronjobs","objective":"Run Jobs with completions, parallelism, backoffLimit and activeDeadlineSeconds, schedule them with CronJobs and a concurrency policy, trigger a run by hand, and write batch code that is safe to retry.","task":{"reading":{}},"title":"Jobs and CronJobs: batch work with retries, deadlines and schedules"}],"summary":"ReplicaSets and self-healing, rolling updates and rollbacks, probes, requests and limits, scheduling, StatefulSets, DaemonSets, Jobs and CronJobs.","title":"Workloads: Deployments, rollouts and jobs","translationNote":"Labs break things on purpose: stalled rollouts, OOMKilled containers, Pending pods. Nothing really runs; behaviour and kubectl output follow Kubernetes 1.34."},{"id":"k8s-networking","lessons":[{"conceptTags":["k8s.services"],"explanation":"Every pod gets its own IP address and loses it when the pod is replaced by a rollout, a crash or a node drain. Clients cannot chase those addresses. A Service gives a changing set of pods one stable virtual IP and one DNS name, and Kubernetes keeps the list of real backends current as pods come and go.","id":"k8s.services","objective":"Expose a Deployment through a ClusterIP Service, trace a request from selector to endpoints to targetPort, and fix a wrong targetPort and a selector that matches no pods.","task":{"reading":{}},"title":"Services: a stable virtual IP and DNS name in front of changing pods"},{"conceptTags":["k8s.service-types"],"explanation":"A ClusterIP is reachable only from inside the cluster. Letting traffic in from outside, pointing an in-cluster name at an external host, or letting clients see every pod each needs a different Service type. The types stack: every LoadBalancer is also a NodePort, and every NodePort is also a ClusterIP.","id":"k8s.service-types","objective":"Pick the right Service type for each job, reach a NodePort and a LoadBalancer from outside the cluster, and explain what externalTrafficPolicy changes.","task":{"reading":{}},"title":"Service types: NodePort, LoadBalancer, ExternalName and headless Services"},{"conceptTags":["k8s.dns"],"explanation":"Pods find Services by name. CoreDNS answers those names from the Kubernetes API, and the kubelet writes every pod's resolv.conf so that short names work. When a call cannot connect, the name has often resolved differently than you expected, or not at all.","id":"k8s.dns","objective":"Resolve Services and StatefulSet pods by short and fully qualified names across namespaces, explain the extra lookups that ndots:5 causes, and debug name resolution from inside a pod.","task":{"reading":{}},"title":"Cluster DNS: CoreDNS, service names, search domains and ndots"},{"conceptTags":["k8s.ingress"],"explanation":"A LoadBalancer per Service is expensive and knows nothing about HTTP. An Ingress describes HTTP routing, meaning hosts, paths and TLS, for many Services at once, and an ingress controller turns that description into proxy configuration. Without a controller an Ingress object does nothing at all.","id":"k8s.ingress","objective":"Write an Ingress with host and path rules for an IngressClass, route two Services behind one entry point, and tell a controller 404 from a controller 503.","task":{"reading":{}},"title":"Ingress: route HTTP by host and path through an ingress controller"},{"conceptTags":["k8s.network-policies"],"explanation":"Out of the box every pod can connect to every other pod in every namespace, so one compromised pod can reach your database. NetworkPolicies restrict that with allow-lists that the network plugin enforces. The rules are simple but not intuitive: there are no deny rules, and a policy changes the behaviour of the pods it selects, not of the sources it names.","id":"k8s.network-policies","objective":"Isolate pods with NetworkPolicies, allow traffic by pod label, namespace and IP block, build a default-deny baseline that keeps DNS working, and verify enforcement from a client pod.","task":{"reading":{}},"title":"NetworkPolicies: default deny and label-based allow-lists for pod traffic"},{"conceptTags":["k8s.traffic-debugging"],"explanation":"\"The site is down\" can mean a failure at any hop: DNS, the Ingress, the Service, its endpoints, pod readiness, the container port or the code. Each hop fails with its own signature, and the fastest debugging walks the path in order instead of guessing. This lesson builds that order and practises it on a Service under load.","id":"k8s.traffic-debugging","objective":"Follow a request from client to container port, read latency, saturation and error signals under load, and fix an overloaded Service and a bad release with scaling and kubectl rollout undo.","task":{"reading":{}},"title":"Debugging traffic end to end: latency, saturation, errors and rollbacks"}],"summary":"ClusterIP, NodePort and LoadBalancer Services, endpoints and targetPort, cluster DNS, Ingress routing, NetworkPolicies and end-to-end traffic debugging.","title":"Networking: Services, DNS, Ingress and policies","translationNote":"The traffic emulator models requests through Services, Ingress and policies; no socket opens. curl reaches the cluster through port-forward, NodePort, LoadBalancer IPs and Ingress hosts."},{"id":"k8s-config","lessons":[{"conceptTags":["k8s.configmaps"],"explanation":"A container image should be the same artifact in every environment; what differs between staging and production is configuration. A ConfigMap keeps that configuration in the cluster as key-value pairs that pods read as environment variables or as files. How a pod reads it decides what happens when the ConfigMap is missing and when it changes.","id":"k8s.configmaps","objective":"Store non-secret settings in a ConfigMap, consume them as environment variables or files, diagnose a missing ConfigMap or key, and roll pods so that they pick up a change.","task":{"reading":{}},"title":"ConfigMaps: settings for pods through env, envFrom and mounted files"},{"conceptTags":["k8s.secrets"],"explanation":"Passwords, API tokens and TLS keys must not be baked into images or ConfigMaps. A Secret is the Kubernetes object for them, and it looks protected because its values appear as gibberish. That gibberish is base64, which anyone can decode; the real protection comes from who may read the object, how etcd stores it, and what your application does with the value.","id":"k8s.secrets","objective":"Create Secrets from literals or stringData, deliver them as variables or files, and name the controls that actually keep them confidential: RBAC, encryption at rest, external managers and careful logging.","task":{"reading":{}},"title":"Secrets: credentials for pods, and why base64 is not protection"},{"conceptTags":["k8s.volumes-pvc"],"explanation":"Everything a container writes to its own filesystem disappears when the container is replaced. Volumes give pods storage with a defined lifetime: some last as long as the pod, others outlive every pod that ever used them. Most storage incidents come from not knowing which lifetime you asked for, or from a claim that can never be bound.","id":"k8s.volumes-pvc","objective":"Choose between ephemeral and persistent volumes, request storage with a PersistentVolumeClaim, read binding and provisioning status, and diagnose a pod stuck Pending on its claim.","task":{"reading":{}},"title":"Volumes and persistent storage: emptyDir, PersistentVolumeClaims and StorageClasses"},{"conceptTags":["k8s.namespaces-quotas"],"explanation":"One cluster usually serves several teams, services and environments, and all of them want a Deployment called web. Namespaces give each group its own space for names, permissions and policies. They are not a security boundary on their own and some objects ignore them entirely, so it pays to know exactly what they divide.","id":"k8s.namespaces-quotas","objective":"Use namespaces to scope names, access and policy, tell which objects are cluster-wide, cap a team's consumption with ResourceQuota and LimitRange, and delete a namespace knowing what goes with it.","task":{"reading":{}},"title":"Namespaces, ResourceQuotas and LimitRanges: dividing one cluster between teams"},{"conceptTags":["k8s.rbac"],"explanation":"Every request to the API server, from kubectl or from a controller running in a pod, is first authenticated to an identity and then authorized against rules. Role-based access control (RBAC) is how you write those rules. Done well, a compromised pod or a leaked kubeconfig can do little; done badly, everything quietly runs as cluster-admin.","id":"k8s.rbac","objective":"Tell authentication from authorization, grant a ServiceAccount exactly the verbs it needs with a Role and RoleBinding, verify the result with kubectl auth can-i, and call the API from Go with the pod's own identity.","task":{"reading":{}},"title":"RBAC: ServiceAccounts, Roles and bindings for least-privilege API access"}],"summary":"ConfigMaps and Secrets as environment and files, PersistentVolumeClaims and StorageClasses, namespaces and quotas, ServiceAccounts and RBAC.","title":"Configuration, secrets, storage and access","translationNote":"Secrets in the lab are as unencrypted as in a default cluster: base64 is an encoding. Production clusters need encryption at rest and a secret manager."},{"id":"k8s-operations","lessons":[{"conceptTags":["k8s.debugging-pods"],"explanation":"A broken pod always says why, but the answer is spread over its status, its events, the logs of the current and the previous container, and the state inside it. Opening the logs first misses pods that never started, and exec cannot reach a container that keeps restarting. A fixed triage order finds the cause in minutes and works the same during an incident at 3 a.m.","id":"k8s.debugging-pods","objective":"Find out why a pod is not working by reading its STATUS, the Events in describe, the current and previous logs, the container from inside and the namespace events, and fix the most common failures.","task":{"reading":{}},"title":"Debug failing pods: get, describe, logs, exec and events in order"},{"conceptTags":["k8s.autoscaling"],"explanation":"Load changes faster than anyone can run kubectl scale, and a fixed replica count is either too small at the peak or wasted at night. The HorizontalPodAutoscaler adjusts a Deployment's replica count from observed metrics. It only works when the pods declare CPU requests, metrics are flowing, and its reaction speed matches how fast the service can take on load.","id":"k8s.autoscaling","objective":"Create an autoscaling/v2 HorizontalPodAutoscaler on CPU utilization, predict its replica count from the formula, tune how fast it scales up and down, and place the Vertical Pod Autoscaler and the cluster autoscaler next to it.","task":{"reading":{}},"title":"Autoscale pods on CPU with the HorizontalPodAutoscaler, VPA and cluster autoscaler"},{"conceptTags":["k8s.node-failures"],"explanation":"Nodes fail: a kernel panic, a lost network link, a cloud instance retired underneath you. Kubernetes recovers by itself, but after deliberate delays and only for pods that a controller owns. Planned maintenance takes a different path, the Eviction API, and that is where PodDisruptionBudgets decide how many pods may go at once.","id":"k8s.node-failures","objective":"Explain the timeline from a lost node to rescheduled pods, protect planned maintenance with a PodDisruptionBudget, drain a node safely, and spread replicas so that one node or zone cannot take a service down.","task":{"reading":{}},"title":"When a node dies: NotReady, eviction, PodDisruptionBudgets and safe drains"},{"conceptTags":["k8s.kustomize-helm"],"explanation":"The same application runs in dev, staging and production with different image tags, replica counts, namespaces and settings. Copying the YAML for each environment drifts within weeks. Kustomize patches a shared base without templates and is built into kubectl; Helm renders a templated chart from values and tracks every release it installs.","id":"k8s.kustomize-helm","objective":"Build per-environment manifests from a shared base with Kustomize transformers and kubectl apply -k, explain Helm charts, values and releases, and choose between them and a GitOps controller.","task":{"reading":{}},"title":"Package manifests per environment with Kustomize overlays, Helm charts and GitOps"},{"conceptTags":["k8s.client-go"],"explanation":"Every controller in a cluster, including the one that runs Deployments, is a Go program built on client-go. A loop that calls List every few seconds overloads the API server and still misses short-lived changes. Informers, listers and workqueues let a controller react to every change from a local cache while its load on the API server stays small and bounded.","id":"k8s.client-go","objective":"Build a clientset from in-cluster or kubeconfig credentials, watch objects through a shared informer and lister, reconcile keys from a rate-limited workqueue, and shut a Go service down cleanly on SIGTERM.","task":{"reading":{}},"title":"Talk to the Kubernetes API from Go with client-go, informers and workqueues"},{"conceptTags":["k8s.production-checklist"],"explanation":"Most Kubernetes outages are not exotic: an image tag that moved, a pod without requests evicted first under memory pressure, a rollout that sent traffic to pods that were not ready, a token with more rights than the app needed. A checklist turns those incidents into review items that every Deployment passes before it ships.","id":"k8s.production-checklist","objective":"Review a Deployment against a production checklist and write one that pins its image, sizes its resources, probes its health, survives disruptions, runs with least privilege and shuts down cleanly.","task":{"reading":{}},"title":"A production checklist for Deployments, applied to gopherforge/web:v2 in the lab"}],"summary":"A triage method for broken pods, autoscaling under load, node failures and drains, kustomize and Helm, client-go controllers and a production checklist.","title":"Operating, scaling and debugging","translationNote":"Helm is explained but not simulated; kustomize runs with kubectl apply -k. Go snippets show client-go patterns for a real cluster."}]}