In this lesson, you will learn how the Kubernetes control loop acts as the "brain" of your cluster, constantly working to ensure reality matches your instructions.
The Control Loop in Plain English
Imagine you tell a robot to keep a room at exactly 72 degrees. The robot doesn’t just turn on the heater once; it has a loop that constantly checks the current temperature, compares it to your 72-degree target, and makes adjustments. If the window opens and the temperature drops, the robot sees the difference and increases the heat.
Kubernetes works exactly the same way. This is the Control Loop Pattern. It consists of three ongoing steps:
- Observe: The controller monitors the current state of the cluster (e.g., "I see 0 replicas of my application running").
- Diff: It compares this against the desired state defined in your object configuration (e.g., "The user requested 3 replicas").
- Act: It performs an action to close the gap (e.g., "I will instruct the scheduler to start 3 new pods").
A Concrete Illustration
When you define a Deployment with three replicas, you aren't commanding Kubernetes to "start three pods now." You are defining a desired state in etcd.
The Controller Manager runs a control loop that looks like this:
# A simplified conceptual logic
for {
desired := getDesiredReplicas() // From your YAML
current := getCurrentReplicas() // From the API Server/etcd
if current < desired {
createPod() // Action taken to reconcile
} else if current > desired {
deletePod() // Action taken to reconcile
}
}
This cycle repeats indefinitely. If a pod crashes, the current state drops below the desired state. The control loop detects this discrepancy immediately and triggers the creation of a replacement pod. This is why Kubernetes is "self-healing"—it never stops checking if your cluster is healthy according to your specific configuration. By keeping this loop running, Kubernetes ensures that even if external events change the environment, the cluster configuration remains stable and accurate.
Key Takeaway: The control loop is the heartbeat of Kubernetes, continuously observing current state, comparing it to your desired state, and taking corrective actions to maintain harmony in your cluster.