Kubernetes Architecture & Setup: Control Plane, Nodes, kubectl, Local & Managed Clusters, kubeadm
"Kubernetes comprises a set of independent, composable control processes that continuously drive the current state towards the provided desired state." — kubernetes.io, Overview ("What Kubernetes is not")
Summary: Kubernetes is a database of desired state (etcd) behind one REST API server, surrounded by independent control loops that watch that API and nudge reality towards it; every setup choice (kind, k3d, minikube, Docker Desktop, kubeadm, EKS, GKE, AKS) is only a different answer to "who runs those processes, and who upgrades them three times a year". Focus: What Kubernetes is and is not; the control plane (kube-apiserver, etcd and Raft, kube-scheduler, kube-controller-manager, cloud-controller-manager) and node components (kubelet, kube-proxy, the container runtime through the CRI: containerd, CRI-O); the declarative model (objects, apiVersion/kind/metadata/spec/status, desired state, reconciliation, the controller loop, list-then-watch, informers, resourceVersion and 410 Gone); API groups and versions, resource URIs, labels, selectors, annotations, namespaces; kubectl mechanics (kubeconfig, contexts, clusters, users, exec credential plugins, get/describe/explain/diff/apply, create vs apply, server-side apply, --dry-run=server, output formats, JSONPath, logs/exec/port-forward, plugins and krew); setup paths (kind, minikube, k3s, k3d, Docker Desktop and OrbStack Kubernetes, kubeadm, managed EKS/GKE/AKS and what each manages, node pools); the release cadence, version skew policy, upgrades, deprecations and API removals; cluster add-ons (CoreDNS, metrics-server, the archived Dashboard and Headlamp, CNI); a first deploy of the KB's Go service and a Laravel app as a php-fpm + nginx pod; and when not to use Kubernetes. Learning goal: Draw the cluster from memory and say which component is involved at each step of kubectl apply; read and fix a kubeconfig; drive kubectl with the right verbs and output formats; pick a local cluster and a managed offering and say what you still own; plan an upgrade that respects the skew policy and the API removal schedule; and ship a Go service and a Laravel app with manifests that pass an offline check and a server-side dry run.
This is the first chapter of the Kubernetes group. Why an organisation adopts containers and Kubernetes at all, the scheduling model and the service-mesh placement are in Containers & Kubernetes; this page is the mechanics and the setup. What a container is at the kernel level (namespaces, cgroups, runc) is Containers Under the Hood; building the images deployed here is Images & Dockerfiles. Everything previewed here is taught in its own chapter: Pods, probes, Deployments, StatefulSets, Jobs and rollouts in Kubernetes Workloads; ConfigMaps, Secrets and volumes in Config, Secrets & Storage; requests, limits, quotas and autoscaling in Resources, Scheduling & Autoscaling; RBAC, ServiceAccounts and admission policy in Kubernetes Security; Helm and Kustomize in Packaging for Kubernetes; events, logs and troubleshooting in Kubernetes Observability & Troubleshooting; CRDs and writing controllers in Go in Extending Kubernetes; CNI, Services, kube-proxy modes, CoreDNS, Ingress and Gateway API in Kubernetes Networking. The cloud accounts, VPCs and IAM a managed cluster lives in are Cloud Provider Primitives; Raft itself is in Distributed SQL, Consensus & 2PC. The command tables live in the kubectl cheatsheet.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a declarative API and control loops, and what Kubernetes is not | Why it exists |
| Borg, 2014, 1.0, CNCF, dockershim removal, today's 1.37 | Where it comes from |
| kube-apiserver, etcd and Raft, scheduler, controller managers | Control plane |
| kubelet, kube-proxy, CRI, containerd, CRI-O | Node components |
Objects, apiVersion, kind, metadata, spec, status | The object model |
| Desired state, reconciliation, the controller loop | Reconciliation |
List, watch, resourceVersion, informers, 410 Gone | Watch and informers |
| API server REST paths, API groups, versions | The REST API and API groups |
| Labels, selectors, annotations, namespaces, quotas | Labels, selectors, annotations, namespaces |
| kubeconfig, contexts, clusters, users, credential plugins | kubeconfig |
| get, describe, explain, diff, apply, create vs apply, SSA, dry-run | kubectl verbs |
-o wide/yaml/json/name/jsonpath/custom-columns, logs, exec, port-forward, krew | Output formats and day-to-day kubectl |
| kind, minikube, k3s, k3d, Docker Desktop, OrbStack | Local clusters |
| kubeadm, static Pods, self-managed control planes | kubeadm |
| EKS, GKE, AKS, what is managed, node pools | Managed Kubernetes |
| Release cadence, version skew policy, upgrades, API removals | Versions and upgrades |
| Admission, CNI, Services, Ingress/Gateway, add-ons, Helm | Previews |
| When not to use Kubernetes | When not to use Kubernetes |
| Flows, knobs, messages | Mechanics |
| Code | Go, Laravel |
| Classic problems | Solving the classic problems |
| Which local cluster, which managed offering, which apply mode | Choosing |
| From one VM to many clusters | In architecture |
| Commands with expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The components (kubernetes.io "Cluster Architecture" and "Kubernetes Components").
| Component | Where it runs | What it does | If it is down |
|---|---|---|---|
| kube-apiserver | Control plane, several instances behind a load balancer | "exposes the Kubernetes API"; authenticates, authorises, runs admission, validates, persists | No changes and no watches; running Pods keep running |
| etcd | Control plane (or external), 3 or 5 members | "Consistent and highly-available key value store" for all cluster data; Raft consensus | Loss of quorum: no writes, the API cannot serve consistent reads |
| kube-scheduler | Control plane, leader-elected | Watches Pods "with no assigned node, and selects a node for them" | New Pods stay Pending |
| kube-controller-manager | Control plane, leader-elected | Node, Job, EndpointSlice, ServiceAccount, Deployment... controllers "compiled into a single binary" | Nothing reconciles: no replacement Pods, no rollouts |
| cloud-controller-manager (optional) | Control plane, only in clouds | Node, route and service controllers that call the cloud API (load balancers) | No new cloud load balancers; dead VMs not noticed |
| kubelet | Every node | "makes sure that containers are running in a Pod"; reports node and Pod status | Node goes NotReady; Pods evicted after a grace period |
| kube-proxy (optional) | Every node | "Maintains network rules on nodes to implement Services" | Service traffic on that node breaks (unless the CNI replaces it) |
| Container runtime | Every node | containerd or CRI-O behind the CRI gRPC API; runc starts the processes | No new containers on that node |
| Add-ons | Pods in kube-system | Cluster DNS (CoreDNS), CNI plugin, metrics-server, ingress/gateway controller | DNS: almost everything fails; metrics: kubectl top and HPA fail |
Setup paths in one table.
| Option | Control plane run by | Nodes | Good for | Version on 2026-11-29 (from the saved release notes) |
|---|---|---|---|---|
| kind | kubeadm inside Docker containers ("node" = container) | Containers | CI, testing Kubernetes, multi-node on a laptop | kind v0.33.0, default node image kindest/node:v1.37.0@sha256:... |
| k3d | k3s server in a Docker container | k3s agents in containers | Fast local multi-node, built-in registry and load balancer | k3d v5.9.0 running k3s v1.37.2+k3s1 |
| minikube | A VM or container (docker, vfkit, qemu, hyperv, kvm2...) | One or more | Learning, add-ons, VM-level realism | minikube v1.39.0, default Kubernetes v1.37.0, containerd by default |
| k3s | A single binary ("less than 100 MB"), SQLite or embedded etcd | k3s agents | Edge, homelab, small VMs | v1.37.2+k3s1 |
| Docker Desktop / OrbStack | The desktop app (kubeadm or kind provisioner / OrbStack's k3s-based cluster) | One (Docker Desktop kind: several) | Zero-setup local cluster next to your images | Version set by the app (kind mode lets you choose) |
| kubeadm | You, on VMs or bare metal; control plane as static Pods | You | Self-managed and on-prem clusters, learning the real thing | Follows upstream (1.37) |
| EKS / GKE / AKS | The cloud provider | You (node groups/pools) or the provider (EKS Auto Mode, GKE Autopilot, AKS Automatic) | Production | Provider's supported list; GKE Rapid gets a minor "1-2 weeks after upstream open source GA" |
kubectl in one table.
| Verb | What it sends | Use it for | Trap |
|---|---|---|---|
get | GET (list or one object) | Looking: -o wide, -o yaml, -l app=x, -w | Default table hides most fields |
describe | Several GETs + Events | Why is it Pending / failing? | Human text, not for scripts |
explain | Reads the OpenAPI schema from the server | Field docs: kubectl explain deploy.spec.strategy | Needs a cluster (it asks the server) |
create -f | POST | One-off creation | Fails with AlreadyExists the second time; add --save-config if apply will manage it later |
apply -f | PATCH (client-side three-way merge, or server-side apply) | Declarative, repeatable | Mixing with edit/scale makes owners fight |
diff -f | Server-side dry-run apply, then a local diff | What would change? | Exit code 1 means "differences found" |
apply --dry-run=server | The full admission + validation chain, not persisted | CI gate before merge | Pods a Deployment would create are not checked (quota); webhooks must declare sideEffects |
logs / exec / port-forward | API server proxies to the kubelet | Debugging one Pod | Bypasses Services; one Pod only |
Why it exists
Before Kubernetes, "deploying ten copies of a service across forty machines" meant a script: pick machines, copy the binary, start it, register it with the load balancer, and hope. When a machine died at 3 a.m., a human ran the script again. The script described actions; when reality drifted (a process crashed, a disk filled, someone restarted something by hand), the script did not know.
Kubernetes inverts that. You store a description of the end state ("two replicas of orders-api:1.4.2, reachable as orders-api.shop") in a database, and a set of programs keep comparing that description with what actually runs and fix the difference, forever. The overview page states the consequence directly: Kubernetes "eliminates the need for orchestration. The technical definition of orchestration is execution of a defined workflow: first do A, then B, then C." Instead, independent control processes "continuously drive the current state towards the provided desired state. It shouldn't matter how you get from A to C."
| Simpler choice | Kubernetes choice | What you buy | What you pay |
|---|---|---|---|
| A deploy script with steps | Desired state stored in an API | Self-healing; drift corrected automatically | You must learn the object model and its controllers |
| Each tool talks to each host | One API server, everything else is a client | One place for authn, authz, audit, admission | The API server and etcd are now your most critical service |
| One big orchestrator | Many small controllers | Each loop is simple; a crash loses nothing | Behaviour emerges from loops; debugging means reading status and events |
| Hosts named in config | Labels and selectors | Groups are queries, not lists | A typo in a selector silently selects nothing |
| A VM per app | Bin-packing Pods on shared nodes | Utilisation, fast start | Noisy neighbours unless requests/limits are set |
| One vendor's PaaS | A portable API across clouds and laptops | Same manifests on kind and EKS | Three minor releases a year to keep up with |
What Kubernetes is not, in the overview's own list: it "is not a traditional, all-inclusive PaaS"; it "Does not deploy source code and does not build your application"; it "Does not provide application-level services, such as middleware ... databases ... caches"; it "Does not dictate logging, monitoring, or alerting solutions"; and it "Does not provide nor mandate a configuration language/system". CI (GitHub Actions, GitLab CI), packaging (Helm), GitOps (Argo CD, Flux) and infrastructure (Terraform) are all separate tools you bring.
The analogy used through this page: a restaurant kitchen with an order board. Waiters (kubectl, CI, Argo CD) never cook; they pin order tickets on one board (the API server, which writes them into a ledger: etcd). Station chefs (controllers) each watch the board for their kind of ticket; the head chef (scheduler) assigns each dish to a cooking station (node); the cook at each station (kubelet) reads the tickets assigned to that station and uses the stove (containerd) to cook. Nobody shouts instructions across the kitchen; everyone reads the board and writes progress back onto the ticket (status). If a cook faints, the dish still on the board is reassigned, because the ticket, not the cook, is the source of truth.
Three common misunderstandings, up front
- "
kubectl applydeploys my app." It stores a desired state and returns; the object page calls an object a "record of intent". Whether Pods start is decided afterwards by controllers, the scheduler and kubelets. Checkkubectl rollout statusorstatus.conditions. See Reconciliation. - "If the control plane is down, my app is down." Running Pods keep running; what stops is change (scheduling, scaling, self-healing, new endpoints). That is also why a managed control plane is the default choice: you want change back quickly, not your Pods restarted. See Control plane.
- "Kubernetes needs Docker." The kubelet talks to a CRI runtime (containerd or CRI-O); the built-in dockershim was removed in 1.24, and "the images produced from docker build will work with all CRI implementations". Docker is still a fine way to build images and to host kind/k3d clusters. See Node components.
Where it comes from
| When | What happened | Source |
|---|---|---|
| Before 2014 | Google runs production on Borg; Kubernetes "combines over 15 years of Google's experience running production workloads at scale" | kubernetes.io overview; GKE overview names Borg |
| 6 June 2014 | "Kubernetes was announced by Google on June 6, 2014" | Wikipedia |
| 21 July 2015 | Kubernetes 1.0 at OSCON; Google and the Linux Foundation form the CNCF "and offered Kubernetes as the seed technology" | Wikipedia; Kubernetes blog, history post (2018) |
| 1.13 | CoreDNS becomes the default cluster DNS ("CoreDNS has been the default cluster DNS add-on since Kubernetes v1.13") | 1.37 release blog |
| 1.16 / 1.22 / 1.25 | Big API removals: extensions/v1beta1 Deployments/DaemonSets (1.16), Ingress v1beta1 and CRD v1beta1 (1.22), PodSecurityPolicy and CronJob batch/v1beta1 (1.25) | Deprecated API Migration Guide |
| 1.22 | Server-side apply GA ("stable ... since the 1.22 release") | Server-Side Apply page |
| 1.23 / 1.26 | CRI "Stable since Kubernetes v1.23"; from v1.26 "the kubelet requires that the container runtime supports the v1 CRI API" | CRI page |
| 1.24 | The in-tree dockershim is removed; cri-dockerd is the external adapter for Docker Engine | Dockershim FAQ |
| 1.35 | Last release supporting containerd 1.x ("The last Kubernetes release to offer this support will be v1.35") | 1.34 release blog |
| By 2026 | Kubernetes Dashboard archived ("no longer maintained"); the project points to Headlamp | Dashboard README |
| 26 Aug 2026 | Kubernetes v1.37 "Garhwal": 67 enhancements; kube-dns and kube-proxy's ipvs mode deprecated | 1.37 release blog |
| 29 Nov 2026 | Release branches maintained for "the most recent three minor releases (1.37, 1.36, 1.35)"; the release history page lists 1.37.2 (2026-10-13) as latest while dl.k8s.io/release/stable.txt already returns v1.37.3 | Version skew policy; releases page; stable.txt |
Two lineages explain today's shape. From Borg came the ideas of a declarative job description, labels instead of hostnames, and a central state store. From the container ecosystem came the runtime: Kubernetes first drove Docker Engine directly, then introduced the CRI so that any runtime could plug in, and finally removed the Docker-specific shim. The API grew by groups (apps, batch, networking.k8s.io...) with alpha, beta and GA versions, and a deprecation policy that is why upgrades sometimes break old manifests.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.
The control plane: kube-apiserver, etcd and Raft, kube-scheduler, kube-controller-manager, cloud-controller-manager Must-know
In plain words: The control plane is the brain: one API server everyone talks to, a replicated database behind it, a scheduler that picks nodes, and controller programs that keep fixing the cluster. It runs no user containers in production.
Common misunderstanding: "The scheduler starts my containers." The scheduler only writes a node name into the Pod (a binding); the kubelet on that node starts the containers. Equally, controllers do not touch nodes: "The Job controller does not run any Pods or containers itself. Instead, the Job controller tells the API server to create or remove Pods."
Definition: The architecture page: the control plane's components "make global decisions about the cluster (for example, scheduling), as well as detecting and responding to cluster events". kube-apiserver is "the front end for the Kubernetes control plane" and "is designed to scale horizontally"; it is the only component that talks to etcd. etcd is the "Consistent and highly-available key value store used as Kubernetes' backing store for all cluster data". etcd uses Raft, "a consensus algorithm that is designed to be easy to understand": a write commits once "(n/2)+1 members, a majority" agree, so a 3-member cluster tolerates 1 failure and 5 members tolerate 2 (etcd FAQ table). etcd's own docs say it is for "systems that will never tolerate split-brain operation and are willing to sacrifice availability to achieve this end". kube-scheduler "watches for newly created Pods with no assigned node, and selects a node for them to run on", weighing resource requirements, constraints, affinity, data locality and deadlines. kube-controller-manager runs the built-in controllers; "Logically, each controller is a separate process, but to reduce complexity, they are all compiled into a single binary". cloud-controller-manager "embeds cloud-specific control logic" (node, route and service controllers); "If you are running Kubernetes on your own premises, or in a learning environment inside your own PC, the cluster does not have a cloud controller manager."
A 3-member etcd under kube-apiserver, one member's disk dies
1 apiserver -> etcd leader: put /registry/deployments/shop/orders-api (resourceVersion++)
2 leader appends to its Raft log, replicates to followers
3 2 of 3 members persisted (quorum = 2) -> commit -> apiserver gets the new revision
4 member 3 dies: quorum still 2 of 3 -> writes continue
5 member 2 also dies: 1 of 3 -> no quorum -> writes fail; the API cannot serve
consistent data; running Pods are unaffected, nothing new can be scheduled
6 restore one member -> quorum regained -> etcd "automatically and safely resumes"Real scenarios:
- A team runs a single control-plane VM with etcd on a slow network disk;
kubectl applytimes out under load while traffic is fine. etcd's FAQ: "performance strongly depends on disk performance. For this reason, SSD is highly recommended." - An EKS cluster's API endpoint is unreachable during a VPN outage: Pods keep serving, but the HPA cannot scale and a node failure is not repaired until the API is back.
- Someone adds a fourth etcd member "for safety": the quorum becomes 3 of 4 and fault tolerance stays at 1 (etcd: "Adding a member to bring the size of cluster up to an even number doesn't buy additional fault tolerance").
- A Service of type
LoadBalancerstays<pending>on a kubeadm cluster on bare metal: there is no cloud-controller-manager to create a load balancer (MetalLB or kube-vip fill that gap).
| Product | Who runs the control plane | Notes |
|---|---|---|
| kubeadm | You; components are static Pods in /etc/kubernetes/manifests, etcd stacked or external | Highly available needs a load balancer in front of several API servers |
| k3s / k3d | The k3s server process; "an embedded SQLite database" for one server, embedded etcd for HA | Same API, fewer binaries |
| kind | kubeadm inside the control-plane container(s); several control-plane nodes possible | For tests, not production HA |
| EKS / GKE / AKS | The provider ("AWS manages the Kubernetes control plane"; AKS creates it "at no cost") | You never see etcd; you pay per cluster-hour on EKS and GKE Standard |
Fix / how to use it: run an odd number of etcd members (3, or 5 for large clusters) on SSDs in separate failure domains, back up etcd (etcdctl snapshot save on kubeadm clusters; the managed providers do it for you), put the API servers behind a load balancer, and treat the control plane's health (API latency, etcd fsync time) as a first-class SLO. Leader election for the scheduler and controller manager uses Lease objects, the same pattern as in the Containers & Kubernetes chapter.
Node components: kubelet, kube-proxy, the container runtime, CRI, containerd, CRI-O Must-know
In plain words: Every node runs an agent (kubelet) that asks the API server "which Pods are mine?" and makes them true by calling the container runtime, plus usually a kube-proxy that turns Service IPs into routing rules.
Common misunderstanding: "kubelet manages every container on the machine." "The kubelet doesn't manage containers which were not created by Kubernetes." A container you start with nerdctl or docker run on a node is invisible to Kubernetes, and kubelet will happily evict around it.
Definition: The kubelet "takes a set of PodSpecs that are provided through various mechanisms and ensures that the containers described in those PodSpecs are running and healthy." It self-registers the Node object (--register-node, true by default) and sends heartbeats in two forms: "Updates to the .status of a Node" and "Lease objects within the kube-node-lease namespace". The node controller checks nodes "every 5 seconds", sets Ready=Unknown for an unreachable node and "waits 5 minutes between marking the node as Unknown and submitting the first eviction request". kube-proxy "maintains network rules on nodes"; "If you use a network plugin that implements packet forwarding for Services by itself ... then you do not need to run kube-proxy" (Cilium's kube-proxy replacement is the common example). The container runtime is reached through the CRI, "the main gRPC protocol for the communication between the node components kubelet and container runtime"; "The kubelet acts as a client when connecting to the container runtime via gRPC", and since v1.26 the runtime must speak CRI v1 or "the kubelet will not register the node". Kubernetes "supports container runtimes such as containerd, CRI-O, and any other implementation of the Kubernetes CRI".
A Pod bound to node-2: what the kubelet does
1 kubelet watch (fieldSelector spec.nodeName=node-2) delivers Pod shop/orders-api-7f9c-abcde
2 CRI RunPodSandbox -> containerd creates the pause container: network + IPC namespaces
3 CNI ADD -> the network plugin gives the sandbox an IP
4 CRI PullImage -> ghcr.io/acme/orders-api:1.4.2 (unless present and policy allows)
5 CRI CreateContainer + StartContainer -> runc starts /orders-api as UID 65532
6 kubelet runs readiness/liveness probes, writes status: Running, Ready=True, podIP
7 on delete: CRI StopContainer with the grace period (SIGTERM, then SIGKILL after 30 s by default)Real scenarios:
- After an OS upgrade, a node stays
NotReadywithcontainer runtime network not ready: the CNI config directory is empty, so sandboxes cannot get IPs. - A cluster upgraded to 1.36 has a node still on containerd 1.7; the 1.34 release notes had warned "if you are using containerd 1.X, consider switching to 2.0+ soon".
- A laptop runs
docker psinside a kind node and sees only kindest/node's own containers; the Pods' containers are visible withcrictl psinside the node. - A team moving from Docker Engine on nodes (pre-1.24) to containerd changes nothing in its images, but node-level scripts that called
dockerbreak.
| Runtime | Relationship to Kubernetes | Notes |
|---|---|---|
| containerd (2.x) | CRI plugin built in; default in kind, k3s, minikube 1.39, EKS, GKE (cos_containerd), AKS | CNCF graduated; also what Docker Engine uses underneath |
| CRI-O | A runtime built only for Kubernetes' CRI | Default in OpenShift; versions track Kubernetes minors |
| Docker Engine + cri-dockerd | External adapter since the dockershim removal | Rare in new clusters |
| gVisor, Kata (via RuntimeClass) | Sandboxed runtimes behind containerd/CRI-O | Isolation for untrusted workloads (Container Security) |
Fix / how to use it: keep node images (OS, containerd, kubelet) as one unit and replace nodes rather than patch them; debug nodes with kubectl describe node, crictl and the kubelet's journal; and let the managed node image (Bottlerocket, COS, Azure Linux, AL2023) carry the runtime version. The runtime stack below the CRI (containerd shims, runc, cgroups) is Containers Under the Hood.
The object model: apiVersion, kind, metadata, spec, status Must-know
In plain words: Everything in Kubernetes is a typed record with a name. You write the spec (what you want); the system writes the status (what it sees). The YAML file is just that record.
Common misunderstanding: "I should put status in my manifest" or "editing status fixes things". Status is "supplied and updated by the Kubernetes system and its components"; clients that write spec cannot even change it through the main endpoint (it is a separate /status subresource).
Definition: "Kubernetes objects are persistent entities in the Kubernetes system." Every manifest needs the required fields: apiVersion ("Which version of the Kubernetes API you're using to create this object"), kind ("What kind of object you want to create"), metadata ("Data that helps uniquely identify the object, including a name string, UID, and optional namespace"), and, for most kinds, spec: "you have to set this when you create the object, providing a description of the characteristics you want the resource to have: its desired state." status "describes the current state of the object". Identity: "Within a namespace, an object's unique identity is defined by the tuple of its API Group, Resource, Namespace, and Name." Metadata also carries uid, resourceVersion, generation, labels, annotations, ownerReferences (a ReplicaSet owns its Pods; garbage collection deletes dependents with their owner) and managedFields (server-side apply).
One Deployment through its life (fields that change)
1 you: metadata.generation=1, spec.replicas=2, spec.template.image=orders-api:1.4.2
2 controller: status.observedGeneration=1, status.replicas=2, status.readyReplicas=0
3 kubelets: Pods become Ready -> status.readyReplicas=2, condition Available=True
4 you edit: spec image -> 1.4.3 -> metadata.generation=2 (status edits never bump it)
5 controller: observedGeneration=2 once it has acted; rollout complete when updated == ready
-> "is my change applied?" = observedGeneration == generation AND the conditions say soReal scenarios: a GitOps diff shows noise because someone committed status: and metadata.uid from kubectl get -o yaml; a Deployment rename creates a second Deployment (the name is identity, not a label); two objects named shop coexist because one is a Namespace and one is a ConfigMap; a CI script waits on observedGeneration to know that the controller saw the change.
| Field | Written by | Notes |
|---|---|---|
apiVersion, kind | You | apps/v1 + Deployment; core types use plain v1 |
metadata.name, namespace, labels, annotations | You | Name rules: DNS-1123 for most kinds |
metadata.uid, resourceVersion, creationTimestamp, managedFields | API server | Never commit them |
spec | You (or a higher controller) | Desired state |
status | Controllers, kubelet | Observed state, via the /status subresource |
Fix / how to use it: keep manifests minimal (only fields you have an opinion on), strip server fields before committing (kubectl get -o yaml output is not a manifest), and read kubectl explain <type>.<field> instead of guessing field names.
Desired state, reconciliation and the controller loop Must-know
In plain words: A controller is a loop: look at what you want, look at what is, do one thing to close the gap, repeat. Many small loops, each owning one kind of object, together run the cluster.
Common misunderstanding: "Controllers react to events, so a missed event means a missed action." Kubernetes controllers are level-triggered: they reconcile the current state, so a restarted controller simply lists everything and continues. Events only tell them when to look.
Definition: "In Kubernetes, controllers are control loops that watch the state of your cluster, then make or request changes where needed. Each controller tries to move the current cluster state closer to the desired state." The docs' analogy is a thermostat (desired temperature vs current). Design principle: "It's useful to have simple controllers rather than one, monolithic set of control loops that are interlinked. Controllers can fail, so Kubernetes is designed to allow for that." Controllers tell their objects apart by labels and owner references: "The Job controller does not delete the Pods that your Deployment created, because there is information (labels) the controllers can use to tell those Pods apart." The docs also warn that "potentially, your cluster never reaches a stable state", and that is fine as long as controllers keep making progress.
Deployment orders-api, replicas 2 -> one node dies
1 node controller: node-3 heartbeats stop -> Ready=Unknown -> after 5 min, evict its Pods
2 Pod orders-api-abc on node-3 is deleted (API write)
3 ReplicaSet controller (watch): owns 1 Pod, wants 2 -> creates orders-api-xyz (API write)
4 scheduler (watch): orders-api-xyz has no node -> binds it to node-1
5 kubelet on node-1 (watch): starts it; EndpointSlice controller adds its IP when Ready
-> no component called another; each reacted to the boardReal scenarios: kubectl scale --replicas=10 during an incident is undone by Argo CD a minute later because Git says 2 (one owner per field); an HPA and a Deployment manifest both set replicas and fight; a PostgreSQL operator reconciles a custom Cluster object into StatefulSets and Services; kubectl delete pod "fixes" a stuck Pod only because the ReplicaSet makes a new one.
| Controller (in kube-controller-manager unless noted) | Watches | Writes |
|---|---|---|
| Deployment | Deployments, ReplicaSets | ReplicaSets (one per template revision) |
| ReplicaSet | ReplicaSets, Pods | Pods |
| Node | Nodes, Leases | Node conditions, evictions |
| EndpointSlice | Services, Pods | EndpointSlices |
| Job | Jobs, Pods | Pods, Job status |
| Namespace | Namespaces | Deletes everything in a terminating namespace |
| Service (cloud-controller-manager) | Services of type LoadBalancer | Cloud load balancers |
| Your operator (Argo CD, cert-manager, CloudNativePG) | Its custom resources | Kubernetes objects or external systems |
Fix / how to use it: declare, then observe: write manifests, then read status.conditions and events; give each field exactly one owner; never "fix" a controller-owned object by hand (fix its owner). Writing your own controller is Extending Kubernetes; the architectural view is in Containers & Kubernetes.
Watch, resourceVersion and informers Must-know
In plain words: Controllers do not poll. They list once, remember a version number, and keep a long HTTP connection open on which the API server streams every change after that number. A library (client-go's informers) keeps a local copy so the controller can read without asking the API server.
Common misunderstanding: "A watch replays everything since I last connected." Only for a limited window: "Clusters using etcd 3 preserve changes in the last 5 minutes by default." After that, the server answers 410 Gone and the client must list again.
Definition: "every Kubernetes object has a resourceVersion field representing the version of that resource as stored in the underlying persistence layer." A list returns a collection resourceVersion; "The client can use that resourceVersion to initiate a watch", and the server streams ADDED, MODIFIED, DELETED (and BOOKMARK) events. When history is gone, clients "must handle the case by recognizing the status code 410 Gone, clearing their local cache, performing a new get or list operation, and starting the watch from the resourceVersion that was returned." In Go, "this is called a Reflector and is located in the k8s.io/client-go/tools/cache package". The sample-controller docs describe the trio: the Reflector "watches the Kubernetes API for the specified resource type"; the Informer "pops objects from the Delta Fifo queue" and saves them "for later retrieval"; the Indexer keeps "a thread-safe data store"; event handlers "obtain the dispatched object's key and enqueue that key in a work queue". Since 1.37 the API server also protects etcd during cache warm-up and "rejects others with HTTP 429 responses", so clients should respect Retry-After and back off.
GET /api/v1/namespaces/test/pods -> PodList, metadata.resourceVersion "10245"
GET /api/v1/namespaces/test/pods?watch=1&resourceVersion=10245
{"type":"ADDED", "object":{... "resourceVersion":"10596" ...}}
{"type":"MODIFIED", "object":{... "resourceVersion":"11020" ...}}
(connection drops for 10 minutes; etcd compacts)
GET ...?watch=1&resourceVersion=11020 -> 410 Gone
GET /api/v1/namespaces/test/pods -> fresh list, new resourceVersion; resumeReal scenarios: a homemade "deployment notifier" polls kubectl get pods every second across 2,000 Pods and becomes the API server's top client; a controller that ignores 410 stops seeing changes after a network blip; a Go operator reads from its informer cache and briefly sees a stale object (it must tolerate that and rely on optimistic concurrency); kubectl get pods -w is the same watch, printed.
| Client | How it watches | Cache |
|---|---|---|
| client-go informers (Go controllers, kube-controller-manager) | Reflector ListAndWatch, relist on 410 | Indexer, shared across controllers in one process |
| controller-runtime (Kubebuilder, Operator SDK) | Informers underneath | Cached client by default |
kubectl get -w | One watch, printed | None |
| Argo CD, Flux | Informers on many kinds | Large in-memory caches |
| Your script with curl | Polling | None: avoid at scale |
Fix / how to use it: in Go, use shared informers and a rate-limited work queue (not raw polling); treat events as "something changed, reconcile this key"; handle 410 and 429. The toy model in Go shows the relist and de-duplication rules in 200 lines.
The REST API, API groups and versions Must-know
In plain words: Behind kubectl is a plain HTTPS REST API. The URL tells you the group, the version, the namespace and the resource. apiVersion: apps/v1 in YAML is literally the /apis/apps/v1 part of the URL.
Common misunderstanding: "v1beta1 and v1 are different objects." "Different API Versions (such as v1 and v1beta1) of the same Group and Resource represent the same underlying data"; the server converts between them. That is why an old object survives an API removal but an old manifest fails to apply.
Definition: "All resource types are either scoped by the cluster (/apis/GROUP/VERSION/*) or to a namespace (/apis/GROUP/VERSION/namespaces/NAMESPACE/*)"; "core resources use /api instead of /apis and omit the GROUP path segment". Terms: a resource type is the URL name (pods), its schema is a kind (Pod), a list is a collection, sub-resources sit below an object (/status, /scale, /log, /exec, /eviction). Verbs: get, list, watch, create, update, patch, delete; "If you sent an HTTP GET request with the ?watch query parameter, Kubernetes calls this a watch and not a get." Versions follow stability levels: alpha (v1alpha1, "may be removed in any release without prior deprecation notice"), beta (v1beta1) and GA (v1, "must not be removed within a major version").
kubectl -n shop get deployment orders-api -o yaml (with -v=6 you see the request line)
1 kubeconfig -> server https://127.0.0.1:6443, credentials of the current context
2 discovery: GET /api, GET /apis -> group "apps" serves v1 (cached under ~/.kube/cache)
3 GET https://127.0.0.1:6443/apis/apps/v1/namespaces/shop/deployments/orders-api
4 200 OK, JSON (or protobuf/CBOR when negotiated) -> kubectl renders YAML| Kind | Group / version | URL (namespaced) |
|---|---|---|
| Pod, Service, ConfigMap, Secret, Namespace, Node | core v1 | /api/v1/namespaces/shop/pods (Nodes and Namespaces are cluster-scoped) |
| Deployment, ReplicaSet, StatefulSet, DaemonSet | apps/v1 | /apis/apps/v1/namespaces/shop/deployments |
| Job, CronJob | batch/v1 | /apis/batch/v1/namespaces/shop/jobs |
| Ingress, NetworkPolicy | networking.k8s.io/v1 | /apis/networking.k8s.io/v1/... |
| HTTPRoute, Gateway | gateway.networking.k8s.io/v1 (a CRD set) | Installed separately |
| Role, RoleBinding | rbac.authorization.k8s.io/v1 | /apis/rbac.authorization.k8s.io/v1/... |
| HorizontalPodAutoscaler | autoscaling/v2 | /apis/autoscaling/v2/... |
Fix / how to use it: kubectl api-resources lists every resource with its group, short name and scope; kubectl api-versions lists served versions; kubectl get --raw /apis/apps/v1 | jq shows discovery as the API server serves it. Build manifests against GA versions whenever one exists.
Labels, selectors, annotations, namespaces (and resource quotas preview) Must-know
In plain words: Labels are short tags you query by; selectors are the queries; annotations are notes for tools; namespaces are folders that scope names, permissions and quotas.
Common misunderstanding: "Namespaces isolate workloads." They scope names, RBAC and quotas; by default Pods in different namespaces can still talk to each other over the network (NetworkPolicy, taught in Kubernetes Networking, changes that), and they share nodes.
Definition: "Labels are key/value pairs" used to "organize and to select subsets of objects"; keys have an optional prefix (DNS subdomain, at most 253 characters) and a name that "must be 63 characters or less"; values "must be 63 characters or less (can be empty)". "The API currently supports two types of selectors: equality-based and set-based" (app=shop,tier!=cache; env in (prod,staging)), and "there is no logical OR (||) operator". Annotations "attach arbitrary non-identifying metadata to objects" (build info, kubernetes.io/change-cause, tool settings) and cannot be selected on. Field selectors filter on fields such as status.phase=Running or spec.nodeName=node-1. "Kubernetes starts with four initial namespaces": default, kube-node-lease, kube-public, kube-system; and the docs advise "For a production cluster, consider not using the default namespace." A Service's DNS name includes its namespace: <service-name>.<namespace-name>.svc.cluster.local. A ResourceQuota caps totals per namespace (Pods, CPU and memory requests); with a CPU or memory quota present, every container must declare requests or the API rejects the Pod (taught in Resources, Scheduling & Autoscaling).
How a Service finds Pods, by labels only
1 Deployment template labels: app.kubernetes.io/name=orders-api
2 Service selector: app.kubernetes.io/name=orders-api
3 EndpointSlice controller lists Pods matching the selector AND Ready -> endpoints
4 typo in the Service selector (orders_api) -> zero endpoints, no error anywhere
5 kubectl -n shop get endpointslices -l kubernetes.io/service-name=orders-api -> emptyRecommended label (app.kubernetes.io/...) | Example | Used by |
|---|---|---|
name | orders-api | Selectors, dashboards |
instance | orders-api-prod | Distinguishing several installs |
version | 1.4.2 | Never in a selector (it changes) |
component | api, worker | Grouping roles |
part-of | shop | The application as a whole |
managed-by | Helm, argocd | Who owns the object |
Fix / how to use it: use the recommended app.kubernetes.io/* labels, keep selectors to stable labels (never version), put notes in annotations, give each team or app a namespace with a quota, and check selectors offline (the Go manifest check does it).
kubeconfig: clusters, users, contexts, credential plugins Must-know
In plain words: kubeconfig is kubectl's address book: a list of clusters (where), users (who), and contexts (a named pair of cluster + user + default namespace). The current context decides where every command goes.
Common misunderstanding: "kubeconfig is a harmless settings file." The docs warn: "Only use kubeconfig files from trusted sources. Using a specially-crafted kubeconfig file could result in malicious code execution or file exposure." An exec entry runs a program on your machine; a kubeconfig with an embedded client key is a password.
Definition: "By default, kubectl looks for a file named config in the $HOME/.kube directory. You can specify other kubeconfig files by setting the KUBECONFIG environment variable or by setting the --kubeconfig flag." "Each context has three parameters: cluster, namespace, and user." Merging: "If the --kubeconfig flag is set, use only the specified file. Do not merge." Otherwise the files in KUBECONFIG ("colon-delimited" on Linux and Mac) are merged and "The first file to set a particular value or map key wins." Users authenticate with client certificates, bearer tokens, or exec credential plugins: "Credential plugins are configured through kubectl config files as part of the user fields"; the plugin returns an ExecCredential and its apiVersion "MUST match the version listed here"; interactiveMode is Never, IfAvailable or Always. Cloud CLIs write these entries for you (aws eks update-kubeconfig, gcloud container clusters get-credentials with gke-gcloud-auth-plugin, az aks get-credentials).
# A kubeconfig with one local and two managed clusters. Shape from
# kubernetes.io "Organizing Cluster Access Using kubeconfig Files" and the
# client-go credential plugin example. Endpoints, paths and names are
# placeholders; certificate files are referenced by path, never pasted here.
# Real files are written by `kind create cluster`, `aws eks update-kubeconfig`,
# `gcloud container clusters get-credentials` or `az aks get-credentials`.
apiVersion: v1
kind: Config
preferences: {}
current-context: kind-shop
clusters:
- name: kind-shop
cluster:
server: https://127.0.0.1:6443 # kind picks a random host port; read it from `kind get kubeconfig`
certificate-authority: /Users/dev/.kube/certs/kind-shop-ca.crt
- name: eks-shop-prod
cluster:
server: https://0123456789ABCDEF.gr7.eu-central-1.eks.amazonaws.com # placeholder endpoint
certificate-authority: /Users/dev/.kube/certs/eks-shop-prod-ca.crt
- name: gke-shop-staging
cluster:
server: https://203.0.113.10 # placeholder (documentation address range)
certificate-authority: /Users/dev/.kube/certs/gke-shop-staging-ca.crt
users:
- name: kind-shop-admin
user:
client-certificate: /Users/dev/.kube/certs/kind-shop-admin.crt
client-key: /Users/dev/.kube/certs/kind-shop-admin.key
- name: eks-shop-prod-sso
user:
exec: # a short-lived token from the cloud CLI on every request batch
apiVersion: client.authentication.k8s.io/v1
command: aws
args: [eks, get-token, --cluster-name, shop-prod, --region, eu-central-1]
env:
- name: AWS_PROFILE
value: shop-prod-readonly
interactiveMode: Never
provideClusterInfo: false
- name: gke-shop-staging-user
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: gke-gcloud-auth-plugin
installHint: Install gke-gcloud-auth-plugin with the gcloud CLI components.
interactiveMode: IfAvailable
provideClusterInfo: true
contexts: # context = cluster + user + default namespace
- name: kind-shop
context:
cluster: kind-shop
user: kind-shop-admin
namespace: shop
- name: prod
context:
cluster: eks-shop-prod
user: eks-shop-prod-sso
namespace: shop
- name: staging
context:
cluster: gke-shop-staging
user: gke-shop-staging-user
namespace: shopkubectl -n shop get pods with KUBECONFIG=~/.kube/config:~/work/eks.yaml
1 merge both files; first file to set current-context wins -> kind-shop
2 context kind-shop -> cluster kind-shop (server, CA) + user kind-shop-admin (client cert)
3 -n shop overrides the context's namespace for this command only
4 user has exec? run the plugin, read ExecCredential.status.token, cache until expiry
5 TLS to the server using the cluster CA; send the credential; get the answerReal scenarios: a developer runs kubectl delete ns shop in the wrong context (prod instead of kind) because a new terminal inherited KUBECONFIG; a CI job fails with exec: executable aws not found (client-go's exec-plugin message) because the runner image lacks the CLI the exec plugin calls; two clusters both create a user named admin and merging silently keeps the first one; a contractor's kubeconfig still works months later because it embeds a client certificate that cannot be revoked easily.
| Tool | What it writes | Credential |
|---|---|---|
| kind | Context kind-<name> | Embedded client cert (admin) |
| k3d | Context k3d-<name> (updateDefaultKubeconfig: true) | Embedded client cert |
| minikube | Context named after the profile | Client cert files under ~/.minikube |
| Docker Desktop | Context docker-desktop | Embedded client cert |
| EKS | aws eks update-kubeconfig --region region-code --name my-cluster | exec aws eks get-token (IAM identity) |
| GKE | gcloud container clusters get-credentials | exec gke-gcloud-auth-plugin |
| AKS | az aks get-credentials --resource-group ... --name ... | Entra ID via kubelogin, or a local admin cert |
Fix / how to use it: one file per cluster, combined through KUBECONFIG only when needed; production contexts with short-lived exec credentials, never long-lived certificates; a prompt or kubectl config current-context in your shell; kubectx/kubens (krew plugins) or kubectl config use-context and set-context --current --namespace. The Lab shows get-contexts, use-context and view --minify run against this file.
kubectl verbs: get, describe, explain, create vs apply, server-side apply, kubectl diff, dry-run Must-know
In plain words: kubectl is an HTTP client with good manners. get and describe read; create, replace and delete are imperative; apply says "make the live object look like this file", and diff and --dry-run=server let you see what that would do first.
Common misunderstanding: "create and apply are interchangeable." create is imperative object configuration: it fails if the object exists. apply is declarative (it creates the object if missing and updates it otherwise), but it was designed for objects it created: the reference says "To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'". apply it computes a patch, and client-side apply stores the last applied file in the annotation kubectl.kubernetes.io/last-applied-configuration so a field you remove from the file can be removed from the object. The docs table: imperative commands for "Development projects", imperative object configuration and declarative configuration for "Production projects", and the warning "A Kubernetes object should be managed using only one technique. Mixing and matching techniques for the same object results in undefined behavior."
Definition: Server-side apply (stable since 1.22) moves the merge into the API server: "The Kubernetes API server tracks managed fields for all newly created objects. When trying to apply an object, fields that have a different value and are owned by another manager will result in a conflict." "A fully specified intent is a partial object that only includes the fields and values for which the user has an opinion." Conflicts are resolved by changing your file, by giving up the field, or by forcing ownership (--force-conflicts). It "is meant both as a replacement for the original client-side implementation of the kubectl apply subcommand, and as simple and effective mechanism for controllers". Migration: kubectl apply --server-side [--dry-run=server]; "The default field manager for kubectl server-side apply is kubectl." Dry-run: --dry-run=client only renders locally; --dry-run=server sends the request through authentication, authorisation, mutating and validating admission and schema validation without persisting. kubectl diff shows the difference between the live object and what an apply would produce (it uses a server-side dry run). kubectl explain prints field documentation from the server's OpenAPI schema.
Client-side apply vs server-side apply, same file, after an HPA scaled replicas to 5
CSA 1 kubectl GET live object + last-applied annotation
2 three-way merge (file, last-applied, live) on your laptop; replicas: 2 in file
3 PATCH -> replicas back to 2; the HPA sets it to 5 again; they fight silently
SSA 1 PATCH application/apply-patch+yaml with fieldManager=kubectl
2 server: spec.replicas is managed by the HPA's manager -> 409 Conflict
3 you remove replicas from the file (let the HPA own it) or --force-conflictsReal scenarios: objects first made with kubectl create -f from a README are later managed with kubectl apply -f in CI: the apply updates them, but with no last-applied-configuration annotation the first three-way merge cannot know which fields to remove, so a field deleted from the file stays on the live object (the docs' migration path is kubectl replace --save-config -f <file> once, then apply only; with server-side apply, fields written by other managers show up as conflicts instead); kubectl edit in production is overwritten by the next GitOps sync; a reviewer asks "what does this PR change in the cluster?" and the pipeline runs kubectl diff -f k8s/ against staging; kubectl explain deployment.spec.strategy.rollingUpdate replaces a web search.
| Command | Mode | Persisted? | Good for |
|---|---|---|---|
kubectl run, create deployment, expose, scale | Imperative commands | Yes | Learning, emergencies |
kubectl create -f, replace -f, delete -f | Imperative object configuration | Yes | Scripts that know the object does not exist |
kubectl apply -f (client-side) | Declarative, last-applied annotation | Yes | Teams without SSA yet |
kubectl apply --server-side -f | Declarative, field ownership | Yes | Multiple appliers, controllers, GitOps |
kubectl apply --dry-run=server -f / kubectl diff -f | Validation preview | No | CI gates |
kubectl create ... --dry-run=client -o yaml | Local rendering | No | Generating a starting manifest |
Fix / how to use it: in CI run kubectl apply --server-side --dry-run=server -f k8s/ and kubectl diff -f k8s/ against the target cluster (they validate the objects sent, not the Pods controllers create later); apply with server-side apply (or let Argo CD or Flux do it; both support SSA); never mix edit/scale with a declarative owner; use create --dry-run=client -o yaml only to bootstrap a file (the Lab shows its real output).
Output formats, jsonpath, kubectl logs exec port-forward, krew plugins Important
In plain words: -o decides how kubectl prints. Tables for eyes, YAML/JSON for reading whole objects, name and jsonpath for scripts. logs, exec and port-forward reach one Pod through the API server. Plugins are just executables named kubectl-something.
Common misunderstanding: "kubectl port-forward tests my Service." It tunnels to one Pod (even port-forward svc/x picks one Pod), bypassing kube-proxy, readiness and load balancing. It is a debugging tool, not a way to expose anything.
Definition: Output formats from the kubectl reference: -o custom-columns=<spec>, -o json, -o jsonpath=<template>, -o kyaml ("KYAML is a Kubernetes-specific dialect of YAML, and can be parsed as YAML"), -o name ("Print only the resource name and nothing else"), -o wide ("For pods, the node name is included"), -o yaml; --sort-by=<jsonpath_exp> sorts. JSONPath supports $, ., [*], [,] unions, filters [?()], and range ... end. kubectl logs and exec and port-forward go API server -> kubelet: the API server's connections to the kubelet are used for "Fetching logs for pods", "Attaching (usually through kubectl) to running pods" and "Providing the kubelet's port-forwarding functionality". Plugins: "A plugin is a standalone executable file, whose name begins with kubectl-"; kubectl plugin list searches PATH; plugins cannot override built-in commands. Krew "is the package manager for kubectl plugins".
# Scripts read fields, not tables
kubectl -n shop get pods -l app.kubernetes.io/name=orders-api -o name
kubectl -n shop get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.nodeName}{"\t"}{.status.phase}{"\n"}{end}'
kubectl get nodes -o custom-columns=NAME:.metadata.name,KUBELET:.status.nodeInfo.kubeletVersion,RUNTIME:.status.nodeInfo.containerRuntimeVersion
kubectl -n shop get deploy orders-api -o jsonpath='{.status.observedGeneration} {.metadata.generation}'
kubectl get pods -A --sort-by=.metadata.creationTimestamp
# One Pod, through the API server and the kubelet
kubectl -n shop logs deploy/orders-api --since=10m -f
kubectl -n shop logs shop-web-7d9f-abcde -c web --previous
kubectl -n shop exec -it deploy/shop-web -c app -- php artisan about
kubectl -n shop port-forward svc/shop-web 8081:80
# Plugins
kubectl krew install ctx ns neat
kubectl plugin listReal scenarios: a deploy script greps kubectl get pods output and breaks when a column is added (use -o jsonpath or -o json | jq); kubectl logs shows nothing because the container restarted (use --previous); kubectl exec into a distroless Go container fails with exec: "sh": executable file not found (use kubectl debug, taught in Kubernetes Observability & Troubleshooting); a team pins plugin versions via a krew index in its dev container.
| Format | Stable for scripts? | Notes |
|---|---|---|
default table / -o wide | No | Columns are for humans |
-o yaml / -o json / -o kyaml | Yes (fields), noisy | Includes status, managedFields (hide with --show-managed-fields=false, the default) |
-o name | Yes | deployment.apps/orders-api |
-o jsonpath=... | Yes | Escape dots in keys: kubernetes\.io/hostname |
-o custom-columns=... | Yes | Tables with chosen fields |
-o go-template=... | Yes | Go templates; braces must stay inside a shell quote |
Fix / how to use it: scripts use -o name, -o jsonpath or -o json | jq; logs/exec/port-forward are for one Pod at a time; install plugins through krew and list them in the team's onboarding. The command tables are in the kubectl cheatsheet.
Local clusters: kind, minikube, k3s, k3d, Docker Desktop Kubernetes, OrbStack Must-know
In plain words: A local cluster is the real Kubernetes API running in containers or a VM on your laptop. They differ in how nodes are made, which add-ons come built in, and how your locally built image gets into the cluster.
Common misunderstanding: "My laptop cluster pulls the image I just built." The cluster's nodes have their own image store. kind needs kind load docker-image, k3d needs k3d image import or its registry, minikube needs minikube image load; only Docker Desktop and OrbStack share the engine's images ("built images are immediately available for use in Pods", OrbStack) and even then :latest forces a pull ("by default, Kubernetes always attempts to pull and update images tagged with :latest").
Definition: kind "is a tool for running local Kubernetes clusters using Docker container 'nodes'" and "was primarily designed for testing Kubernetes itself, but may be used for local development or CI"; its config (kind.x-k8s.io/v1alpha4) declares nodes with roles and extraPortMappings, and node images must be pinned by digest. minikube "is local Kubernetes, focusing on making it easy to learn and develop for Kubernetes", needs "2 CPUs or more", "2GB of free memory", "20GB of free disk space" and a "Container or virtual machine manager"; it has many add-ons (minikube addons enable ingress), and "minikube is for learning and development". k3s is "Lightweight Kubernetes. Easy to install, half the memory, all in a binary of less than 100 MB"; servers run the control plane (SQLite for one server, embedded etcd for HA), agents run workloads, and it ships "coredns, traefik, local-storage, and metrics-server" plus servicelb as packaged add-ons (--disable=traefik). k3d "is a lightweight wrapper to run k3s ... in docker", configured with k3d.io/v1alpha5 Simple files, and can create a registry next to the cluster. Docker Desktop "includes a standalone Kubernetes server and client" with two provisioners: "Kubeadm creates a single-node cluster and the version is set by Docker Desktop" and "kind creates a multi-node cluster and you can set the version and number of nodes". OrbStack "includes a lightweight single-node Kubernetes cluster optimized for development", with Service and cluster.local access from the Mac.
# kind cluster for this chapter: one control plane, two workers, host port 8080
# mapped to the control-plane node for NodePort/Ingress experiments.
# Create with: kind create cluster --name shop --config kind-config.yaml
# kind's v0.33.0 release notes: "You *must* use the @sha256 digest to guarantee
# an image built for this release" -- so the node image is pinned by digest.
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: shop
nodes:
- role: control-plane
image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
extraPortMappings:
- containerPort: 30080 # a NodePort inside the node container
hostPort: 8080 # http://127.0.0.1:8080 on the laptop (listenAddress defaults to 0.0.0.0)
protocol: TCP
- role: worker
image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5
- role: worker
image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5# k3d cluster (k3s in Docker): one server, two agents, a local registry and
# the built-in k3d load balancer publishing port 8080 -> 80. k3s' ServiceLB
# (left enabled) hosts Traefik's LoadBalancer Service on ports 80/443.
# Create with: k3d cluster create --config k3d-config.yaml
apiVersion: k3d.io/v1alpha5
kind: Simple
metadata:
name: shop # kubeconfig context becomes k3d-shop
servers: 1
agents: 2
image: rancher/k3s:v1.37.2-k3s1 # a k3s release tag; k3s ships CoreDNS, Traefik, metrics-server
kubeAPI:
hostIP: "127.0.0.1"
hostPort: "6445"
ports:
- port: 8080:80 # host 8080 -> the k3d load balancer -> Traefik (k3s' packaged ingress controller)
nodeFilters:
- loadbalancer
registries:
create:
name: registry.localhost
host: "0.0.0.0"
hostPort: "5000"
# k3d prefixes it: docker push k3d-registry.localhost:5000/orders-api:1.4.2
# and Pods use image: k3d-registry.localhost:5000/orders-api:1.4.2#!/usr/bin/env bash
# Create, inspect and delete the chapter's local clusters. Expected, not run in
# this build environment (no Docker/Kubernetes may be started here).
# Usage: ./local-clusters.sh kind|k3d|minikube|delete
set -euo pipefail
cd "$(dirname "$0")"
# The exact names the manifests in ../k8s pull (imagePullPolicy: IfNotPresent).
IMAGES=(ghcr.io/acme/orders-api:1.4.2 ghcr.io/acme/shop-app:1.8.0 ghcr.io/acme/shop-web:1.8.0)
case "${1:-}" in
kind)
kind create cluster --config kind-config.yaml # context: kind-shop
kubectl cluster-info --context kind-shop
kind load docker-image "${IMAGES[@]}" --name shop # no registry needed
;;
k3d)
k3d cluster create --config k3d-config.yaml # context: k3d-shop
k3d image import "${IMAGES[@]}" --cluster shop
;;
minikube)
# minikube asks for 2 CPUs, 2GB of free memory and 20GB of disk.
minikube start --profile shop --driver=docker --kubernetes-version=v1.37.0 --nodes=2
minikube --profile shop addons enable metrics-server
for i in "${IMAGES[@]}"; do minikube --profile shop image load "$i"; done
;;
delete)
kind delete cluster --name shop || true
k3d cluster delete shop || true
minikube delete --profile shop || true
;;
*)
echo "usage: $0 kind|k3d|minikube|delete" >&2
exit 2
;;
esac
kubectl get nodes -o widekind create cluster --config kind-config.yaml (what happens)
1 docker run three kindest/node:v1.37.0@sha256:... containers (systemd + containerd + kubelet inside)
2 kubeadm init in the control-plane container: certificates, static Pods for apiserver/etcd/scheduler/kcm
3 kindnet (CNI) and CoreDNS installed; kubeadm join in the worker containers
4 kubeconfig context kind-shop written; API published on 127.0.0.1:<random port>
5 host 127.0.0.1:8080 -> control-plane container :30080 (extraPortMappings) -> NodePort ServiceReal scenarios: CI spins up kind per pull request to run integration tests against a real API server; a developer on an 8 GB laptop prefers k3d (one process per node, no VM); a team standardises on Docker Desktop's kind provisioner to match CI's kind version; minikube's --driver=vfkit gives a VM when a test needs real kernel modules.
| Option | Multi-node | Built-in add-ons | Image loading | Ingress/LB story |
|---|---|---|---|---|
| kind | Yes (containers) | CoreDNS, kindnet, local-path storage | kind load docker-image | extraPortMappings; cloud-provider-kind for LoadBalancer, Ingress and Gateway |
| k3d | Yes (containers) | CoreDNS, Traefik, metrics-server, local-path, servicelb | k3d image import, built-in registry | k3d load balancer + Traefik |
| minikube | Yes (--nodes) | Many add-ons (ingress, metrics-server, Headlamp, registry) | minikube image load | minikube tunnel, ingress add-on |
| k3s (on a VM) | Yes (agents) | As k3d | containerd ctr images import or a registry | Traefik, servicelb |
| Docker Desktop | kind mode only | Networking and storage controllers | Shared with the engine (containerd image store in kind mode) | localhost for LoadBalancer Services |
| OrbStack | No (use kind/k3d for that) | Flannel CNI; "No Ingress controller is installed by default" | Shared with the engine | *.k8s.orb.local for LoadBalancer Services |
Fix / how to use it: pin the node image (kind) or k3s tag (k3d) to the minor you run in production, keep the cluster config in the repository, never use :latest for local images, and delete and recreate clusters rather than repair them (kind delete cluster is idempotent by design: deleting a missing cluster "will not return an error").
kubeadm: bootstrapping a self-managed cluster Important
In plain words: kubeadm is the official tool that turns a set of Linux machines with a container runtime into a cluster: it creates certificates, writes the control plane as static Pods, and gives you a join command for the other machines.
Common misunderstanding: "kubeadm installs everything." It does not install the container runtime, the CNI plugin, an ingress controller, storage or a load balancer for the API; its own output says "You should now deploy a Pod network to the cluster".
Definition: kubeadm init "first runs a series of prechecks", "then downloads and installs the cluster control plane components", and prints "Your Kubernetes control-plane has initialized successfully!" with the instructions to copy /etc/kubernetes/admin.conf to $HOME/.kube/config. Control-plane components run as static Pods ("managed by the kubelet on specific nodes. This is a common approach used by tools like kubeadm"). For HA, --control-plane-endpoint names a DNS or load-balancer address shared by several control-plane nodes; etcd is stacked (on the control-plane nodes) or external. Upgrades: "Skipping MINOR versions when upgrading is unsupported"; the workflow is "Upgrade a primary control plane node", "Upgrade additional control plane nodes", "Upgrade worker nodes", with kubeadm upgrade plan, kubeadm upgrade apply v1.37.x, kubeadm upgrade node and kubectl drain. The architecture page lists kOps and Kubespray as other cluster-management tools; Cluster API does the same declaratively.
# On the first control-plane node (expected, not run)
sudo kubeadm init --control-plane-endpoint=cluster-endpoint:6443 --pod-network-cidr=10.244.0.0/16
mkdir -p $HOME/.kube && sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config && sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubectl apply -f <your CNI manifest> # e.g. Calico, Cilium, Flannel
# On each worker, the command kubeadm init printed:
sudo kubeadm join cluster-endpoint:6443 --token <token> --discovery-token-ca-cert-hash sha256:<hash>| Concern | kubeadm | Managed (EKS/GKE/AKS) |
|---|---|---|
| Certificates and rotation | You (kubeadm certs renew, yearly expiry) | Provider |
| etcd backups | You | Provider |
| API load balancer | You (HAProxy, kube-vip, cloud LB) | Provider |
| Minor upgrades | You, node by node | One API call or automatic, nodes by pool |
| CNI, storage, ingress | You | Defaults provided, replaceable |
Fix / how to use it: use kubeadm when you must own the control plane (on-prem, regulated, edge) or to learn; otherwise use a managed offering and spend the time on workloads.
Managed Kubernetes: EKS, GKE, AKS, what is managed, node pools Must-know
In plain words: In managed Kubernetes, the provider runs the control plane (API servers, etcd, controllers) and gives you an endpoint; you run nodes in groups ("node pools"), unless you also hand nodes to the provider (EKS Auto Mode, GKE Autopilot, AKS Automatic).
Common misunderstanding: "Managed means the provider upgrades and secures everything." The control plane managed for you still leaves workloads, add-ons, RBAC, network policy and (in standard modes) node upgrades with you, and a version past its support window is force-upgraded: on EKS, "If you haven't updated your cluster before the extended support period ends, your cluster is auto-upgraded to the oldest currently supported extended version."
Definition: EKS: "AWS manages the Kubernetes control plane when you create a cluster with EKS"; with "EKS Auto Mode ... EKS extends its control to manage Nodes (Kubernetes data plane) as well". "A minor version is under standard support in Amazon EKS for the first 14 months after it's released", then "extended support for the next 12 months" at "an additional cost per cluster hour". Managed node groups "automate the provisioning and lifecycle management of nodes"; "Node updates and terminations automatically drain nodes". GKE "is a managed implementation of the Kubernetes open source container orchestration platform"; in Autopilot "Google manages your infrastructure configuration"; release channels: Rapid ("1-2 weeks after upstream open source GA"), Regular ("(default)", recommended "for most users"), Stable, and Extended for long-term support. "A node pool is a group of nodes within a cluster that all have the same configuration", and each node carries the label cloud.google.com/gke-nodepool. AKS: "When you create an AKS cluster, Azure automatically creates and configures a control plane for you at no cost"; "Azure operates critical control plane components such as kube-apiserver, etcd, kube-scheduler, kube-controller-manager, and cloud-controller-manager"; AKS supports "three GA minor versions"; AKS Automatic adds managed nodes, scaling and upgrades.
Day 1 on EKS (expected, not run; Terraform or eksctl do the same declaratively)
1 VPC, subnets, IAM roles (Terraform) -> /platform/cloud-provider-primitives
2 aws eks create-cluster ... --kubernetes-version 1.37 -> control plane endpoint (provider-run)
3 aws eks create-nodegroup ... (or Auto Mode) -> EC2 nodes join with kubelet + containerd
4 aws eks update-kubeconfig --name shop-prod -> context with exec "aws eks get-token"
5 add-ons: VPC CNI, CoreDNS, kube-proxy (EKS add-ons), then ingress/gateway, metrics-server
6 kubectl apply -k k8s/ (or Argo CD) -> workloads| EKS | GKE | AKS | |
|---|---|---|---|
| Control plane | AWS-managed, per-cluster hourly price | Google-managed; free tier "without incurring costs for cluster management" | Azure-managed "at no cost" (Free tier), Standard/Premium optional |
| Nodes, standard mode | Managed node groups or self-managed | Node pools (Standard mode) | Node pools |
| Nodes, fully managed | EKS Auto Mode | Autopilot | AKS Automatic |
| Versions | 14 months standard + 12 months extended | Release channels Rapid/Regular/Stable/Extended | Three GA minors, LTS option |
| kubectl auth | aws eks get-token (IAM) | gke-gcloud-auth-plugin | Entra ID (kubelogin) or local accounts |
| Default CNI | Amazon VPC CNI (Pods get VPC IPs) | GKE Dataplane / VPC-native | Azure CNI variants |
Fix / how to use it: create managed clusters with Terraform (one module per environment), choose a release channel or an upgrade cadence on day 1, use the provider's fully-managed node mode unless you need custom nodes, and keep at least one non-production cluster one minor ahead. The cloud side (VPC, IAM, load balancers) is Cloud Provider Primitives.
Versions: Kubernetes release cadence, version skew policy, upgrades, deprecations and API removals Must-know
In plain words: A new minor Kubernetes comes out about every four months and each is patched for about a year, so a cluster that is not upgraded two or three times a year falls out of support. Components may differ by a few minors, and upgrades go one minor at a time, control plane first.
Common misunderstanding: "We can jump from 1.33 to 1.37 in one go." The policy requires "kube-apiserver to not skip minor versions when upgrading, even in single-instance clusters". You go 1.34, 1.35, 1.36, 1.37, checking removed APIs at each step.
Definition: "Kubernetes releases currently happen approximately three times per year"; "The Kubernetes project maintains release branches for the most recent three minor releases" and "Kubernetes 1.19 and newer receive approximately 1 year of patch support." Version skew policy: HA API servers "must be within one minor version"; "kubelet must not be newer than kube-apiserver" and "may be up to three minor versions older" (two for kubelet older than 1.25); kube-proxy has the same rule and must be within three minors of its kubelet; kube-controller-manager, kube-scheduler and cloud-controller-manager "must not be newer than the kube-apiserver instances they communicate with" and "may be up to one minor version older"; "kubectl is supported within one minor version (older or newer) of kube-apiserver". Upgrade order: API servers, then controller manager, scheduler and cloud controller manager ("in any order, or even simultaneously"), then kubelets ("or they can be left at 1.36, 1.35, or 1.34"). One inconsistency in the policy page itself: its upgrade pre-requisites ask for kubelets "at version 1.36 or 1.35" before a 1.37 API server ("within 2 minor versions of the new API server version"), stricter than the three-minor steady-state rule; the safe plan follows the stricter text, and the skew package offers both (strict flag). Deprecation policy: "Beta API versions are deprecated no more than 9 months or 3 minor releases after introduction (whichever is longer), and are no longer served 9 months or 3 minor releases after deprecation"; GA versions "must not be removed within a major version". The Deprecated API Migration Guide lists every removal (extensions/v1beta1 Deployment in 1.16; Ingress networking.k8s.io/v1beta1 in 1.22; CronJob batch/v1beta1, PodSecurityPolicy and autoscaling/v2beta1 in 1.25; flowcontrol.apiserver.k8s.io/v1beta3 in 1.32).
Upgrading a kubeadm cluster 1.36 -> 1.37 (the documented order)
1 read release notes; scan manifests and Helm charts for APIs removed in 1.37
2 latest 1.36 patch everywhere, then: kubeadm upgrade plan
3 first control-plane node: kubeadm upgrade apply v1.37.x (apiserver, kcm, scheduler, etcd)
4 other control-plane nodes: kubeadm upgrade node
5 each worker: kubectl drain <node> --ignore-daemonsets -> upgrade kubelet -> uncordon
6 kubectl and CI images to 1.37 (or 1.36/1.38: one minor either side)Real scenarios: a 1.25 upgrade breaks an old Helm chart still using policy/v1beta1 PodDisruptionBudget; a GKE cluster on the Rapid channel receives a minor the team had not tested; a node pool left on 1.33 blocks the control plane's move to 1.37 (kubelet would trail by four); CI's kubectl 1.30 talks to a 1.37 cluster and kubectl diff behaves oddly (outside the skew).
| Rule | Value | Source |
|---|---|---|
| Minor releases | About three per year | Release cycle |
| Patch support | About 1 year per minor (1.19+) | Version skew policy |
| Maintained branches | Latest three minors (1.37, 1.36, 1.35 on 2026-11-29) | Version skew policy |
| kubelet / kube-proxy lag | Up to 3 minors older, never newer | Version skew policy |
| Controllers lag | Up to 1 minor older, never newer | Version skew policy |
| kubectl | One minor either side | Version skew policy; install page |
| Beta API lifetime | Deprecated within 9 months or 3 minors; removed 9 months or 3 minors later | Deprecation policy |
| EKS support | 14 months standard + 12 months extended | EKS versions page |
Fix / how to use it: upgrade on a calendar (each minor within a few months of release), scan for removed APIs before every hop (kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis, client warnings, or tools such as Pluto), keep kubectl and CI images within one minor, and check a planned change against the policy in code (the skew package in Go). Recent deprecations to plan for: kube-dns ("no new packages will be built for kube-dns after v1.40"), kube-proxy ipvs mode ("By v1.40 ... disabled by default", "By v1.43 ... removed entirely"), and kubectl run --filename.
Previews: admission controllers, CNI, Services, Ingress and Gateway API, cluster add-ons, Helm Important
In plain words: A working cluster needs more than the core: something that checks and changes requests (admission), a network for Pods (CNI), stable addresses (Services), HTTP entry points (Ingress or Gateway API), DNS and metrics add-ons, and a way to package all of that (Helm). Each has its own chapter; here is just enough to recognise them.
Common misunderstanding: "A fresh kubeadm cluster is ready for apps." Without a CNI plugin, nodes stay NotReady and Pods stay Pending; without an ingress or gateway controller, Ingress objects do nothing; without metrics-server, kubectl top and the HPA fail.
Definition (admission controllers preview): "Admission controllers are code within the Kubernetes API server that check the data arriving in a request to modify a resource"; they "may be validating, mutating, or both"; "The admission control process proceeds in two phases" (mutating, then validating); "reads bypass the admission control layer". "In Kubernetes 1.37, the default ones are" twenty plugins including NamespaceLifecycle, LimitRanger, ServiceAccount, PodSecurity, ResourceQuota, DefaultStorageClass, MutatingAdmissionPolicy, ValidatingAdmissionPolicy and the two webhook plugins. Policy engines (Kyverno, Gatekeeper) and Pod Security Admission are Kubernetes Security.
Definition (CNI preview, Services preview, Ingress and Gateway API preview): network plugins "implement the container network interface (CNI) specification. They are responsible for allocating IP addresses to pods and enabling them to communicate with each other within the cluster" (Calico, Cilium, Flannel, kindnet, Amazon VPC CNI). A Service gives a set of Pods (chosen by a label selector) one virtual IP and DNS name; ClusterIP, NodePort and LoadBalancer types; kube-proxy or the CNI programs it. Ingress routes HTTP by host and path through an ingress controller (Ingress-NGINX, Traefik in k3s); the Gateway API (Gateway, HTTPRoute, ...) is its role-oriented successor, installed as CRDs. All three are taught in Kubernetes Networking.
Definition (cluster add-ons): "Addons use Kubernetes resources (DaemonSet, Deployment, etc) to implement cluster features" and live in kube-system. "all Kubernetes clusters should have cluster DNS": CoreDNS "is a DNS server/forwarder, written in Go, that chains plugins", and serves *.svc.cluster.local. metrics-server collects resource metrics "every 15 seconds" for the HPA, VPA and kubectl top, and "is meant only for autoscaling purposes" (Prometheus is for monitoring). The Kubernetes Dashboard "is now archived and no longer maintained"; its README says "Please consider using Headlamp instead".
Definition (Helm preview): Helm packages manifests as charts with values and tracks releases (helm install, helm upgrade, helm rollback); most add-ons above are installed with it. Charts, values and Kustomize overlays are Packaging for Kubernetes.
A new cluster, from empty to "apps can run"
1 control plane up (kubeadm/managed) -> nodes NotReady: no CNI
2 CNI (Cilium/Calico/VPC CNI) -> nodes Ready, Pods get IPs
3 CoreDNS (usually installed with step 1) -> Service names resolve
4 metrics-server -> kubectl top, HPA work
5 ingress or gateway controller -> Ingress/HTTPRoute objects take effect
6 cert-manager, external-dns, policy engine, GitOps (Argo CD) -> production platform| Add-on | Installed by default in | Purpose |
|---|---|---|
| CoreDNS | kubeadm, kind, k3s, minikube, EKS (add-on), GKE (kube-dns or Cloud DNS), AKS | Cluster DNS |
| CNI plugin | kind (kindnet), k3s (Flannel), EKS (VPC CNI), GKE, AKS, OrbStack (Flannel) | Pod network |
| metrics-server | k3s, minikube add-on, AKS, GKE | Resource metrics API |
| Ingress/Gateway controller | k3s (Traefik), minikube add-on, cloud-provider-kind | HTTP entry |
| Dashboard (archived) / Headlamp | minikube add-on (Headlamp) | Web UI |
Fix / how to use it: treat add-ons as part of the cluster definition (Terraform for managed add-ons, Helm or GitOps for the rest), pin their versions, and upgrade them with the cluster.
When not to use Kubernetes Good to know
In plain words: Kubernetes is a toolkit for building a platform. If you have one or two services and nobody whose job is running clusters, a managed container service or a PaaS is cheaper and safer.
Common misunderstanding: "Using EKS/GKE/AKS removes the operational cost." It removes the control plane; you still own three upgrades a year, add-ons, node images, security policy and a learning curve for every developer.
Definition: the cost is the control plane plus everything that makes it production-ready (CNI, ingress or gateway, cert-manager, DNS automation, metrics, logs, autoscaling, policy, secrets, backups) and the release treadmill described above. The full decision with alternatives (Amazon ECS, Cloud Run, Azure Container Apps, Fly.io, Laravel Cloud or Forge for a Laravel monolith) is in Containers & Kubernetes.
Signals that Kubernetes is premature
1 one or two deployable services, one team, no platform engineer
2 no need for custom controllers, GPUs, multi-cloud or on-prem portability
3 the "cluster" would be one node: Compose on a VM or a PaaS does the same with less
-> start with a managed container platform; move when service count or requirements pay for a platform team| Situation | Better fit |
|---|---|
| One Laravel monolith with a queue worker | Laravel Cloud, Forge, or Compose on a VM |
| A few stateless HTTP services on one cloud | Cloud Run, ECS Fargate, Azure Container Apps |
| Many services, many teams, shared tooling | Managed Kubernetes with GitOps |
| On-prem or edge fleet | k3s or kubeadm with a platform team |
Fix / how to use it: decide explicitly, write down the trigger that would move you to Kubernetes, and when you move, start with a managed cluster, GitOps and the smallest add-on set.
Mechanics
One write, end to end
kubectl apply --server-side -f k8s/go-service/deployment.yaml (context kind-shop)
1 kubectl: read kubeconfig, discovery (cached), PATCH /apis/apps/v1/namespaces/shop/deployments/orders-api
Content-Type: application/apply-patch+yaml, ?fieldManager=kubectl
2 apiserver: authentication (client cert -> user kubernetes-admin, group kubeadm:cluster-admins)
3 apiserver: authorization (RBAC: may this user patch deployments in shop?)
4 mutating admission: defaults (strategy, revisionHistoryLimit), mutating policies and webhooks
5 schema validation + field validation; validating admission (ResourceQuota, PodSecurity, policies)
6 etcd: write /registry/deployments/shop/orders-api, new resourceVersion -> 200 OK to kubectl
7 watchers: Deployment controller -> ReplicaSet; ReplicaSet controller -> 2 Pods (each Pod create
repeats steps 2-6, now as the controller's ServiceAccount; quota checks the Pods' requests)
8 scheduler: filter + score -> POST .../pods/<name>/binding
9 kubelet on the chosen node: CRI sandbox, CNI, pull, start; probes; status updates
10 EndpointSlice controller: ready Pod IPs behind Service orders-api; kube-proxy reprograms rulesWhat lives where in etcd and on disk
| Item | Location | Notes |
|---|---|---|
| Objects | etcd keys under /registry/<resource>/<namespace>/<name> | Encoded as protobuf; Secrets optionally encrypted at rest |
| kubeadm static Pod manifests | /etc/kubernetes/manifests/*.yaml on control-plane nodes | Edit = restart that component |
| Admin kubeconfig | /etc/kubernetes/admin.conf | Copy to $HOME/.kube/config |
| PKI | /etc/kubernetes/pki | CA, apiserver, etcd, front-proxy certificates |
| kubelet config | /var/lib/kubelet/config.yaml | KubeletConfiguration |
| Node leases | kube-node-lease namespace | One Lease per node |
| k3s data | /var/lib/rancher/k3s | Packaged add-on manifests in server/manifests |
| kubectl discovery cache | $HOME/.kube/cache | Delete it when kubectl shows stale resources |
Knobs
| Knob | Component | Default | Notes |
|---|---|---|---|
--node-monitor-period | kube-controller-manager | 5 s | How often node health is checked |
Eviction wait after Ready=Unknown | node controller | 5 min | Then Pods on an unreachable node are evicted |
--node-eviction-rate | kube-controller-manager | 0.1 per second | "won't evict pods from more than 1 node per 10 seconds" |
--register-node | kubelet | true | Self-registration of the Node object |
--container-runtime-endpoint | kubelet | runtime socket | CRI v1 required since 1.26 |
terminationGracePeriodSeconds | Pod spec | 30 s | SIGTERM, then SIGKILL |
| Watch history | etcd 3 | about 5 min | Older resourceVersion -> 410 Gone |
--enable-admission-plugins / --disable-admission-plugins | kube-apiserver | 20 defaults in 1.37 | kube-apiserver -h | grep enable-admission-plugins |
--runtime-config=<group>/<version>=false | kube-apiserver | all served | Simulate an API removal in a test cluster |
KUBECONFIG | kubectl | $HOME/.kube/config | Colon-separated list, first value wins |
--field-manager | kubectl apply --server-side | kubectl | Name your CI's manager |
-v=6 .. -v=9 | kubectl | 0 | Prints HTTP requests (6) up to bodies (9) |
Error messages you will actually see
| Message | Meaning | Fix |
|---|---|---|
The connection to the server localhost:8080 was refused - did you specify the right host or port? | No kubeconfig found; client-go's deprecated default server is http://localhost:8080 (message format from kubectl's helpers.go) | Set KUBECONFIG or create the context |
Unable to connect to the server: dial tcp ...: i/o timeout | Endpoint unreachable (VPN, private endpoint, stopped kind) | Network path, or kind get clusters |
error: You must be logged in to the server (Unauthorized) | Credential rejected (expired token or cert) | Refresh the exec plugin login, regenerate kubeconfig |
Error from server (Forbidden): pods is forbidden: User "..." cannot list resource "pods" | RBAC denies | A Role/RoleBinding (Kubernetes Security) |
error: resource mapping not found for name: ... no matches for kind "Ingress" in version "extensions/v1beta1" | The manifest uses a removed API | Migrate to networking.k8s.io/v1 |
Error from server (AlreadyExists) | create on an existing object | Use apply |
Apply failed with 1 conflict: conflict with "<manager>" using apps/v1: .spec.replicas | SSA field owned by another manager | Drop the field or --force-conflicts |
exceeded quota: shop-quota, requested: requests.cpu=... / must specify requests.cpu | ResourceQuota rejects the Pod | Set requests; raise the quota |
FailedScheduling ... 0/42 nodes available: insufficient cpu (Event; the resources docs' example) | Scheduler found no fitting node | Smaller requests, more nodes |
container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady | No CNI configured on the node | Install the CNI plugin |
ErrImagePull / ImagePullBackOff on kind | The node cannot find the image locally or in a registry | kind load docker-image, or a registry |
CreateContainerConfigError: secret "shop-app-secrets" not found | envFrom refers to a missing Secret | Create the Secret first |
410 Gone / too old resource version (client logs) | Watch position compacted | Relist (informers do it) |
429 Too Many Requests with Retry-After | API Priority and Fairness or watch-cache protection | Back off, fix the noisy client |
Go
The KB's Go service is the orders-api built in Images & Dockerfiles: a stdlib server that listens on $PORT, answers /healthz and /readyz, flips readiness off and drains within 8 s of SIGTERM. This chapter does not repeat it; it deploys that image and adds three small Go packages that make the chapter's mechanics checkable without a cluster: the watch contract, the skew policy, and an offline consistency check over the manifests.
Before
The usual first deploy of a Go service, generated by kubectl create deployment and edited by hand: no namespace, :latest, no probes, no requests (rejected by any namespace with a CPU quota), the generated app= label reused in an unrelated Service, and a NodePort chosen at random.
# Before: works once on a laptop, then surprises everyone
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api # namespace: default (implicit)
spec:
replicas: 1
selector:
matchLabels:
app: orders-api
template:
metadata:
labels:
app: orders-api
spec:
containers:
- name: orders-api
image: ghcr.io/acme/orders-api:latest # moves; Always pulled
# no ports, no probes, no resources, runs with the image's defaults
---
apiVersion: v1
kind: Service
metadata:
name: orders
spec:
type: NodePort
selector:
app: orders # matches nothing: zero endpoints, no error
ports:
- port: 8080After
The first deployment of a Go service: namespace and quota, a Deployment with recommended labels, named ports, readiness and liveness preview probes on the image's real endpoints, requests and limits, a non-root security context, and a NodePort Service that the kind config maps to 127.0.0.1:8080.
# The chapter's namespace plus a ResourceQuota (preview: quotas, requests and
# limits are taught in /platform/kubernetes-resources-scheduling-autoscaling).
# With requests.cpu / requests.memory in a quota, every container created in
# the namespace must declare requests, or the API server rejects the Pod.
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
app.kubernetes.io/part-of: shop
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: shop-quota
namespace: shop
spec:
hard:
pods: "40"
requests.cpu: "4"
requests.memory: 8Gi
limits.memory: 16Gi# First deployment of a Go service: the orders-api image built in
# /platform/docker-images-dockerfiles (distroless, UID 65532, listens on $PORT,
# /healthz and /readyz, drains within 8 s of SIGTERM). Workload details
# (rollouts, probes in depth) are /platform/kubernetes-workloads.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
namespace: shop
labels:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
annotations:
kubernetes.io/change-cause: "orders-api 1.4.2 first deploy"
spec:
replicas: 2
selector:
matchLabels:
app.kubernetes.io/name: orders-api # immutable after creation
template:
metadata:
labels:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
spec:
terminationGracePeriodSeconds: 30 # the default, stated: the app drains in 8 s
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
containers:
- name: orders-api
# In CI deploy the digest the build printed: ghcr.io/acme/orders-api@sha256:...
image: ghcr.io/acme/orders-api:1.4.2
imagePullPolicy: IfNotPresent # lets `kind load` / `k3d image import` images be used
ports:
- name: http
containerPort: 8080
env:
- name: PORT
value: "8080"
- name: POD_NAME # downward API; the pilot image does not read it yet (see the Go angle)
valueFrom:
fieldRef:
fieldPath: metadata.name
readinessProbe: # preview: gates Service traffic
httpGet:
path: /readyz
port: http
periodSeconds: 5
livenessProbe: # preview: restarts a wedged process; never checks dependencies
httpGet:
path: /healthz
port: http
periodSeconds: 10
failureThreshold: 3
resources: # required by the namespace quota
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]# Services preview (taught in /foundations/kubernetes-networking): a stable
# virtual IP and DNS name, orders-api.shop.svc.cluster.local, in front of the
# ready Pods whose labels match the selector. NodePort 30080 is what the kind
# config maps to 127.0.0.1:8080; in a cloud cluster use ClusterIP behind an
# Ingress or a Gateway instead.
apiVersion: v1
kind: Service
metadata:
name: orders-api
namespace: shop
labels:
app.kubernetes.io/name: orders-api
spec:
type: NodePort
selector:
app.kubernetes.io/name: orders-api
ports:
- name: http
port: 80
targetPort: http
nodePort: 30080# Lets `kubectl apply -k k8s/` (and `kubectl kustomize k8s/`) handle the whole
# first deploy in one command. Overlays per environment are taught in
# /platform/helm-kustomize-packaging.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- namespace.yaml
- go-service/deployment.yaml
- go-service/service.yaml
- laravel-app/configmap.yaml
- laravel-app/deployment.yaml
- laravel-app/service.yaml
- laravel-app/migrate-job.yamlThe list-then-watch contract as a toy: a Store with resourceVersion and compaction (410 Gone), a Reflector that lists, watches, relists and keeps a cache, and a de-duplicating Queue. The tests show that list-then-watch misses nothing, that a compacted position returns ErrGone, that the reflector relists and queues objects deleted while it was away, and that three updates to one object become one reconcile.
// Package apiwatch is a toy model of the Kubernetes list-then-watch contract
// (kubernetes.io "API concepts": "Efficient detection of changes") and of the
// client-go Reflector/Informer/work-queue trio built on top of it.
//
// It has no Kubernetes dependency: Store plays the API server backed by etcd
// (every write gets a new resourceVersion, history is compacted), Reflector
// plays client-go's Reflector + Indexer (a local cache kept in sync), and Queue
// plays the controller's work queue (keys, de-duplicated).
package apiwatch
import (
"errors"
"sort"
"sync"
)
// EventType mirrors the "type" field of a watch event.
type EventType string
const (
Added EventType = "ADDED"
Modified EventType = "MODIFIED"
Deleted EventType = "DELETED"
)
// Object is a stand-in for a Kubernetes object: a key and its resourceVersion.
type Object struct {
Name string
ResourceVersion uint64
Spec string
}
// Event is one entry of a watch stream.
type Event struct {
Type EventType
Object Object
}
// ErrGone is what the API server answers (HTTP 410 Gone) when a client asks to
// watch from a resourceVersion whose history has already been compacted.
var ErrGone = errors.New("410 Gone: requested resourceVersion is too old")
// Store is the "API server": the current objects plus a bounded change history.
type Store struct {
mu sync.Mutex
rv uint64
objects map[string]Object
history []Event // ordered by Object.ResourceVersion
compacted uint64 // history at or below this revision is gone
}
// NewStore returns an empty store at resourceVersion 0.
func NewStore() *Store { return &Store{objects: map[string]Object{}} }
// Put creates or updates an object and records the change.
func (s *Store) Put(name, spec string) Object {
s.mu.Lock()
defer s.mu.Unlock()
s.rv++
typ := Modified
if _, ok := s.objects[name]; !ok {
typ = Added
}
o := Object{Name: name, ResourceVersion: s.rv, Spec: spec}
s.objects[name] = o
s.history = append(s.history, Event{Type: typ, Object: o})
return o
}
// Delete removes an object; it reports whether the object existed.
func (s *Store) Delete(name string) bool {
s.mu.Lock()
defer s.mu.Unlock()
o, ok := s.objects[name]
if !ok {
return false
}
s.rv++
delete(s.objects, name)
o.ResourceVersion = s.rv
s.history = append(s.history, Event{Type: Deleted, Object: o})
return true
}
// List returns every object (sorted by name) and the collection's
// resourceVersion, which is where a following watch must start.
func (s *Store) List() ([]Object, uint64) {
s.mu.Lock()
defer s.mu.Unlock()
items := make([]Object, 0, len(s.objects))
for _, o := range s.objects {
items = append(items, o)
}
sort.Slice(items, func(i, j int) bool { return items[i].Name < items[j].Name })
return items, s.rv
}
// WatchFrom returns the changes after rv, or ErrGone if that part of the
// history was compacted. A real watch is a long-lived stream; polling keeps
// this model deterministic.
func (s *Store) WatchFrom(rv uint64) ([]Event, error) {
s.mu.Lock()
defer s.mu.Unlock()
if rv < s.compacted {
return nil, ErrGone
}
var out []Event
for _, e := range s.history {
if e.Object.ResourceVersion > rv {
out = append(out, e)
}
}
return out, nil
}
// Compact drops history up to and including rv (etcd compaction; Kubernetes
// documents a default window of about five minutes).
func (s *Store) Compact(rv uint64) {
s.mu.Lock()
defer s.mu.Unlock()
kept := s.history[:0]
for _, e := range s.history {
if e.Object.ResourceVersion > rv {
kept = append(kept, e)
}
}
s.history = kept
if rv > s.compacted {
s.compacted = rv
}
}
// Queue is a de-duplicating FIFO of keys, like client-go's work queue: three
// MODIFIED events for one object before the worker runs become one item.
type Queue struct {
keys []string
dirty map[string]bool
}
// Add enqueues key unless it is already waiting.
func (q *Queue) Add(key string) {
if q.dirty == nil {
q.dirty = map[string]bool{}
}
if q.dirty[key] {
return
}
q.dirty[key] = true
q.keys = append(q.keys, key)
}
// Get pops the oldest key; ok is false when the queue is empty.
func (q *Queue) Get() (key string, ok bool) {
if len(q.keys) == 0 {
return "", false
}
key, q.keys = q.keys[0], q.keys[1:]
delete(q.dirty, key)
return key, true
}
// Len is the number of waiting keys.
func (q *Queue) Len() int { return len(q.keys) }
// Reflector keeps Cache equal to the server's objects using list-then-watch,
// and relists when the server answers 410 Gone. Every change it applies
// enqueues the object's key (the informer's event handler).
type Reflector struct {
Store *Store
Queue *Queue
Cache map[string]Object
LastRV uint64
Relists int
listed bool
}
// Sync performs one step: the initial list, or one watch poll.
func (r *Reflector) Sync() error {
if !r.listed {
r.relist()
return nil
}
events, err := r.Store.WatchFrom(r.LastRV)
if errors.Is(err, ErrGone) {
// What client-go does: drop the stale position, list again, resume.
r.relist()
return nil
}
if err != nil {
return err
}
for _, e := range events {
switch e.Type {
case Deleted:
delete(r.Cache, e.Object.Name)
default:
r.Cache[e.Object.Name] = e.Object
}
r.LastRV = e.Object.ResourceVersion
r.Queue.Add(e.Object.Name)
}
return nil
}
func (r *Reflector) relist() {
items, rv := r.Store.List()
fresh := make(map[string]Object, len(items))
for _, o := range items {
fresh[o.Name] = o
r.Queue.Add(o.Name)
}
for name := range r.Cache {
if _, ok := fresh[name]; !ok {
r.Queue.Add(name) // deleted while we were not watching
}
}
if r.listed {
r.Relists++
}
r.Cache, r.LastRV, r.listed = fresh, rv, true
}package apiwatch
import (
"errors"
"reflect"
"testing"
)
func cacheOf(s *Store) map[string]Object {
items, _ := s.List()
m := map[string]Object{}
for _, o := range items {
m[o.Name] = o
}
return m
}
func TestListThenWatchMissesNothing(t *testing.T) {
s := NewStore()
s.Put("orders-api", "replicas=2")
r := &Reflector{Store: s, Queue: &Queue{}}
if err := r.Sync(); err != nil { // initial list
t.Fatal(err)
}
if r.LastRV != 1 {
t.Fatalf("LastRV after list = %d, want 1", r.LastRV)
}
s.Put("orders-api", "replicas=3")
s.Put("shop-web", "replicas=2")
s.Delete("shop-web")
if err := r.Sync(); err != nil { // one watch poll
t.Fatal(err)
}
if !reflect.DeepEqual(r.Cache, cacheOf(s)) {
t.Fatalf("cache %v != server %v", r.Cache, cacheOf(s))
}
if r.LastRV != 4 || r.Relists != 0 {
t.Fatalf("LastRV=%d Relists=%d, want 4 and 0", r.LastRV, r.Relists)
}
}
func TestWatchFromCompactedRevisionIsGone(t *testing.T) {
s := NewStore()
for i := 0; i < 5; i++ {
s.Put("orders-api", "v")
}
s.Compact(3)
if _, err := s.WatchFrom(2); !errors.Is(err, ErrGone) {
t.Fatalf("WatchFrom(2) err = %v, want ErrGone", err)
}
ev, err := s.WatchFrom(3)
if err != nil || len(ev) != 2 {
t.Fatalf("WatchFrom(3) = %d events, %v; want 2, nil", len(ev), err)
}
}
func TestReflectorRelistsAfterGone(t *testing.T) {
s := NewStore()
s.Put("a", "1")
s.Put("b", "1")
r := &Reflector{Store: s, Queue: &Queue{}}
_ = r.Sync() // list at rv=2
for r.Queue.Len() > 0 {
r.Queue.Get()
}
// The client is disconnected for a long time: b is deleted, c created,
// and the server compacts the history the client still needs.
s.Delete("b")
s.Put("c", "1")
s.Compact(4)
if err := r.Sync(); err != nil {
t.Fatal(err)
}
if r.Relists != 1 {
t.Fatalf("Relists = %d, want 1", r.Relists)
}
if !reflect.DeepEqual(r.Cache, cacheOf(s)) {
t.Fatalf("cache %v != server %v", r.Cache, cacheOf(s))
}
// b must be reconciled too (it vanished while unobserved), so it is queued.
var got []string
for {
k, ok := r.Queue.Get()
if !ok {
break
}
got = append(got, k)
}
want := []string{"a", "c", "b"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("queued %v, want %v", got, want)
}
}
func TestQueueDeduplicatesKeys(t *testing.T) {
s := NewStore()
r := &Reflector{Store: s, Queue: &Queue{}}
_ = r.Sync()
s.Put("orders-api", "replicas=2")
s.Put("orders-api", "replicas=3")
s.Put("orders-api", "replicas=4")
_ = r.Sync()
if r.Queue.Len() != 1 {
t.Fatalf("queue length = %d, want 1 (level-triggered: reconcile the latest state once)", r.Queue.Len())
}
if got := r.Cache["orders-api"].Spec; got != "replicas=4" {
t.Fatalf("cached spec = %q, want the latest", got)
}
}The version skew policy as code, with the policy page's own examples as tests (single API server, HA skew narrowing every range, the pre-1.25 two-minor rule, no skipped minors, and an upgrade blocked by a kubelet four minors behind):
// Package skew encodes the Kubernetes version skew policy
// (https://kubernetes.io/releases/version-skew-policy/) so that a cluster's
// component versions, or a planned upgrade, can be checked in a test or a CI job.
package skew
import (
"fmt"
"sort"
"strconv"
"strings"
)
// Version is a Kubernetes minor version (patch numbers do not matter for skew).
type Version struct{ Major, Minor int }
func (v Version) String() string { return fmt.Sprintf("%d.%d", v.Major, v.Minor) }
// Parse accepts "1.37", "v1.37.3" or "1.37.3+k3s1".
func Parse(s string) (Version, error) {
s = strings.TrimPrefix(strings.TrimSpace(s), "v")
parts := strings.SplitN(s, ".", 3)
if len(parts) < 2 {
return Version{}, fmt.Errorf("skew: %q is not major.minor", s)
}
maj, err1 := strconv.Atoi(parts[0])
min, err2 := strconv.Atoi(parts[1])
if err1 != nil || err2 != nil {
return Version{}, fmt.Errorf("skew: %q is not major.minor", s)
}
return Version{maj, min}, nil
}
// MustParse is Parse for literals in tests and examples.
func MustParse(s string) Version {
v, err := Parse(s)
if err != nil {
panic(err)
}
return v
}
// Node is one worker: its kubelet and the kube-proxy running next to it.
type Node struct {
Name string
Kubelet Version
KubeProxy *Version // nil when a CNI replaces kube-proxy
}
// Cluster lists the versions that matter for the policy. Controllers holds
// kube-controller-manager, kube-scheduler and cloud-controller-manager; the
// check assumes they reach the API servers through a load balancer (the
// policy's stricter case).
type Cluster struct {
APIServers []Version
Controllers map[string]Version
Nodes []Node
Kubectl *Version
}
// nodeLag is how many minors a kubelet or kube-proxy may trail the API server:
// three, or two for components older than 1.25.
func nodeLag(v Version) int {
if v.Major == 1 && v.Minor < 25 {
return 2
}
return 3
}
func minmax(vs []Version) (lo, hi int) {
lo, hi = vs[0].Minor, vs[0].Minor
for _, v := range vs[1:] {
lo, hi = min(lo, v.Minor), max(hi, v.Minor)
}
return lo, hi
}
// Check returns every violation of the skew policy, or nil. Only major
// version 1 exists, so comparisons use the minor number.
func Check(c Cluster) []string {
if len(c.APIServers) == 0 {
return []string{"no kube-apiserver"}
}
var out []string
lo, hi := minmax(c.APIServers)
if hi-lo > 1 {
out = append(out, fmt.Sprintf("kube-apiserver instances span 1.%d..1.%d; HA allows one minor", lo, hi))
}
names := make([]string, 0, len(c.Controllers))
for name := range c.Controllers {
names = append(names, name)
}
sort.Strings(names) // deterministic messages
for _, name := range names {
v := c.Controllers[name]
switch {
case v.Minor > lo:
out = append(out, fmt.Sprintf("%s %s is newer than kube-apiserver 1.%d", name, v, lo))
case v.Minor < hi-1:
out = append(out, fmt.Sprintf("%s %s is more than one minor older than kube-apiserver 1.%d", name, v, hi))
}
}
for _, n := range c.Nodes {
k := n.Kubelet
switch {
case k.Minor > lo:
out = append(out, fmt.Sprintf("node %s: kubelet %s is newer than kube-apiserver 1.%d", n.Name, k, lo))
case k.Minor < hi-nodeLag(k):
out = append(out, fmt.Sprintf("node %s: kubelet %s trails kube-apiserver 1.%d by more than %d", n.Name, k, hi, nodeLag(k)))
}
if p := n.KubeProxy; p != nil {
switch {
case p.Minor > lo:
out = append(out, fmt.Sprintf("node %s: kube-proxy %s is newer than kube-apiserver 1.%d", n.Name, p, lo))
case p.Minor < hi-nodeLag(*p):
out = append(out, fmt.Sprintf("node %s: kube-proxy %s trails kube-apiserver 1.%d by more than %d", n.Name, p, hi, nodeLag(*p)))
}
if d := p.Minor - k.Minor; d > nodeLag(*p) || -d > nodeLag(*p) {
out = append(out, fmt.Sprintf("node %s: kube-proxy %s and kubelet %s differ by more than %d", n.Name, p, k, nodeLag(*p)))
}
}
}
if kc := c.Kubectl; kc != nil {
for _, a := range c.APIServers {
if d := kc.Minor - a.Minor; d > 1 || d < -1 {
out = append(out, fmt.Sprintf("kubectl %s is more than one minor from kube-apiserver %s", kc, a))
break
}
}
}
return out
}
// UpgradePath lists every minor between from (exclusive) and to (inclusive):
// the policy forbids skipping minors on kube-apiserver, even with one instance.
func UpgradePath(from, to Version) ([]Version, error) {
if from.Major != to.Major || to.Minor < from.Minor {
return nil, fmt.Errorf("skew: cannot upgrade %s -> %s", from, to)
}
var path []Version
for m := from.Minor + 1; m <= to.Minor; m++ {
path = append(path, Version{from.Major, m})
}
return path, nil
}
// CanUpgradeAPIServers reports the violations the cluster would have right
// after every kube-apiserver moves to target, plus the no-skip rule. It applies
// the steady-state skew rules (kubelet up to three minors behind). Note: the
// policy's upgrade-order section lists stricter pre-requisites (kubelets "at
// version 1.36 or 1.35" before a 1.37 API server, "within 2 minor versions");
// pass Strict to enforce that reading.
func CanUpgradeAPIServers(c Cluster, target Version, strict bool) []string {
if len(c.APIServers) == 0 {
return []string{"no kube-apiserver"}
}
lo, _ := minmax(c.APIServers)
var out []string
if target.Minor > lo+1 {
out = append(out, fmt.Sprintf("target %s skips a minor from kube-apiserver 1.%d", target, lo))
}
if strict {
for _, n := range c.Nodes {
if n.Kubelet.Minor < target.Minor-2 {
out = append(out, fmt.Sprintf("node %s: kubelet %s is not within 2 minors of the new kube-apiserver %s (upgrade-order pre-requisite)", n.Name, n.Kubelet, target))
}
}
}
after := c
after.APIServers = make([]Version, len(c.APIServers))
for i := range after.APIServers {
after.APIServers[i] = target
}
after.Kubectl = nil // a workstation tool, upgraded separately
return append(out, Check(after)...)
}package skew
import (
"reflect"
"strings"
"testing"
)
func v(s string) *Version { x := MustParse(s); return &x }
func ctrl(s string) map[string]Version {
return map[string]Version{
"kube-controller-manager": MustParse(s),
"kube-scheduler": MustParse(s),
"cloud-controller-manager": MustParse(s),
}
}
func TestParse(t *testing.T) {
for in, want := range map[string]Version{"1.37": {1, 37}, "v1.37.3": {1, 37}, "1.37.2+k3s1": {1, 37}} {
got, err := Parse(in)
if err != nil || got != want {
t.Errorf("Parse(%q) = %v, %v; want %v", in, got, err, want)
}
}
if _, err := Parse("latest"); err == nil {
t.Error("Parse(latest) succeeded")
}
}
// The policy's own examples, kube-apiserver at 1.37.
func TestPolicyExamplesSingleAPIServer(t *testing.T) {
ok := Cluster{
APIServers: []Version{MustParse("1.37")},
Controllers: ctrl("1.36"),
Nodes: []Node{
{Name: "n1", Kubelet: MustParse("1.34"), KubeProxy: v("1.34")},
{Name: "n2", Kubelet: MustParse("1.37"), KubeProxy: v("1.37")},
},
Kubectl: v("1.38"),
}
if got := Check(ok); got != nil {
t.Fatalf("supported cluster reported %v", got)
}
bad := ok
bad.Nodes = []Node{{Name: "old", Kubelet: MustParse("1.33")}}
bad.Kubectl = v("1.35")
got := Check(bad)
if len(got) != 2 || !strings.Contains(got[0], "kubelet 1.33") || !strings.Contains(got[1], "kubectl 1.35") {
t.Fatalf("Check = %q", got)
}
}
// HA skew narrows everything: apiservers at 1.37 and 1.36.
func TestPolicyExamplesHASkewNarrows(t *testing.T) {
c := Cluster{
APIServers: []Version{MustParse("1.37"), MustParse("1.36")},
Controllers: ctrl("1.37"),
Nodes: []Node{{Name: "n1", Kubelet: MustParse("1.37")}},
Kubectl: v("1.38"),
}
got := Check(c)
want := []string{
"cloud-controller-manager 1.37 is newer than kube-apiserver 1.36",
"kube-controller-manager 1.37 is newer than kube-apiserver 1.36",
"kube-scheduler 1.37 is newer than kube-apiserver 1.36",
"node n1: kubelet 1.37 is newer than kube-apiserver 1.36",
"kubectl 1.38 is more than one minor from kube-apiserver 1.36",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("Check =\n%q\nwant\n%q", got, want)
}
c.Controllers, c.Nodes, c.Kubectl = ctrl("1.36"), []Node{{Name: "n1", Kubelet: MustParse("1.34")}}, v("1.37")
if got := Check(c); got != nil {
t.Fatalf("narrowed but valid cluster reported %v", got)
}
}
func TestOlderThan125AllowsTwoMinors(t *testing.T) {
c := Cluster{APIServers: []Version{MustParse("1.27")}, Nodes: []Node{{Name: "n", Kubelet: MustParse("1.24")}}}
if got := Check(c); len(got) != 1 {
t.Fatalf("kubelet 1.24 under 1.27: %v, want one violation", got)
}
}
func TestUpgradePathNeverSkips(t *testing.T) {
got, err := UpgradePath(MustParse("1.34"), MustParse("1.37"))
want := []Version{{1, 35}, {1, 36}, {1, 37}}
if err != nil || !reflect.DeepEqual(got, want) {
t.Fatalf("UpgradePath = %v, %v", got, err)
}
}
func TestCanUpgradeAPIServers(t *testing.T) {
c := Cluster{
APIServers: []Version{MustParse("1.36"), MustParse("1.36"), MustParse("1.36")},
Controllers: ctrl("1.36"),
Nodes: []Node{{Name: "n1", Kubelet: MustParse("1.35")}, {Name: "n2", Kubelet: MustParse("1.33")}},
}
got := CanUpgradeAPIServers(c, MustParse("1.37"), false)
if len(got) != 1 || !strings.Contains(got[0], "node n2: kubelet 1.33 trails kube-apiserver 1.37 by more than 3") {
t.Fatalf("CanUpgradeAPIServers(1.37) = %q", got)
}
got = CanUpgradeAPIServers(c, MustParse("1.38"), false)
if len(got) == 0 || !strings.Contains(got[0], "skips a minor") {
t.Fatalf("CanUpgradeAPIServers(1.38) = %q", got)
}
// The upgrade-order section's stricter text: kubelets at 1.36 or 1.35 for a 1.37 API server.
c.Nodes = []Node{{Name: "n1", Kubelet: MustParse("1.35")}, {Name: "n3", Kubelet: MustParse("1.34")}}
if got := CanUpgradeAPIServers(c, MustParse("1.37"), false); got != nil {
t.Fatalf("steady-state rules should allow kubelet 1.34: %q", got)
}
got = CanUpgradeAPIServers(c, MustParse("1.37"), true)
if len(got) != 1 || !strings.Contains(got[0], "node n3: kubelet 1.34 is not within 2 minors") {
t.Fatalf("strict = %q", got)
}
}The offline manifest check (YAML parsed with gopkg.in/yaml.v3): selectors match Pod template labels, Services select a Pod template and target declared port names, probes use declared ports, images carry a non-latest tag, every container has requests (the quota demands it), the Nginx ConfigMap reaches FPM over localhost, the kubeconfig's contexts point at defined clusters and users, and the cluster configs pin their node images.
// Package manifestcheck runs offline consistency checks over the chapter's
// YAML: the mistakes that `kubectl apply` would only reveal on a live cluster
// (a selector that matches no Pod, a probe on an undeclared port, a context
// pointing at a missing user). It is not schema validation; on a cluster,
// `kubectl apply --dry-run=server` is the real check.
package manifestcheck
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// Doc is one YAML document decoded into generic maps.
type Doc struct {
File string
Body map[string]any
}
// Load reads every *.yaml under dir (multi-document files included), skipping
// kustomization.yaml, which is not a Kubernetes object.
func Load(dir string) ([]Doc, error) {
var docs []Doc
err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".yaml") || d.Name() == "kustomization.yaml" {
return err
}
raw, err := os.ReadFile(path)
if err != nil {
return err
}
dec := yaml.NewDecoder(bytes.NewReader(raw))
for {
var m map[string]any
if err := dec.Decode(&m); errors.Is(err, io.EOF) {
break
} else if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
if m != nil {
docs = append(docs, Doc{File: path, Body: m})
}
}
return nil
})
return docs, err
}
// Get walks a dotted path through nested maps ("spec.template.metadata.labels").
func Get(m map[string]any, path string) any {
var cur any = m
for _, k := range strings.Split(path, ".") {
mm, ok := cur.(map[string]any)
if !ok {
return nil
}
cur = mm[k]
}
return cur
}
func str(m map[string]any, path string) string { s, _ := Get(m, path).(string); return s }
func strMap(v any) map[string]string {
out := map[string]string{}
if m, ok := v.(map[string]any); ok {
for k, x := range m {
out[k] = fmt.Sprint(x)
}
}
return out
}
func list(v any) []map[string]any {
var out []map[string]any
if xs, ok := v.([]any); ok {
for _, x := range xs {
if m, ok := x.(map[string]any); ok {
out = append(out, m)
}
}
}
return out
}
// subset reports whether every key/value of sel is in labels.
func subset(sel, labels map[string]string) bool {
if len(sel) == 0 {
return false // an empty selector selects everything: never what you meant here
}
for k, v := range sel {
if labels[k] != v {
return false
}
}
return true
}
// CheckObjects returns every problem found across the documents.
func CheckObjects(docs []Doc, namespace string) []string {
var out []string
add := func(d Doc, f string, a ...any) {
out = append(out, fmt.Sprintf("%s %s/%s: %s", filepath.Base(d.File), str(d.Body, "kind"), str(d.Body, "metadata.name"), fmt.Sprintf(f, a...)))
}
type podTemplate struct {
labels map[string]string
ports map[string]bool
}
var templates []podTemplate
for _, d := range docs {
for _, f := range []string{"apiVersion", "kind", "metadata.name"} {
if str(d.Body, f) == "" {
add(d, "missing %s", f)
}
}
kind := str(d.Body, "kind")
if kind != "Namespace" && str(d.Body, "metadata.namespace") != namespace {
add(d, "namespace %q, want %q", str(d.Body, "metadata.namespace"), namespace)
}
tpl := Get(d.Body, "spec.template")
if tpl == nil {
continue
}
t, _ := tpl.(map[string]any)
labels := strMap(Get(t, "metadata.labels"))
if kind == "Deployment" && !subset(strMap(Get(d.Body, "spec.selector.matchLabels")), labels) {
add(d, "spec.selector.matchLabels does not match the Pod template labels")
}
pt := podTemplate{labels: labels, ports: map[string]bool{}}
for _, c := range list(Get(t, "spec.containers")) {
name, image := str(c, "name"), str(c, "image")
if image == "" || strings.HasSuffix(image, ":latest") || !strings.Contains(image, ":") {
add(d, "container %s: image %q must carry an explicit, non-latest tag or digest", name, image)
}
if Get(c, "resources.requests") == nil {
add(d, "container %s: no resources.requests (the namespace quota rejects it)", name)
}
declared := map[string]bool{}
for _, p := range list(c["ports"]) {
if n := str(p, "name"); n != "" {
declared[n], pt.ports[n] = true, true
}
}
for _, probe := range []string{"readinessProbe", "livenessProbe", "startupProbe"} {
for _, h := range []string{"httpGet", "tcpSocket"} {
if port, ok := Get(c, probe+"."+h+".port").(string); ok && !declared[port] {
add(d, "container %s: %s uses port %q, not declared in ports", name, probe, port)
}
}
}
}
templates = append(templates, pt)
}
for _, d := range docs {
if str(d.Body, "kind") != "Service" {
continue
}
sel := strMap(Get(d.Body, "spec.selector"))
var match *podTemplate
for i := range templates {
if subset(sel, templates[i].labels) {
match = &templates[i]
break
}
}
if match == nil {
add(d, "selector %v matches no Pod template", sel)
continue
}
for _, p := range list(Get(d.Body, "spec.ports")) {
if tp, ok := p["targetPort"].(string); ok && !match.ports[tp] {
add(d, "targetPort %q is not a named port of the selected Pods", tp)
}
}
}
sort.Strings(out)
return out
}
// CheckKubeconfig verifies that current-context exists and that every context
// names a defined cluster and user.
func CheckKubeconfig(path string) ([]string, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var cfg map[string]any
if err := yaml.Unmarshal(raw, &cfg); err != nil {
return nil, err
}
names := func(key string) map[string]bool {
out := map[string]bool{}
for _, e := range list(cfg[key]) {
out[str(e, "name")] = true
}
return out
}
clusters, users, contexts := names("clusters"), names("users"), names("contexts")
var out []string
if cur := str(cfg, "current-context"); !contexts[cur] {
out = append(out, fmt.Sprintf("current-context %q is not a context", cur))
}
for _, c := range list(cfg["contexts"]) {
if !clusters[str(c, "context.cluster")] {
out = append(out, fmt.Sprintf("context %s: unknown cluster %q", str(c, "name"), str(c, "context.cluster")))
}
if !users[str(c, "context.user")] {
out = append(out, fmt.Sprintf("context %s: unknown user %q", str(c, "name"), str(c, "context.user")))
}
}
return out, nil
}package manifestcheck
import (
"os"
"strings"
"testing"
)
const root = "../.." // docs/snippets/platform/kubernetes-architecture-setup
func TestChapterManifestsAreConsistent(t *testing.T) {
docs, err := Load(root + "/k8s")
if err != nil {
t.Fatal(err)
}
if len(docs) != 9 {
t.Fatalf("loaded %d objects, want 9 (Namespace, ResourceQuota, 2 Deployments, 2 Services, 2 ConfigMaps, Job)", len(docs))
}
if problems := CheckObjects(docs, "shop"); problems != nil {
t.Fatalf("problems:\n%s", strings.Join(problems, "\n"))
}
}
func TestCheckerCatchesTheClassicMistakes(t *testing.T) {
docs, err := Load(root + "/k8s")
if err != nil {
t.Fatal(err)
}
for _, d := range docs {
if str(d.Body, "kind") == "Service" && str(d.Body, "metadata.name") == "orders-api" {
d.Body["spec"].(map[string]any)["selector"] = map[string]any{"app": "orders"} // typo'd selector
}
if str(d.Body, "kind") == "Deployment" && str(d.Body, "metadata.name") == "shop-web" {
c := Get(d.Body, "spec.template.spec.containers").([]any)[1].(map[string]any)
c["image"] = "ghcr.io/acme/shop-web:latest"
}
}
got := strings.Join(CheckObjects(docs, "shop"), "\n")
for _, want := range []string{"matches no Pod template", `image "ghcr.io/acme/shop-web:latest"`} {
if !strings.Contains(got, want) {
t.Errorf("checker output lacks %q:\n%s", want, got)
}
}
}
func TestNginxTalksToFPMOverLocalhost(t *testing.T) {
raw, err := os.ReadFile(root + "/k8s/laravel-app/configmap.yaml")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), "fastcgi_pass 127.0.0.1:9000;") {
t.Fatal("containers in one Pod share localhost; fastcgi_pass must be 127.0.0.1:9000")
}
}
func TestKubeconfigExample(t *testing.T) {
problems, err := CheckKubeconfig(root + "/kubeconfig/config.example.yaml")
if err != nil || problems != nil {
t.Fatalf("kubeconfig: %v %v", problems, err)
}
}
func TestClusterConfigsPinVersions(t *testing.T) {
kind, err := os.ReadFile(root + "/clusters/kind-config.yaml")
if err != nil {
t.Fatal(err)
}
if n := strings.Count(string(kind), "image: kindest/node:v1.37.0@sha256:"); n != 3 {
t.Fatalf("kind nodes pinned by digest: %d of 3", n)
}
k3d, err := os.ReadFile(root + "/clusters/k3d-config.yaml")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(k3d), "apiVersion: k3d.io/v1alpha5") || !strings.Contains(string(k3d), "image: rancher/k3s:v1.37.2-k3s1") {
t.Fatal("k3d config must use v1alpha5 and a pinned k3s image")
}
}module academy/kubernetes-architecture-setup
go 1.24
require gopkg.in/yaml.v3 v3.0.1The Go angle
- Kubernetes is written in Go, and so is its client. kubectl, the control plane, CoreDNS, etcd, containerd, Helm, kind and k3s are Go programs;
k8s.io/client-gois the same library the controllers use. Theapiwatchmodel mirrors client-go'stools/cachenames (Reflector, Indexer, work queue) so the real code is recognisable when you open it. - Level-triggered reconcile in Go. A handler should enqueue a key (
namespace/name), never the object; the worker reads the latest object from the cache.TestQueueDeduplicatesKeysis the reason: three events, one reconcile. - Graceful shutdown inside the grace period. The orders-api drains in 8 s;
terminationGracePeriodSecondsdefaults to 30 s, and readiness goes false first so EndpointSlices drop the Pod before the drain (OS Processes, Signals & Graceful Shutdown). - Configuration from the Pod. The Deployment sets
PORT(read by the orders-api) andPOD_NAMEthrough the downward API. The pilot image does not readPOD_NAMEyet; addingos.Getenv("POD_NAME")to its logger fields is how logs from 20 replicas stay attributable. - Talking to the API from Go. Inside a Pod,
rest.InClusterConfig()(client-gorest/config.go) reads the ServiceAccount token and CA from/var/run/secrets/kubernetes.io/serviceaccount/that Kubernetes mounts ("Kubernetes will automatically inject the public root certificate and a valid bearer token into the pod"); outside,clientcmdloads the same kubeconfig as kubectl. Writing controllers with controller-runtime is Extending Kubernetes. - Testing manifests is ordinary Go testing. The
manifestcheckpackage runs ingo testwith no cluster; on a cluster,kubectl apply --dry-run=serveradds the schema and admission checks it cannot do (quota on Pods only for objects that are Pods, see Q12). - Dependency pinning.
gopkg.in/yaml.v3 v3.0.1keeps the module ongo 1.24; client-go would pull a much larger dependency tree, which is why the toy models avoid it.
Laravel
Before
The first attempt most Laravel teams make: one container, the PHP built-in server, configuration baked into the image, migrations on every Pod start.
# Before: php artisan serve in a Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop
spec:
replicas: 3
selector:
matchLabels: { app: shop }
template:
metadata:
labels: { app: shop }
spec:
containers:
- name: shop
image: ghcr.io/acme/shop:latest
# development server, single-threaded; migrations race across 3 replicas
command: ["sh", "-c", "php artisan migrate --force && php artisan serve --host=0.0.0.0 --port=8000"]
env:
- name: APP_KEY
value: base64:hard-coded-in-git # a secret in a manifestAfter
The first deployment of a Laravel app as a php-fpm + nginx pod, using the two images (app = php-fpm, web = Nginx with public/) built in Images & Dockerfiles. Settings come from a ConfigMap and a Secret; Nginx gets its server block from a ConfigMap with fastcgi_pass 127.0.0.1:9000, because containers in one Pod share the network namespace; migrations run once per release in a Job.
# Non-secret settings for the Laravel app, plus the Nginx server block for the
# web container. Secrets (APP_KEY, DB_PASSWORD) live in the Secret
# shop-app-secrets, created out of band (/platform/kubernetes-config-secrets-storage).
apiVersion: v1
kind: ConfigMap
metadata:
name: shop-app-config
namespace: shop
labels:
app.kubernetes.io/name: shop
data:
APP_ENV: production
APP_DEBUG: "false"
LOG_CHANNEL: stderr # the container runtime collects stdout/stderr
DB_CONNECTION: pgsql
DB_HOST: postgres.shop.svc.cluster.local # a Service name; the database is not part of this chapter
DB_PORT: "5432"
SESSION_DRIVER: database
CACHE_STORE: database
---
apiVersion: v1
kind: ConfigMap
metadata:
name: shop-nginx
namespace: shop
labels:
app.kubernetes.io/name: shop
data:
# Same server block as the image's (from the Laravel deployment docs), except
# fastcgi_pass: containers in one Pod share the network namespace, so php-fpm
# is 127.0.0.1:9000 here, where Compose used the service name app:9000.
default.conf: |
server {
listen 80;
server_name _;
root /var/www/html/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ ^/index\.php(/|$) {
fastcgi_pass 127.0.0.1:9000;
# PHP files are in the app container at the same path; Nginx only
# needs the public/ assets, which are baked into the web image.
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}
location ~ /\.(?!well-known).* {
deny all;
}
}# First deployment of a Laravel app: a php-fpm + nginx pod. Two containers,
# one Pod: they share localhost (fastcgi_pass 127.0.0.1:9000) but not a
# filesystem; the web image already contains public/ (see the Dockerfile's
# `web` target in /platform/docker-images-dockerfiles), so no shared volume.
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-web
namespace: shop
labels:
app.kubernetes.io/name: shop-web
app.kubernetes.io/part-of: shop
spec:
replicas: 2
selector:
matchLabels:
app.kubernetes.io/name: shop-web
template:
metadata:
labels:
app.kubernetes.io/name: shop-web
app.kubernetes.io/part-of: shop
spec:
containers:
- name: app # php-fpm; the image's entrypoint runs `php artisan optimize`, then php-fpm
image: ghcr.io/acme/shop-app:1.8.0
imagePullPolicy: IfNotPresent
ports:
- name: fpm
containerPort: 9000
envFrom:
- configMapRef:
name: shop-app-config
- secretRef:
name: shop-app-secrets # missing Secret -> CreateContainerConfigError
readinessProbe: # preview: FPM accepts connections
tcpSocket:
port: fpm
periodSeconds: 5
livenessProbe:
tcpSocket:
port: fpm
periodSeconds: 10
failureThreshold: 3
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 512Mi
- name: web # nginx serving public/ and passing PHP to the app container
image: ghcr.io/acme/shop-web:1.8.0
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
readinessProbe: # /up through Nginx and FPM: proves the path and that Laravel boots (DB only with a DiagnosingHealth listener)
httpGet:
path: /up
port: http
periodSeconds: 5
resources:
requests:
cpu: 50m
memory: 32Mi
limits:
memory: 64Mi
volumeMounts:
- name: nginx-conf
mountPath: /etc/nginx/conf.d/default.conf
subPath: default.conf
readOnly: true
volumes:
- name: nginx-conf
configMap:
name: shop-nginx# ClusterIP Service in front of the Nginx containers; reach it locally with
# kubectl -n shop port-forward svc/shop-web 8081:80
apiVersion: v1
kind: Service
metadata:
name: shop-web
namespace: shop
labels:
app.kubernetes.io/name: shop-web
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: shop-web
ports:
- name: http
port: 80
targetPort: http# Database migrations run once per release, not in every web Pod. Jobs are
# taught in /platform/kubernetes-workloads; Helm hooks or an Argo CD sync wave
# usually run this before the Deployment changes.
apiVersion: batch/v1
kind: Job
metadata:
name: shop-migrate-1-8-0
namespace: shop
labels:
app.kubernetes.io/name: shop-migrate
app.kubernetes.io/part-of: shop
spec:
backoffLimit: 2
ttlSecondsAfterFinished: 3600
template:
metadata:
labels:
app.kubernetes.io/name: shop-migrate
spec:
restartPolicy: Never
containers:
- name: migrate
image: ghcr.io/acme/shop-app:1.8.0
imagePullPolicy: IfNotPresent
# args replace the image's CMD; its ENTRYPOINT still runs first
args: ["php", "artisan", "migrate", "--force"]
envFrom:
- configMapRef:
name: shop-app-config
- secretRef:
name: shop-app-secrets
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 256MiThe Laravel angle
- The health route is made for this. Laravel 13's deployment docs: the health route "may be used to report the status of your application to an uptime monitor, load balancer, or orchestration system such as Kubernetes"; "By default, the health check route is served at
/upand will return a 200 HTTP response if the application has booted without exceptions". The web container's readiness probe hits/upthrough Nginx and FPM, so it proves the request path and that the app boots, nothing more:/updoes not touch the database. Laravel's hook for that: it dispatches "aIlluminate\Foundation\Events\DiagnosingHealthevent", and "Within a listener for this event, you may check your application's database or cache status"; throwing from the listener makes/upanswer 500. The listener below checks the connection and that migrations ran; it belongs on readiness only (a database outage then removes every Pod from the Service, which is the intended signal, while liveness stays on the TCP check). Keep liveness on the cheap TCP check: a database blip should make a Pod unready, not restart it. - Trust the proxy in front of the Pod. Behind an Ingress or Gateway the client IP and scheme arrive in
X-Forwarded-*headers; Laravel's docs, for cloud load balancers whose addresses you do not know: "you may use * to trust all proxies".
<?php
// bootstrap/app.php (excerpt): health route for the probes, proxies trusted for Ingress/Gateway
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// The Pod is only reachable through the cluster's ingress or gateway.
$middleware->trustProxies(at: '*');
})
->create();<?php
// app/Listeners/CheckDatabaseOnHealth.php
// Laravel's /up only proves the app booted. Laravel dispatches DiagnosingHealth
// on every /up request; throwing from a listener turns the answer into a 500,
// so the readiness probe also proves PostgreSQL is reachable and migrated.
// Listeners in app/Listeners are discovered automatically.
namespace App\Listeners;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
class CheckDatabaseOnHealth
{
public function handle(DiagnosingHealth $event): void
{
DB::connection()->getPdo(); // throws if the database is unreachable
if (! Schema::hasTable('migrations')) {
throw new RuntimeException('database reachable but not migrated');
}
}
}- Configuration is environment, at start-up.
envFromturns the ConfigMap and Secret into environment variables; the image's entrypoint runsphp artisan optimize(config, events, routes and views cached) when the container starts, so the cached config contains the Pod's environment, not the build machine's. - Logs to stderr.
LOG_CHANNEL=stderruses Laravel'sstderrchannel ('stream' => 'php://stderr'), sokubectl logs -c appand the node's log collector see every line; nothing is written to the container filesystem. - One process type per Deployment. Queue workers and the scheduler reuse the
appimage with differentargs(php artisan queue:work,php artisan schedule:work) in their own Deployments, so they scale and restart independently (Kubernetes Workloads). - Sessions and cache off the Pod. With several replicas,
SESSION_DRIVERandCACHE_STOREmust be shared (database or Redis); the file driver would give each Pod its own sessions. - Octane or FrankenPHP replace the two-container Pod with one container (see the FrankenPHP image in Images & Dockerfiles); the manifests then look like the Go service's.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Commands hit the wrong cluster | Explicit contexts, prompt, separate files | kubectl config current-context, kubeconfig per cluster, kubectx | No "deleted prod by accident" | Discipline; tooling in the shell |
| Local image not found in kind | Load or use a registry | kind load docker-image, k3d registry, imagePullPolicy: IfNotPresent | Fast inner loop | One more step per build |
| Upgrade breaks manifests | Scan for removed APIs before each hop | Migration guide, deprecated-API metrics, Pluto, --runtime-config tests | No surprises at upgrade time | Work every four months |
| Cluster falls out of support | Upgrade calendar | One minor at a time, control plane, then node pools | Patches keep coming | Testing per minor |
| Two tools fight over a field | Server-side apply + single owner | --server-side, drop replicas when an HPA owns it | Conflicts are visible | Learning field ownership |
| "Applied" but nothing runs | Observe status, not exit codes | kubectl rollout status, observedGeneration, events | Real feedback in CI | Waits in pipelines |
| Service has no endpoints | Selector discipline | Recommended labels, offline check, get endpointslices | Silent failure becomes a test failure | Labels must be stable |
| Watches overload the API server | Informers, not polling | client-go shared informers, back off on 429 | Scales to many objects | Caches use memory |
| Production cluster needed quickly | Managed Kubernetes | EKS/GKE/AKS via Terraform, managed node mode | No etcd or certificates to run | Per-cluster cost, provider limits |
| Secrets in manifests | Secrets out of band | secretRef to a Secret created by an operator or CI | Nothing secret in Git | Needs a secrets pipeline (Config, Secrets & Storage) |
Commands hit the wrong cluster
Keep one kubeconfig per cluster and combine them only on purpose; show the current context in the prompt; give production contexts short-lived exec credentials and a read-only default user; and for destructive commands pass --context explicitly in scripts so the shell's current context does not matter.
The image is "not found" on a local cluster
kind and minikube nodes have their own containerd image store. Build with the exact name the manifest pulls, then kind load docker-image ghcr.io/acme/orders-api:1.4.2 --name shop (or minikube image load, k3d image import), and use a non-latest tag with imagePullPolicy: IfNotPresent; local-clusters.sh loads all three of the chapter's images. For repeated work, k3d's registry (k3d-registry.localhost:5000) or a local registry:2 connected to the kind network is simpler.
An upgrade removes an API you still use
Before every minor: read the migration guide for that release, query the API server's deprecated-API metric and client warnings (kubectl prints Warning: ... is deprecated on every use), render Helm charts and Kustomize overlays and grep for the removed apiVersions, and run a test cluster with --runtime-config=<group>/<version>=false. Stored objects are converted automatically; only the files and charts need changing.
"kubectl apply succeeded" but the app is broken
apply returns at step 6 of One write, end to end. In CI follow it with kubectl rollout status deploy/orders-api -n shop --timeout=120s and, on failure, kubectl describe and kubectl get events --sort-by=.lastTimestamp. GitOps tools surface the same information as health status.
Choosing
Which local cluster
| Need | Choose | Why |
|---|---|---|
| CI integration tests, upstream-like behaviour | kind | kubeadm-built, pinned node images, multi-node, fast to delete |
| Laptop with little memory, Traefik and registry built in | k3d | k3s is light; registry and load balancer in the config |
| Learning with add-ons, VM realism, GPU or driver tests | minikube | Many drivers and add-ons |
| Zero setup next to Docker | Docker Desktop (kind mode) or OrbStack | Shares images, one click |
| A small always-on server, edge, homelab | k3s | Single binary, SQLite or embedded etcd |
| Learning how a real control plane is assembled | kubeadm on VMs | Same steps as on-prem |
Which managed offering, which node mode
| Situation | Choice | Note |
|---|---|---|
| Already on AWS, IAM-heavy | EKS (Auto Mode unless custom nodes are needed) | Plan for 14+12 month support windows |
| Want the provider to pick versions | GKE with a release channel (Regular), Autopilot | Rapid only for pre-production |
| Already on Azure, Entra ID | AKS (Automatic for new teams) | LTS option for slower upgrades |
| Custom kernels, GPUs, special AMIs | Standard mode with your own node groups/pools | You own node upgrades |
| On-prem or air-gapped | kubeadm, k3s, or a vendor distribution | You own the control plane |
Which apply mode
| Who changes the cluster | Mode | Note |
|---|---|---|
| One person learning | kubectl apply -f | Fine |
| CI pipeline | kubectl apply --server-side --field-manager=ci after diff and --dry-run=server | Visible conflicts |
| GitOps (Argo CD, Flux) | The tool applies (SSA supported) | Humans stop using apply against that cluster |
| Charts with many objects | Helm (helm upgrade --install) | Releases and rollbacks (Packaging) |
In architecture: from a single process to a distributed system
Kubernetes is itself a distributed system (a replicated store plus loops), and it hosts yours. The questions grow from "how do I run one app on it" to "how many clusters, who owns them, and how do they stay in step".
Monolith: one app, one cluster (or none)
A Laravel monolith on Kubernetes is the php-fpm + nginx Deployment above, a worker Deployment, a scheduler Deployment and a migration Job, all from one image, in one namespace, on one managed cluster. The honest question first is When not to use Kubernetes: for one monolith, a PaaS or Compose on a VM is often cheaper. If you choose Kubernetes, choose a managed control plane, two or three nodes across zones and the smallest add-on set.
Modular monolith: namespaces and ownership
Several modules or teams share a cluster: one namespace per team or module, a ResourceQuota per namespace, recommended labels so ownership is queryable, RBAC per namespace, and a GitOps repository with one directory per namespace. Everything still lives in one control plane, so a misbehaving controller or a huge list call affects everyone; API Priority and Fairness and quotas are the guard rails.
Microservices: many services, a platform team
Dozens of services from GitHub Actions or GitLab CI pipelines, images signed and pushed, manifests rendered by Helm or Kustomize, Argo CD syncing them. The cluster becomes a product: the platform team owns cluster versions, add-ons (ingress or gateway, cert-manager, external-dns, metrics, policy), golden-path templates and the upgrade calendar; service teams own their namespaces.
A service change, platform view
1 PR merged -> CI builds, tests, scans, signs image D
2 CI bumps the digest in the GitOps repo (Helm values or Kustomize images)
3 Argo CD sees the commit -> server-side apply to the cluster
4 admission verifies the signature and policies; quota checks requests
5 controllers roll out; Argo CD reports Healthy once status says soDistributed data: etcd, many clusters, regions
Inside one cluster, etcd is the distributed database you depend on: an odd number of members, quorum, fast disks, regular snapshots (managed providers hide this). Across clusters there is no shared control plane: each cluster has its own etcd and API, so "multi-region" means several clusters plus something that keeps them in step (GitOps with one source of truth, Cluster API or Terraform for the clusters themselves, global DNS or a multi-cluster gateway for traffic). Stretching one etcd across regions raises commit latency (etcd: "The cost is higher consensus request latency from crossing data center boundaries"), which is why the usual answer is one cluster per region.
Scaling path: 1x, 10x, 100x
| Scale | Clusters | Control plane | Delivery | People |
|---|---|---|---|---|
| 1x | One managed cluster (plus kind/k3d locally) | Provider, default settings | kubectl apply -k from CI | Developers |
| 10x | prod + staging per region, same minor | Provider; upgrade calendar; add-ons in Terraform/Helm | GitOps (Argo CD/Flux), server-side apply | A small platform team |
| 100x | Fleets per region and environment | Cluster API or Terraform modules; version skew managed per fleet | GitOps with ApplicationSets, policy as code | Platform engineering with an internal developer platform |
Lab
Label: every command that needs a cluster (kind, k3d, minikube, kubeadm, cloud CLIs, any kubectl verb that talks to a server) is expected, not run: no Kubernetes or Docker may be started in this build environment (AUTHORING cost rule). Their output is shown as the shape the docs describe, with placeholders, never invented values. Steps marked ran on the host were executed on macOS (Go 1.27.4 darwin/arm64; Docker Desktop's bundled kubectl v1.36.1 used client-only, with HOME and KUBECONFIG pointed at a scratch copy, so no cluster was contacted). Real output is saved in pipeline/sources/kubernetes-architecture-setup/lab-host-output.txt.
1. Go packages: watch model, skew policy, manifest check (ran on the host)
cd docs/snippets/platform/kubernetes-architecture-setup/go
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ok academy/kubernetes-architecture-setup/apiwatch 1.303s
# ok academy/kubernetes-architecture-setup/manifestcheck 1.315s
# ok academy/kubernetes-architecture-setup/skew 1.303s2. kubeconfig contexts, offline (ran on the host, client only)
cp ../kubeconfig/config.example.yaml /tmp/kc.yaml # a copy: use-context rewrites the file
kubectl config get-contexts --kubeconfig /tmp/kc.yaml
# CURRENT NAME CLUSTER AUTHINFO NAMESPACE
# * kind-shop kind-shop kind-shop-admin shop
# prod eks-shop-prod eks-shop-prod-sso shop
# staging gke-shop-staging gke-shop-staging-user shop
kubectl config use-context prod --kubeconfig /tmp/kc.yaml
# Switched to context "prod".
kubectl config view --minify --kubeconfig /tmp/kc.yaml # only the current context's cluster and user
# ... current-context: prod ... exec: apiVersion: client.authentication.k8s.io/v1, command: aws ...3. Render without a server (ran on the host, client only)
kubectl kustomize ../k8s | grep -E '^kind:' | sort | uniq -c
# 2 kind: ConfigMap
# 2 kind: Deployment
# 1 kind: Job
# 1 kind: Namespace
# 1 kind: ResourceQuota
# 2 kind: Service
kubectl create deployment hello --image=ghcr.io/acme/orders-api:1.4.2 --dry-run=client -o yaml
# apiVersion: apps/v1 ... labels: app: hello ... containers: - image: ghcr.io/acme/orders-api:1.4.2
# name: orders-api ... resources: {} ... status: {}Note what --dry-run=client produced: a container named after the image, resources: {}, status: {} and no probes, which is exactly the "Before" shape. It is a starting point, not a manifest.
4. Create a local cluster and look around (expected, not run)
cd ../clusters && ./local-clusters.sh kind
kubectl cluster-info --context kind-shop
# Kubernetes control plane is running at https://127.0.0.1:<port>
# CoreDNS is running at https://127.0.0.1:<port>/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
kubectl get nodes -o wide
# NAME STATUS ROLES VERSION CONTAINER-RUNTIME (columns trimmed)
# shop-control-plane Ready control-plane v1.37.0 containerd://<version>
# shop-worker Ready <none> v1.37.0 containerd://<version>
# shop-worker2 Ready <none> v1.37.0 containerd://<version>
kubectl -n kube-system get pods -o wide # etcd, kube-apiserver, kube-controller-manager,
# kube-scheduler (static Pods), kube-proxy, kindnet, coredns
kubectl get ns # default, kube-node-lease, kube-public, kube-system, local-path-storage
kubectl api-resources --api-group=apps
kubectl explain deployment.spec.strategy.rollingUpdate.maxSurge
kubectl get --raw /apis/apps/v1 | jq '.resources[].name'Docker Desktop's own docs show the same check on its kubeadm cluster as docker-desktop Ready control-plane 3h v1.29.1, their documented sample from an older release.
5. First deploy, validated server-side first (expected, not run)
cd .. && kind load docker-image ghcr.io/acme/orders-api:1.4.2 ghcr.io/acme/shop-app:1.8.0 ghcr.io/acme/shop-web:1.8.0 --name shop
kubectl create namespace shop --dry-run=client -o yaml | kubectl apply -f -
kubectl -n shop create secret generic shop-app-secrets --from-literal=APP_KEY=base64:... --from-literal=DB_PASSWORD=...
kubectl apply --server-side --dry-run=server -k k8s/ # schema, RBAC, admission for these objects; nothing stored
# The Deployments' and Job's Pods are not created by a dry run, so Pod requests are not checked
# against the ResourceQuota here; test that with a Pod: kubectl create --dry-run=server -f pod.yaml
kubectl diff -k k8s/ # exit 1 = differences (all new objects here)
kubectl apply --server-side --field-manager=lab -k k8s/
kubectl -n shop rollout status deploy/orders-api --timeout=120s
# deployment "orders-api" successfully rolled out
curl -s http://127.0.0.1:8080/readyz # host -> kind :30080 NodePort -> a ready Pod
kubectl -n shop port-forward svc/shop-web 8081:80 & curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8081/up
# 200 once the app boots. Plain /up does not check the database; with the CheckDatabaseOnHealth
# listener it is 500 until a PostgreSQL Service named postgres exists in shop and the
# migrate Job has succeeded (this chapter ships no database, so the Job fails here)If the Secret step is skipped, only the containers that reference it wait in CreateContainerConfigError with secret "shop-app-secrets" not found: the app (FPM) container of each shop-web Pod and the Job's migrate container. The web (Nginx) container starts, but its /up readiness probe fails (no FPM behind 127.0.0.1:9000, so Nginx answers 502), the Pod shows 1/2 ready containers and never joins the Service: a missing dependency is a status, not a crash.
6. Watch it reconcile (expected, not run)
kubectl -n shop get pods -l app.kubernetes.io/name=orders-api -w &
kubectl -n shop delete pod -l app.kubernetes.io/name=orders-api --wait=false
# Terminating ... then new Pods Pending -> ContainerCreating -> Running (ReplicaSet restores 2)
kubectl -n shop scale deploy/orders-api --replicas=4 # imperative change
kubectl -n shop get deploy orders-api -o jsonpath='{.metadata.managedFields[*].manager}'
# two managers now: lab (the apply) and the one kubectl scale used, which took .spec.replicas
kubectl apply --server-side --field-manager=lab -k k8s/
# expected shape: Apply failed with 1 conflict: conflict with "<the scale manager>" ...: .spec.replicas
kubectl apply --server-side --field-manager=lab --force-conflicts -k k8s/ # take it back: replicas 27. Versions and upgrade readiness (expected, not run)
kubectl version # client and server; must be within one minor
kubectl get nodes -o custom-columns=NAME:.metadata.name,KUBELET:.status.nodeInfo.kubeletVersion
kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis
kubectl -n kube-system get configmap kube-proxy -o jsonpath='{.data.config\.conf}' | grep 'mode:'
# the 1.37 release blog's own command: empty or iptables/nftables is fine; ipvs is deprecated
kind delete cluster --name shop # idempotentCommon misconceptions
| Belief | Reality |
|---|---|
kubectl apply deploys and waits | It stores desired state and returns; controllers act afterwards. Wait with rollout status |
| Control plane down = app down | Running Pods keep serving; change stops (scheduling, scaling, healing) |
| Kubernetes needs Docker on the nodes | Nodes run a CRI runtime (containerd, CRI-O); dockershim was removed in 1.24; Docker-built images work everywhere |
| The scheduler starts containers | It only binds a Pod to a node; the kubelet starts containers through the CRI |
| Components talk to each other directly | Hub and spoke: everything goes through kube-apiserver; only it touches etcd |
| More etcd members = more safety | Only odd sizes help: 4 members tolerate 1 failure, like 3 |
| Namespaces isolate workloads | They scope names, RBAC and quotas; network isolation needs NetworkPolicy; nodes are shared |
create and apply are the same | create fails if the object exists; apply patches declaratively (and SSA tracks field owners) |
| A watch replays all missed events | Only within the retained history (about 5 minutes on etcd 3); then 410 Gone and a relist |
v1beta1 and v1 objects are different data | Same stored object, converted per request; only old manifests break when a version is removed |
| Managed Kubernetes upgrades everything for you | The control plane yes; node pools, add-ons and your manifests' API versions are still yours, and unsupported versions get force-upgraded |
| You can skip minor versions in an upgrade | kube-apiserver must not skip minors, even with one instance |
port-forward svc/x tests the Service | It picks one Pod and bypasses kube-proxy and readiness |
| The Kubernetes Dashboard is the standard UI | It is archived; the project points to Headlamp |
| A local cluster sees images I just built | Only Docker Desktop and OrbStack share the engine's images; kind, k3d and minikube need a load/import step or a registry |
Cheat sheet
| Topic | Remember |
|---|---|
| Control plane | kube-apiserver (the only door), etcd (Raft, odd members), scheduler (binds), controller managers (loops), CCM (cloud only) |
| Node | kubelet (my Pods, heartbeats via Lease), kube-proxy (Service rules, optional), containerd/CRI-O via CRI v1 |
| Object | apiVersion, kind, metadata (name, namespace, labels, annotations), spec (you), status (the system) |
| Reconcile | Watch, compare, act once, repeat; level-triggered; one owner per field |
| Watch | list -> resourceVersion -> watch; 410 Gone -> relist; informer cache + work queue of keys |
| REST | /api/v1/... core, /apis/GROUP/VERSION/namespaces/NS/RESOURCE/NAME, sub-resources /status, /scale, /log |
| Labels | Query by labels, never by version; recommended app.kubernetes.io/*; annotations for notes |
| kubeconfig | clusters + users + contexts; KUBECONFIG merge, first wins; exec plugins for clouds; treat as a secret |
| Apply | diff and --dry-run=server in CI, apply --server-side to change, never edit under GitOps |
| Output | -o name, -o jsonpath, -o custom-columns, -o yaml; scripts never parse tables |
| Local | kind (CI), k3d (light, registry), minikube (add-ons, VMs), Docker Desktop/OrbStack (shared images), load images explicitly |
| Managed | EKS/GKE/AKS run the control plane; you pick node mode (groups/pools vs Auto Mode/Autopilot/Automatic) |
| Versions | ~3 minors a year, ~1 year support, 3 branches; kubelet up to 3 behind, controllers 1, kubectl ±1; no skipping |
| Removals | Beta APIs: deprecated within 9 months/3 minors, removed 9 months/3 minors later; scan before each hop |
| Add-ons | CNI before anything; CoreDNS; metrics-server for HPA and kubectl top; Headlamp, not Dashboard |
| Laravel pod | php-fpm + nginx in one Pod: fastcgi_pass 127.0.0.1:9000; /up readiness; migrations in a Job; logs to stderr |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Walk through what happens between kubectl apply -f deployment.yaml returning and the Pods serving traffic. Which components are involved, and which of them talk to etcd? Must-know
Answer
Answer: kubectl sends a PATCH to kube-apiserver, which authenticates, authorises (RBAC), runs mutating admission, validates, runs validating admission and writes the object to etcd; then the command returns. Afterwards the Deployment controller (watching the API) creates a ReplicaSet, the ReplicaSet controller creates Pods, the scheduler binds each Pod to a node, the kubelet on that node calls the runtime through the CRI (sandbox, CNI, pull, start), runs probes and writes status, and the EndpointSlice controller adds ready Pod IPs behind the Service so kube-proxy can route to them. Only kube-apiserver talks to etcd; every other component is an API client. That is why apply succeeding says nothing about the rollout: check kubectl rollout status.
2 — The control plane of your cluster is unreachable for 20 minutes. What keeps working, what stops, and why? Must-know
Answer
Answer: Running Pods keep running and serving, because kubelets and the container runtime keep the existing containers alive and kube-proxy's rules stay in place. What stops is anything that needs the API: new deployments, scaling (HPA), rescheduling after a node failure, new endpoints for new Pods, kubectl logs/exec. Kubelets cannot report status, and when the API returns, the node controller may see stale heartbeats and needs time to settle. This is the reason to run three API servers and an odd-sized etcd behind a load balancer, or to buy a managed control plane.
3 — Why does etcd run with 3 or 5 members and not 4? What happens when 2 of 3 members fail? Must-know
Answer
Answer: etcd uses Raft: a write commits when a majority, (n/2)+1, has persisted it. 3 members have quorum 2 and tolerate 1 failure; 4 members have quorum 3 and still tolerate only 1, so the fourth member adds cost and latency without fault tolerance (etcd's FAQ says exactly that); 5 tolerate 2. With 2 of 3 down there is no quorum: etcd cannot commit writes, so kube-apiserver cannot change anything and cannot serve consistent data; running Pods are unaffected. etcd resumes automatically once a majority is back.
4 — A colleague says "Kubernetes removed Docker support in 1.24, so our Docker images no longer work". Correct them. Must-know
Answer
Answer: 1.24 removed the dockershim, the kubelet's built-in adapter for Docker Engine as a node runtime. Nodes now use a CRI runtime such as containerd or CRI-O (Docker Engine is still possible through the external cri-dockerd). Images are OCI images: "the images produced from docker build will work with all CRI implementations". What breaks is node-level tooling that assumed docker on the node (use crictl) and builds that used the node's Docker socket inside Pods.
5 — What is the difference between kubectl create -f, kubectl apply -f and kubectl apply --server-side -f? When would you see a conflict? Must-know
Answer
Answer: create is imperative: POST, and it fails with AlreadyExists if the object exists; apply creates or updates, but on an object made by plain create it has no last-applied record (the reference says to create with apply or create --save-config). Client-side apply computes a three-way merge on the client using the last-applied-configuration annotation, so it can remove fields you deleted from the file, but it silently overwrites fields others changed. Server-side apply sends the partial object ("fully specified intent") to the server, which records an owner (field manager) per field; if you set a field to a different value than its current owner, the server returns a conflict, which you resolve by dropping the field, changing your value, or --force-conflicts. Typical conflict: your manifest sets spec.replicas while an HPA or a kubectl scale owns it.
6 — Your controller logs 410 Gone after a network blip and stops seeing changes. Explain the mechanism and the fix. Important
Answer
Answer: A watch resumes from a resourceVersion, but the server keeps only a limited history ("Clusters using etcd 3 preserve changes in the last 5 minutes by default"). If the client's last version is older than the retained history, the server answers 410 Gone. The client must clear its position, list again (getting a fresh resourceVersion and the full current state), compare with its cache to find objects deleted meanwhile, and watch from the new version. client-go's Reflector does this automatically; hand-written watch loops must too. The apiwatch model's TestReflectorRelistsAfterGone shows the sequence.
7 — A Service has zero endpoints although the Deployment's Pods are Running and Ready. What do you check first, and why does Kubernetes not report an error? Must-know
Answer
Answer: The Service's spec.selector against the Pods' labels (kubectl get pods --show-labels, kubectl get endpointslices -l kubernetes.io/service-name=<name>); then the Service's targetPort against the container's port name or number. A selector is a query, and a query that matches nothing is valid, so there is no error, just an empty EndpointSlice. Recommended stable labels and an offline check (the chapter's manifestcheck fails on "selector matches no Pod template") turn this into a test failure.
8 — Your cluster runs kube-apiserver 1.36 on three instances, controllers 1.36 and node pools at 1.35 and 1.33. Can you upgrade the control plane to 1.37 today? To 1.38? Important
Answer
Answer: Not to 1.37 yet: after the upgrade, kubelets at 1.33 would trail the API server by four minors, beyond the policy's three. Upgrade that node pool first, to 1.35: the steady-state rule would accept 1.34, but the policy's upgrade pre-requisites ask for kubelets within two minors of the new API server (1.35 or 1.36), and 1.35 satisfies both readings (the existing 1.35 pool is fine). 1.38 is never allowed directly: kube-apiserver must not skip minors, so the path is 1.36 → 1.37 → 1.38, API servers first, then controller manager, scheduler and cloud controller manager, then kubelets. kubectl in CI must also be within one minor of every API server. The skew package's CanUpgradeAPIServers encodes exactly this check.
9 — What does EKS (or GKE, AKS) manage for you, and what do you still own on day 2? Important
Answer
Answer: The provider runs the control plane: API servers, etcd (with backups and quorum), scheduler, controller manager and cloud controller manager, plus its endpoint and certificates; AKS lists exactly those components as Azure-operated. You still own the nodes in standard mode (node groups/pools, their images and upgrades), add-ons (CNI configuration, CoreDNS, ingress or gateway, metrics, cert-manager), workloads and their API versions, RBAC and policies, and the upgrade schedule within the provider's support window (EKS: 14 months standard plus 12 months extended, then automatic upgrade). EKS Auto Mode, GKE Autopilot and AKS Automatic also take over nodes.
10 — You built ghcr.io/acme/orders-api:1.4.2 locally and applied the Deployment to a kind cluster. The Pods are in ImagePullBackOff. Why, and what are two fixes? Important
Answer
Answer: kind's nodes are containers with their own containerd image store; the image exists only in your Docker engine, so the kubelet tries to pull from the registry named in the image reference and fails. Fixes: kind load docker-image ghcr.io/acme/orders-api:1.4.2 --name shop (with imagePullPolicy: IfNotPresent and a non-latest tag), or push to a registry the nodes can reach (a local registry:2 connected to the kind network, or k3d's built-in registry). Docker Desktop and OrbStack share the engine's images, but :latest still triggers a pull.
11 — Why does the Laravel Pod's Nginx config say fastcgi_pass 127.0.0.1:9000 when the Compose version said app:9000, and where do the PHP files and the public assets live? Important
Answer
Answer: Containers in one Pod share a network namespace, so php-fpm listening on port 9000 in the app container is reachable from the web container on localhost; in Compose they were separate containers on a network, reached by service name. They do not share a filesystem: the PHP code lives in the app image at /var/www/html (Nginx only passes SCRIPT_FILENAME), and public/ assets are baked into the web image, so no shared volume is needed. The readiness probe on /up goes through Nginx and FPM, so it proves that path and that Laravel boots; it checks the database only if a DiagnosingHealth listener does.
12 — When is kubectl apply --dry-run=server better than --dry-run=client, and what can it still not catch? Good to know
Answer
Answer: --dry-run=client only renders the object locally (useful to generate YAML). --dry-run=server sends the real request through authentication, RBAC, mutating and validating admission (policies, and webhooks that declare no side effects) and schema validation without persisting, so it catches removed API versions, unknown fields and policy denials for the objects you send. It cannot see what controllers would create later: a Deployment or Job dry run creates no Pods, so a CPU/memory ResourceQuota is not evaluated against their Pods (the quota docs: creating a Deployment that tries to use more resources than are available "succeeds, but the Deployment may not be able to get all of the Pods it manages to exist"). Test quota with a Pod manifest (kubectl create --dry-run=server -f pod.yaml), and readiness, image pulls, runtime Secrets and capacity only after a real apply, followed by rollout status.
13 — Name three situations in which you would not put a service on Kubernetes. Good to know
Answer
Answer: A single Laravel monolith with one team and no platform engineer (a PaaS such as Laravel Cloud or Forge, or Compose on a VM, is cheaper); a few stateless HTTP services on one cloud that fit Cloud Run, ECS Fargate or Azure Container Apps; and any case where the cluster would be one node with no need for custom controllers, GPUs or portability. The cost to weigh is the control plane, the add-ons and three minor upgrades a year; Containers & Kubernetes has the comparison.
Glossary
| Term | Meaning |
|---|---|
| Kubernetes (K8s) | Open-source platform for managing containerised workloads through a declarative API and control loops |
| Cluster | A control plane plus a set of worker nodes |
| Control plane | The components that store desired state and make global decisions: kube-apiserver, etcd, kube-scheduler, kube-controller-manager, cloud-controller-manager |
| kube-apiserver | The REST front end of the control plane; the only component that reads and writes etcd |
| etcd | Consistent, highly available key-value store holding all cluster data |
| Raft | The consensus algorithm etcd uses; commits need a majority (quorum) |
| Quorum | (n/2)+1 members of an etcd cluster |
| kube-scheduler | Binds Pods that have no node to a suitable node |
| kube-controller-manager | One binary running the built-in controllers (Deployment, ReplicaSet, Node, Job, EndpointSlice...) |
| cloud-controller-manager | Controllers that call the cloud API: nodes, routes, load balancers; absent on-prem and locally |
| Node | A worker machine (VM, bare metal, or a container in kind/k3d) |
| kubelet | Node agent that runs the Pods assigned to its node and reports status |
| kube-proxy | Node component programming Service rules (iptables/nftables); optional with some CNIs |
| Container runtime | Software that runs containers on a node (containerd, CRI-O) |
| CRI | Container Runtime Interface: the gRPC API between kubelet and runtime; v1 required since 1.26 |
| containerd | CNCF runtime with a built-in CRI plugin; the default in most clusters |
| CRI-O | A Kubernetes-only CRI runtime (OpenShift's default) |
| dockershim | The kubelet's former built-in Docker adapter, removed in 1.24 |
| Pod | The smallest deployable unit: one or more containers sharing network and IPC namespaces |
| Object | A persistent record in the API ("record of intent") |
| apiVersion | Group and version of an object's schema (apps/v1, v1) |
| kind | The object's type (Deployment, Service) |
| metadata | Name, namespace, UID, labels, annotations, owner references, resourceVersion, managedFields |
| spec | The desired state, written by you |
| status | The observed state, written by controllers and kubelets |
| Desired state | What the stored objects say should exist |
| Reconciliation | Moving the current state towards the desired state |
| Controller loop | A non-terminating loop that watches objects and acts to close the gap |
| Level-triggered | Acting on current state rather than on the sequence of events |
| Watch | A long-lived request streaming ADDED/MODIFIED/DELETED events after a resourceVersion |
| resourceVersion | Opaque version of an object or collection, used to resume watches and for optimistic concurrency |
| 410 Gone | Answer to a watch from a compacted resourceVersion; the client must relist |
| Informers | client-go machinery (Reflector, Indexer, handlers) keeping a local cache via list-then-watch |
| Work queue | De-duplicating, rate-limited queue of object keys feeding a controller's workers |
| API server REST | The HTTP API: /api/v1 for core, /apis/GROUP/VERSION for groups, verbs get/list/watch/create/update/patch/delete |
| API groups | Families of resources (apps, batch, networking.k8s.io), each with versions |
| Labels | Identifying key/value pairs used for selection |
| Selectors | Equality- or set-based queries over labels (no OR) |
| Annotations | Non-identifying metadata for tools and humans |
| Namespaces | Scopes for names, RBAC and quotas; four exist initially |
| ResourceQuota | Per-namespace limits on object counts and resource requests/limits (resource quotas preview) |
| kubectl | The Kubernetes CLI: an API client driven by kubeconfig |
| kubeconfig | File listing clusters, users and contexts; default $HOME/.kube/config |
| Contexts | Named triples of cluster, user and namespace |
| Clusters (kubeconfig) | Server URL and CA for an API server |
| Users (kubeconfig) | Credentials: client certificate, token, or exec plugin |
| Exec credential plugin | A program kubectl runs to obtain a short-lived token (aws eks get-token, gke-gcloud-auth-plugin) |
| kubectl get / describe | Read objects / read objects plus related events, for humans |
| apply | Declarative update: make the live object match the file |
| create vs apply | Imperative creation (fails if present) vs declarative patching |
| Server-side apply | Apply computed by the API server with per-field ownership (managedFields) and conflicts |
| Field manager | The name recorded as owner of fields in server-side apply |
| kubectl diff | Shows what an apply would change, via a server-side dry run |
| Dry-run | --dry-run=client (render locally) or --dry-run=server (full validation, not persisted) |
| kubectl explain | Field documentation from the server's OpenAPI schema |
| Output formats | -o wide/yaml/json/kyaml/name/jsonpath/custom-columns/go-template |
| jsonpath | Template language for selecting fields in kubectl output |
| kubectl logs exec port-forward | Per-Pod debugging through the API server to the kubelet |
| krew plugins | kubectl plugins (kubectl-* executables) installed with the krew package manager |
| kind | Kubernetes in Docker: nodes as containers, built with kubeadm |
| minikube | Local Kubernetes in a VM or container with many add-ons |
| k3s | Lightweight Kubernetes distribution in one binary |
| k3d | Runs k3s clusters in Docker containers |
| Docker Desktop Kubernetes | Docker Desktop's built-in cluster (kubeadm or kind provisioner) |
| OrbStack | macOS container app with a single-node development cluster |
| kubeadm | Official tool to bootstrap and upgrade self-managed clusters; control plane as static Pods |
| Static Pod | A Pod the kubelet runs from a local manifest file, not created through the API |
| Managed Kubernetes | A provider runs the control plane (control plane managed); you run workloads and usually nodes |
| EKS | Amazon Elastic Kubernetes Service; Auto Mode also manages nodes |
| GKE | Google Kubernetes Engine; Standard or Autopilot; release channels |
| AKS | Azure Kubernetes Service; Standard or Automatic; free control plane tier |
| Node pools | Groups of identically configured nodes (managed node groups on EKS) |
| Kubernetes release cadence | About three minor releases per year, each patched for about a year |
| Version skew policy | Allowed version differences between components and the required upgrade order |
| Upgrades | One minor at a time: API servers, then controllers, then kubelets |
| Deprecations and API removals | Beta API versions are removed on a schedule; manifests must move to newer versions |
| Admission controllers | API server plugins that mutate or validate writes after authorisation (admission controllers preview) |
| CNI | Container Network Interface; plugins give Pods IPs and connectivity (CNI preview) |
| Service | Stable virtual IP and DNS name in front of Pods chosen by labels (Services preview) |
| Ingress and Gateway API | HTTP routing objects served by a controller; Gateway API is the role-oriented successor (Ingress and Gateway API preview) |
| Cluster add-ons | Cluster features run as Pods in kube-system: DNS, CNI, metrics, UI |
| CoreDNS | The default cluster DNS server since 1.13 |
| metrics-server | Resource metrics for HPA, VPA and kubectl top; not a monitoring system |
| Dashboard | The archived Kubernetes web UI; Headlamp is the suggested replacement |
| Readiness and liveness | Probes that gate traffic and restart wedged containers (readiness and liveness preview) |
| Helm | Package manager for Kubernetes charts and releases (Helm preview) |
| php-fpm + nginx pod | A Laravel Pod with an FPM container and an Nginx container sharing localhost |
References
- Kubernetes concepts: overview https://kubernetes.io/docs/concepts/overview/ — components https://kubernetes.io/docs/concepts/overview/components/ — cluster architecture https://kubernetes.io/docs/concepts/architecture/ — nodes https://kubernetes.io/docs/concepts/architecture/nodes/ — control plane to node communication https://kubernetes.io/docs/concepts/architecture/control-plane-node-communication/ — controllers https://kubernetes.io/docs/concepts/architecture/controller/ — cloud controller manager https://kubernetes.io/docs/concepts/architecture/cloud-controller/ — CRI https://kubernetes.io/docs/concepts/architecture/cri/ — garbage collection https://kubernetes.io/docs/concepts/architecture/garbage-collection/
- Kubernetes objects: objects https://kubernetes.io/docs/concepts/overview/working-with-objects/ — object management https://kubernetes.io/docs/concepts/overview/working-with-objects/object-management/ — names https://kubernetes.io/docs/concepts/overview/working-with-objects/names/ — labels https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ — namespaces https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/ — annotations https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ — field selectors https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/ — owners and dependents https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/ — recommended labels https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/ — the Kubernetes API https://kubernetes.io/docs/concepts/overview/kubernetes-api/
- Kubernetes API reference: API concepts https://kubernetes.io/docs/reference/using-api/api-concepts/ — server-side apply https://kubernetes.io/docs/reference/using-api/server-side-apply/ — deprecation policy https://kubernetes.io/docs/reference/using-api/deprecation-policy/ — deprecated API migration guide https://kubernetes.io/docs/reference/using-api/deprecation-guide/ — admission controllers https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/ — authentication and credential plugins https://kubernetes.io/docs/reference/access-authn-authz/authentication/
- kubectl: overview https://kubernetes.io/docs/reference/kubectl/ — quick reference https://kubernetes.io/docs/reference/kubectl/quick-reference/ — conventions https://kubernetes.io/docs/reference/kubectl/conventions/ — JSONPath https://kubernetes.io/docs/reference/kubectl/jsonpath/ — kubeconfig https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/ — plugins https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/ — install on macOS https://kubernetes.io/docs/tasks/tools/install-kubectl-macos/ — declarative management https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/ — port-forward https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/ — command reference: apply https://kubernetes.io/docs/reference/kubectl/generated/kubectl_apply/, diff https://kubernetes.io/docs/reference/kubectl/generated/kubectl_diff/, explain https://kubernetes.io/docs/reference/kubectl/generated/kubectl_explain/
- Releases: version skew policy https://kubernetes.io/releases/version-skew-policy/ — release history https://kubernetes.io/releases/ — release cycle https://kubernetes.io/releases/release/ — v1.37 release blog https://kubernetes.io/blog/2026/08/26/kubernetes-v1-37-release/ — v1.34 release blog https://kubernetes.io/blog/2025/08/27/kubernetes-v1-34-release/ — dockershim FAQ https://kubernetes.io/blog/2022/02/17/dockershim-faq/ — stable marker https://dl.k8s.io/release/stable.txt
- Setup: production environment https://kubernetes.io/docs/setup/production-environment/ — container runtimes https://kubernetes.io/docs/setup/production-environment/container-runtimes/ — kubeadm create cluster https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/ — kubeadm HA topology https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/ha-topology/ — kubeadm upgrade https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-upgrade/ — operating etcd https://kubernetes.io/docs/tasks/administer-cluster/configure-upgrade-etcd/ — add-ons https://kubernetes.io/docs/concepts/cluster-administration/addons/ — resource metrics pipeline https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/ — resource quotas https://kubernetes.io/docs/concepts/policy/resource-quotas/
- etcd: why etcd https://etcd.io/docs/v3.6/learning/why/ — FAQ (quorum, odd members) https://etcd.io/docs/v3.6/faq/ — Raft https://raft.github.io/ — etcd raft library https://github.com/etcd-io/raft
- client-go internals (sample-controller): https://raw.githubusercontent.com/kubernetes/sample-controller/master/docs/controller-client-go.md
- Local clusters: kind https://kind.sigs.k8s.io/ — kind quick start https://kind.sigs.k8s.io/docs/user/quick-start/ — kind configuration https://kind.sigs.k8s.io/docs/user/configuration/ — kind v0.33.0 release https://github.com/kubernetes-sigs/kind/releases/tag/v0.33.0 — minikube https://minikube.sigs.k8s.io/docs/start/ — k3s https://docs.k3s.io/ — k3s architecture https://docs.k3s.io/architecture — k3s packaged components https://docs.k3s.io/installation/packaged-components — k3d https://k3d.io/stable/ — k3d config file https://k3d.io/stable/usage/configfile/ — k3d registries https://k3d.io/stable/usage/registries/ — Docker Desktop Kubernetes https://docs.docker.com/desktop/use-desktop/kubernetes/ — OrbStack Kubernetes https://docs.orbstack.dev/kubernetes/
- Managed: Amazon EKS https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html — EKS versions https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html — managed node groups https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html — EKS Auto Mode https://docs.aws.amazon.com/eks/latest/userguide/automode.html — EKS kubeconfig https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html — GKE overview https://cloud.google.com/kubernetes-engine/docs/concepts/kubernetes-engine-overview — Autopilot https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview — release channels https://cloud.google.com/kubernetes-engine/docs/concepts/release-channels — node pools https://cloud.google.com/kubernetes-engine/docs/concepts/node-pools — GKE kubectl access https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl — AKS https://learn.microsoft.com/en-us/azure/aks/what-is-aks — AKS core concepts https://learn.microsoft.com/en-us/azure/aks/core-aks-concepts — AKS versions https://learn.microsoft.com/en-us/azure/aks/supported-kubernetes-versions
- Add-ons and tools: CoreDNS https://github.com/coredns/coredns — metrics-server https://github.com/kubernetes-sigs/metrics-server — Dashboard (archived) https://github.com/kubernetes/dashboard — krew https://krew.sigs.k8s.io/ — containerd https://github.com/containerd/containerd — CRI-O https://github.com/cri-o/cri-o — Helm https://helm.sh/docs/intro/using_helm/
- Laravel 13: deployment (health route, optimize) https://laravel.com/docs/13.x/deployment — requests (trusted proxies) https://laravel.com/docs/13.x/requests — logging https://laravel.com/docs/13.x/logging — configuration https://laravel.com/docs/13.x/configuration
- Go:
net/httpserver (Shutdown) https://go.dev/src/net/http/server.go —os/signal(NotifyContext) https://go.dev/src/os/signal/signal.go — yaml.v3 https://github.com/go-yaml/yaml/tree/v3.0.1