# Learning Kubernetes from a High-Level Mental Model

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/learn-k8s-from-a-higher-perspective/>). I am continuously working to improve the translation.

## Preface

Although this title and the term (*mental model*) look very AI-ish, I actually think it summarizes things quite well, so I used it as the title.

Let me try to go through the fundamentals of K8S again from this perspective.

## The So-Called "High-Level Mental Model"

Actually, I was inspired by my understanding of git to try re-understanding k8s from this perspective, so let me first explain my understanding of git:

> [!note]
>
> I'd like to think I understand git reasonably well, but that doesn't mean I'm familiar with all kinds of git commands
> 
>- In fact, I only know the basic ones, at most with a few extensions
> 
>What I mean is that I know git's underlying structure, and I can look at git from a high-level perspective:
> 
>- git can be understood as a DAG (directed acyclic graph)
> - Each node in this graph is a commit, and a commit is a complete snapshot of a version
> - The parent commit (previous version) always points to the child commit (next version), and the incremental changes in the process are the version changes (**state machine transitions**)
> - Inside a commit there are blobs, and **logically** a blob is the content of each file tracked by git in that version
> - A so-called branch is just a pointer; the branch's name (a string) points to some commit; when commits are updated, the branch moves along the DAG accordingly
> - There is a staging area, which controls which files need to be migrated during the state machine transition
> 
>I can consider that git consists of roughly just these things, and this can be called my **mental model** of git. In theory, I can now perform **any** git operation.
> 
>For example, I don't necessarily need to know what the command for some operation is; I can describe it to an agent, for instance:
> 
>- I want to move the part of the commit tree from commit A to commit B onto commit D, essentially a grafting operation.
> - Then the agent can help me execute a rebase (or possibly a cherry pick, or directly call some plumbing commands I don't know about)
> 
>As long as I understand git's underlying structure, I can operate it from a high-level perspective.

So I want to build a similar mental model for k8s, with roughly these key points:

(Actually, I think the answer Gemini 4 Hydrogen gave me was pretty good, but for the sake of review, I'll type it out myself)

Understanding it from the highest level of abstraction:

- k8s has a giant central bulletin board (etcd)
- All components **do only two things**: 1. Modify the requests on the bulletin board 2. Watch the requests on the bulletin board and do the work

Going one level down:

etcd is the **sole state store**; any component such as Pod, Deployment, etc., is essentially just structured YAML data in etcd.

The structured data can be divided into two parts:

- Spec: declares what state is desired
- Status: the actual current state

The API Server is the **sole communication bus**; all communication between components goes through the API Server. The API Server is essentially just a **RESTful API Server** + **Watch mechanism** (long-lived connection listening). **Any `kubectl` operation is merely sending an HTTP request to the API Server**, either returning read-only data or modifying the spec's content (modifying some field in etcd).

The part that is actually responsible for managing state is called the **Controller**; they **do not communicate with each other and run independently**. The core of a Controller is called the **Reconcile Loop**, roughly pseudocode like this:

```go
for {
  desired := watchSpecFromAPIServer()
  actual := watchStatusFromAPIServer()
  if desired != actual {
    doSomethingToAlignThem()
  }
}
```

However, Controllers work at a certain granularity, and since they cannot communicate directly with each other, they must communicate through the **Watch mechanism** and the **etcd database**, forming a **chained relay**. For example:

> [!note]
>
> - The user modifies the Deployment's spec via `kubectl`, declaring that the desired number of Pods changes from 3 to 5
> - After the Deployment Controller detects the change, it modifies the ReplicaSet's Spec to 5
> - After the ReplicaSet Controller detects the change, it writes two additional new Pod objects into etcd.
>   - Note that these Pod objects are only **declared**; there is no corresponding actual runtime, and `Spec.nodeName` is empty
> - The Scheduler (also a Controller) watches all Pods with an empty `Spec.nodeName`; once it finds one, it computes resources to find an idle node, then fills `nodeName` into the corresponding field. **Note that at this point it has only modified the spec and has not actually started the runtime**.
> - Each node has a kubelet component, which watches for Pods whose `Spec.nodeName` is itself; once it detects a new one, it actually pulls the image and runs the runtime in its own VM
> - Meanwhile, the node also contains CNI and kube-proxy, which work together with the Service component to manage the local machine's network forwarding and rules, etc.

At the same time, this architecture is **extensible**, reflected in these two features:

- CRD (Custom Resource Definition) is essentially defining a custom YAML format, telling the API Server that a self-defined kind of object exists
- An Operator is a program you write yourself and deploy into the cluster, using the API Server's Watch mechanism to manage CRDs; in essence, it is a Custom Controller

We can easily notice one of k8s's inherent flaws:

1. Declaration != implementation; the corresponding expectation is expressed, but it doesn't mean the state machine has completed the transition, so there are naturally issues like latency
2. Some others to be added TODO

## [Kubernetes Tutorials](https://kubernetes.io/zh-cn/docs/tutorials/)

With this perspective in hand, let's try re-reading the official k8s tutorial documentation.

[The first article](https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro/) says that a k8s cluster can consist of two parts: the Control Plane and Nodes

- The Control Plane contains kube-api-server, etcd, kube-scheduler, kube-controller-manager
- A Node contains kubelet, container runtime

[The second article](https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/deploy-app/deploy-intro/) mainly introduces what a Deployment is.

In short, it packages all the requirements for running pods into a single API Object, such as Pod creation rules, the desired number of replicas, and the update strategy.

Specifically, three fields:

- `replicas` describes the desired number of pods to run
- `template` describes how this Pod should be created, such as where to pull the image from, environment variable settings...
- `selector` describes which pods to manage and how to identify them; you can think of this as a CSS selector—it needs specific labels to identify the scope under its jurisdiction

[The third article](https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/explore/explore-intro/) mainly goes deeper into Nodes and Pods.

A Pod is the smallest unit of scheduling in k8s and can contain **several containers**; a pod has these characteristics:

- Shared network namespace, e.g., all containers can access each other via localhost
- A Pod has Volumes, and containers within the pod can mount the volume to different places
- The scheduler's smallest unit of scheduling is the pod

> [!note]
>
> **Why do we need Pods instead of directly managing Containers?**
>
> You can understand this from a concrete scenario.
>
> Suppose there is a Web Server that needs a log collector to continuously read the log files it generates.
>
> If the two containers were completely independent, you would need to additionally solve:
>
> - How to let the two containers share files?
> - How to make them deploy on the same machine?
> - How to make them use a common network address?
> - How to make them have the same lifecycle?
>
> A Pod organizes these related resources into a whole. This forms a very natural abstraction: **A Pod = a group of containers that need to be scheduled together and share part of the runtime environment.**

A Node can be understood as a **worker machine** in the k8s cluster (it can be a physical machine or a virtual machine).

A Node consists of:

- At least one pod
- kubelet, which manages pods and containers, and registers the node with the api server
- container runtime

If a node goes down, the pods inside it have their nodeName field removed, and then wait to be reassigned.

> [!note]
>
> Regarding persistence, it involves concepts like StatefulSet, PersistentVolume, etc.—more on that later.

[The fourth article](https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/expose/expose-intro/) is mainly about Services.

Roughly speaking:

- To solve the problem that Pods may repeatedly go offline causing their IPs to keep changing, while Pods need to communicate with each other, a Service can provide something like DNS

- Each Pod has a Label, like this:

  ```yaml
  # Pod A
  metadata:
    labels:
      app: backend
      version: v1
  ```
  
- A Service can select Pods with specific Labels (by defining the `spec.Selector` field) and give it a name (similar to DNS), say `backend`, so that other Pods can access it via `backend:80`

- Note that port forwarding can also be configured yourself; omitted here

The implementation behind this relies on the EndpointSlice component, which can be understood as a DNS table, maintained by watching state.

> [!note]
>
> You can think of it as the chained relationship between Deployment and ReplicaSet.

Traffic forwarding is implemented by the kube-proxy component in the control plane using Linux kernel forwarding (configuring network forwarding rules such as iptables or nftables).

- **Note this has nothing to do with the API Server**; the API Server is only responsible for resource-management-related requests

[The last article](https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/update/update-intro/) mainly covers how k8s performs rolling updates; in one sentence, it modifies the Pod Template in a Deployment, then triggers a Rollout, gradually creating new Pods and deleting old ones.
