Desired state: controllers, built-in objects and custom resources
Name the parts of a cluster, watch a reconciliation loop work in a toy controller you can run, and connect the objects you will use in every later lesson: Pods, ReplicaSets, Deployments, Services, namespaces and custom resources.
Contentsand lesson path
On this page
- Why it matters
- The control plane and the nodes
- The reconciliation loop
- Pods, ReplicaSets and Deployments
- Services and namespaces
- Self-healing when a node is lost
- Custom resources and operators
- Check your understanding
- Apply it
- Review prompt
Lessons of Kubernetes Fundamentals
- Desired state: controllers, built-in objects and custom resources Concept · 20 min
- Lab: deploy, configure and expose a service with honest probes, requests and limits Lab · 40 min
- Lab: rollouts, rollbacks, autoscaling and environment overlays Lab · 30 min
- Lab: Jobs, StatefulSets and persistent volumes Lab · 30 min
- Why it will not run: scheduling, quotas, images, crashes and evictions Worked example · 25 min
- Check: repair broken workloads against the clock Knowledge check · 10 questions
What you will learn
- Explain the control plane, nodes and the reconciliation loop, and how Pods, ReplicaSets, Deployments, Services and namespaces relate.
Prerequisites: Containerization
01. Why it matters
Kubernetes does not run your commands one by one. It records what you want, then keeps working until the cluster matches. Most surprises in this skill, from a Pod that comes back after you delete it to a rollout that never finishes, make sense once you can say which component is comparing which two things.
This lesson names the parts of a cluster, shows the reconciliation loop in a toy controller you can run, and connects the objects that every later lesson uses: Pods, ReplicaSets, Deployments, Services and namespaces. It ends with custom resources, the way Kubernetes is extended with the same pattern.
02. The control plane and the nodes
A cluster has a control plane, which stores state and makes decisions, and nodes, which run your containers.
- kube-apiserver is the front door. Every client, from
kubectlto the controllers, reads and writes objects through it. It authenticates and authorises each request, runs admission checks, and is the only component that talks to etcd, the key-value store that holds every object. - kube-controller-manager runs many controllers in one process: Deployment, ReplicaSet, Job, node lifecycle, EndpointSlice and more. Each one watches some object types and makes changes through the API server.
- kube-scheduler watches for Pods that have no node yet and picks a node that fits their resource requests, node selectors, affinity rules and tolerations. It only records the decision in
spec.nodeName; it starts nothing. - On every node, the kubelet watches for Pods bound to that node, asks the container runtime (for example containerd) to start their containers, runs their probes and reports status back. kube-proxy, or a network plugin that replaces it, programs the node so that traffic sent to a Service reaches a ready Pod.
On a managed service such as EKS, GKE or AKS, the provider runs the control plane for you. You still meet every one of these components through their behaviour.
03. The reconciliation loop
Most objects have a spec, what you asked for, and a status, what a controller last observed. A controller runs a loop: read the desired state, observe the actual state, act to reduce the difference, repeat. It does not follow a stored list of steps, so it copes with any starting point, including one left behind by a crash halfway through a change.
The toy below is a ReplicaSet controller in a few lines of Python. Run it with Python 3.10 or later; it needs no cluster.
"""A toy ReplicaSet controller: compare desired with observed, then act."""
import itertools
desired = 3
pods = {"web-a1", "web-b2", "web-c3"} # what the "API server" currently stores
names = (f"web-n{i}" for i in itertools.count(1))
def reconcile() -> None:
diff = desired - len(pods)
for _ in range(diff): # too few: create
pods.add(next(names))
for name in sorted(pods)[: max(-diff, 0)]: # too many: delete
pods.remove(name)
print(f"desired={desired} observed={len(pods)} pods={sorted(pods)}")
reconcile() # nothing to do
pods.discard("web-b2") # someone deletes a Pod
reconcile() # a new Pod with a new name appears
desired = 2 # someone scales down
reconcile()python3 reconcile.pydesired=3 observed=3 pods=['web-a1', 'web-b2', 'web-c3']
desired=3 observed=3 pods=['web-a1', 'web-c3', 'web-n1']
desired=2 observed=2 pods=['web-c3', 'web-n1']Three things to notice. The controller does not care why a Pod disappeared. The replacement gets a new name, because a deleted Pod is never brought back. And scaling down is the same loop with the sign reversed.
Real controllers also cope with each other. Every object carries metadata.resourceVersion. If two writers both try to update the same version, the API server accepts the first and rejects the second with 409 Conflict; the loser reads the object again and recomputes its change.
04. Pods, ReplicaSets and Deployments
- A Pod is one or more containers that share a network namespace (one IP address,
localhostbetween them) and volumes. A Pod is scheduled once. If its node dies, the Pod is gone, and nothing recreates a Pod that no controller owns. - A ReplicaSet keeps a set number of Pods that match its label selector. Its controller creates or deletes Pods; it recreates Pods lost to a node failure when some node has room for them, but it cannot make them healthy.
- A Deployment manages ReplicaSets. When you change its Pod template, it creates a new ReplicaSet and moves replicas from the old one to the new one; lesson 4 covers the rules. You rarely edit ReplicaSets yourself.
Ownership is recorded in metadata.ownerReferences: each Pod points at its ReplicaSet, which points at its Deployment, and deleting an owner deletes what it owns. Selection works through labels: the Deployment selector must match the labels in its Pod template, or the API server rejects it.
05. Services and namespaces
A Pod gets a new IP address every time it is replaced, so clients need something stable. A Service gives a set of Pods, chosen by label selector, one virtual IP address and one DNS name. The EndpointSlice controller keeps the list of matching Pods and marks each endpoint ready or not ready from the Pod readiness; kube-proxy sends new connections only to ready endpoints. The main types are:
ClusterIP, the default: reachable only inside the cluster.NodePort: also opens the same port, from 30000–32767 by default, on every node.LoadBalancer: also asks the cloud provider, or a local add-on, for an external load balancer.- Headless (
clusterIP: None): no virtual IP; DNS returns the Pod addresses directly. Lesson 7 uses one for a database.
A namespace is a scope for names and policy. Two teams can each have a Service called web in their own namespace. RBAC roles, ResourceQuotas and LimitRanges apply per namespace, and cluster DNS includes the namespace in every Service name. Namespaces are not a network boundary on their own: without NetworkPolicies, Pods in different namespaces can still reach each other. Some objects are cluster-scoped and belong to no namespace, such as Nodes, PersistentVolumes, StorageClasses and namespaces themselves.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: payments
spec:
replicas: 3
selector:
matchLabels:
app: web # which Pods this Deployment's ReplicaSets own
template:
metadata:
labels:
app: web # must match the selector above
spec:
containers:
- name: app
image: docker.io/library/python:3.13-alpine
command: ["python", "-m", "http.server", "8080"]
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: web
namespace: payments
spec:
type: ClusterIP # the default: a virtual IP reachable inside the cluster
selector:
app: web # every ready Pod with this label becomes an endpoint
ports:
- port: 80 # clients call web.payments:80
targetPort: 8080 # traffic is sent to containerPort 8080 on the PodFrom a Pod in namespace payments: web
From a Pod in another namespace: web.payments
Fully qualified name: web.payments.svc.cluster.local06. Self-healing when a node is lost
Here is what happens, with default settings in current releases, when a node running one of three web replicas loses power.
- The kubelet stops renewing its node Lease. After
--node-monitor-grace-period(50 seconds by default since v1.32; 40 seconds before) the node lifecycle controller in kube-controller-manager sets the nodeReadycondition toUnknown, marks the Pods on it not ready, and adds the taintnode.kubernetes.io/unreachablewith effectNoExecute. Because those Pods are not ready, the Service stops sending them new connections. - Kubernetes gives every Pod a toleration for that taint with
tolerationSeconds: 300, unless you set your own. The Pods stay bound for five more minutes in case the node comes back; then the controller evicts them. - The ReplicaSet controller now counts 2 Pods against
replicas: 3and creates a replacement from its template. The scheduler binds it to a healthy node with room for its requests, and the kubelet on that node starts it.
So by default a lost node costs about six minutes of reduced capacity, and the replacement stays Pending if no other node has room. Run enough replicas, spread across nodes, to absorb that.
07. Custom resources and operators
Kubernetes is extended with the same pattern. A CustomResourceDefinition (CRD) adds a new object type to the API, such as PostgresCluster; the API server stores and validates it like a built-in type. On its own a CRD does nothing. An operator is a controller you install that watches those objects and reconciles them, for example by creating a StatefulSet, taking backups or promoting a replica after a failure.
You will meet this in lesson 2: the Gateway API is a set of CRDs, and nothing routes traffic until you install a controller that implements them. For complex stateful systems, a mature operator is usually safer than hand-written manifests, but it runs with broad permissions in your cluster, so read what it is allowed to do before you install it.
08. Check your understanding
09. Apply it
Once you have the kind cluster from lesson 2, use it to see these ideas for real:
- Run
kubectl get pods -n kube-system -o wideand match each Pod to a component named in this lesson. Which ones run on every node? - Delete one Pod of a Deployment while
kubectl get pods -wruns in a second terminal. Then print the owner of the new Pod withkubectl get pod <name> -o jsonpath='{.metadata.ownerReferences[0].name}'. - Create two namespaces, put a Service called
webin each, and resolve both from a temporary Pod:kubectl run dns --rm -it --restart=Never --image=busybox:1.37 -- nslookup web.<namespace>.svc.cluster.local.
10. Review prompt
Without looking back, write down: which component stores cluster state, which assigns Pods to nodes and which starts containers; what a ReplicaSet controller compares, and why a replacement Pod has a new name; how a Service finds its Pods and which of them get traffic; which DNS name reaches a Service in another namespace; and what a CRD needs before it does anything.
References
- Kubernetes Documentation: Cluster components
- Kubernetes Documentation: Controllers
- Kubernetes Documentation: ReplicaSet
- Kubernetes Documentation: Service
- Kubernetes Documentation: Namespaces
- Kubernetes Documentation: Taints and tolerations (taint-based evictions)
- Kubernetes Documentation: Custom resources
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.