Declarative vs. Imperative
[!TIP] The Thermostat Analogy
- Imperative: “Turn on the heater. Wait 10 minutes. Turn it off.” (You are managing the process).
- Declarative: “I want the temperature to be 72°F.” (You set the goal, the system manages the process). Kubernetes is a Thermostat for your infrastructure.
1. Imperative (The Old Way)
In traditional systems (or scripts), you list the steps to achieve a result.
# Imperative: Do this, then do that.
docker run -d --name my-app nginx
# If it crashes? You have to run it again.
# If you need 2 more? You run it 2 more times.
This is brittle. If a step fails, the script breaks. If the environment changes (server dies), the script doesn’t know.
2. Declarative (The Kubernetes Way)
In Kubernetes, you define the Desired State in a manifest (YAML). You hand this manifest to the API Server.
# Declarative: This is what I want.
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3 # I want 3 copies. Always.
template:
spec:
containers:
- name: nginx
image: nginx
Kubernetes takes this “Wish List” and works tirelessly to make it true.
3. The Reconciliation Loop (Controller Pattern)
This is the heartbeat of Kubernetes. Every controller (Node, ReplicaSet, Endpoints) runs a loop:
- Observe: Check the Current State (e.g., “There are 2 pods running”).
- Diff: Compare with Desired State (e.g., “The user wants 3 pods”).
- Act: Perform an operation to fix the difference (e.g., “Start 1 more pod”).
This loop runs forever. If a pod crashes 5 minutes later, the controller notices the diff (2 vs 3) and creates a new one. Self-Healing.
4. Interactive: The Reconciliation Game
You are the Controller. Your goal is to keep the system in sync.
- Desired State: The target number of green squares.
- Current State: The actual number of green squares.
- Task: Click “Add” or “Remove” to match the Desired State. But watch out! Random chaos will destroy your squares.
5. Level Triggered vs Edge Triggered
- Edge Triggered: You get a notification only when a change happens. If you miss the event (network blip), you are out of sync forever.
- Level Triggered: You check the state periodically. Even if you miss an event, the next check will see “Oh, I have 2 but I need 3”.
Kubernetes is Level Triggered. This makes it incredibly robust.
In the next module, we will start looking at the Core Objects (Pod, Deployment, Service) that you will use every day.