# Kubernetes: what it solves, and when you don't need it

The problems that appear once you run many containers, how desired state and control loops fix them, the core objects and parts of a cluster, and the honest alternatives.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 1. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/01-why-kubernetes

## What you will learn

- Explain the problems Kubernetes solves that Docker on one server doesn't
- Describe desired state and the control loop in your own words
- Name the core objects (Pod, Deployment, Service, Namespace) and what each one is for
- Name the parts of a cluster and what happens when you run `kubectl apply`
- Decide when a simpler option than Kubernetes is the better choice

## The problem after containers

On one server, Docker is all you need. `docker run` starts the app, and if it crashes you
restart it. Now picture 30 servers running 200 containers for 15 services, and ask:

- Which server has room for the next container?
- A server dies at 3 a.m. Who restarts its containers somewhere else?
- How do you roll out a new version without downtime, and roll it back when it's bad?
- Containers move between servers and their IPs change. How does one service find another?
- Traffic triples on sale day. Who adds copies, and removes them afterwards?

Doing that by hand or with scripts is a full-time job. **Kubernetes** is a system that does it
for you: you give it a cluster of machines and a description of what should run, and it keeps
it running. It grew out of Borg, Google's internal cluster manager, was open-sourced in 2014
and is now looked after by the CNCF.

## Desired state and the control loop

This is the one idea that makes Kubernetes click. You don't tell it **what to do**; you tell it
**what you want**, and it works out the steps.

```yaml
# web.yaml: "I want three copies of nginx running, always."
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:1.27
          ports:
            - containerPort: 80
```

```sh
$ kubectl apply -f web.yaml
deployment.apps/web created
```

From then on, **controllers** run a loop that never stops: look at what's running, compare it
with what you declared, and fix the difference. A Pod crashes? Start another. You change
`replicas` to 5? Two more appear. A node disappears? Its Pods are recreated elsewhere, but not
instantly, because Kubernetes first has to be sure the node is really gone.

### What a node failure really looks like

On the course's EKS cluster, one worker node's EC2 instance was terminated, as if the machine had
died. The real timeline:

| Time   | What happened                                                                                    |
| ------ | ------------------------------------------------------------------------------------------------ |
| t+16s  | The node stopped reporting; its status became **NotReady**                                       |
| t+78s  | AWS reported the instance gone, so the node object was **deleted** and its Pods were rescheduled |
| t+111s | The node group's Auto Scaling group had launched a **replacement node**, now Ready               |
| t+142s | Every shop-web Pod was **Running** again                                                         |

It took over two minutes, not seconds, and it was this fast only because the cloud provider could
confirm the instance no longer existed. When a node is merely **unreachable** (a network problem, a
hung kubelet) and its machine still exists, Kubernetes marks it NotReady, taints it, and waits: every
Pod carries a default toleration of **300 seconds** for that taint, so its Pods are evicted after five
minutes. That's deliberate: a node that comes back quickly shouldn't lose every Pod. It's also why
production apps run at least two replicas spread across nodes.

That's why the same file is your documentation and your deploy, and why rebuilding a lost cluster
can start from the same files. It isn't a full disaster-recovery plan, though: manifests describe
your apps, not their **data**. Databases, volumes and uploaded files need their own backups (EBS
snapshots, database backups, or a tool such as Velero), and the Storage lesson comes back to this.

## The objects you'll use every day

| Object     | What it is                                                                                                                  |
| ---------- | --------------------------------------------------------------------------------------------------------------------------- |
| Cluster    | A set of machines Kubernetes manages as one                                                                                 |
| Node       | One machine (usually a VM) in the cluster that runs your Pods                                                               |
| Pod        | The smallest unit: one or more containers sharing an IP address and storage                                                 |
| Deployment | Keeps N identical Pods running (through a ReplicaSet) and rolls out new versions gradually                                  |
| Service    | One stable name and IP in front of a changing set of Pods                                                                   |
| Namespace  | A scope for names, permissions and quotas, to separate teams or environments in one cluster. Not a security wall on its own |

Everything is an object with the same shape: `apiVersion`, `kind`, `metadata` and `spec`. Learn
to read one and you can read them all.

## The parts of a cluster

> **Figure.** A Kubernetes cluster. The control plane has the API server, etcd, the scheduler and the controller manager. Each worker node runs a kubelet, kube-proxy and a container runtime, which run the Pods. kubectl talks only to the API server.
>
> kubectl talks to the API server. The control plane decides; the nodes run the Pods.

**The control plane** is the brain:

- **API server**: the front door. `kubectl`, the other components and your CI all talk to it, and only it.
- **etcd**: a key-value store holding every object and its desired state.
- **Scheduler**: picks a node for each new Pod, based on free CPU and memory and your rules.
- **Controller manager**: runs the control loops, like the one that keeps a Deployment at 3 Pods.

**Worker nodes** do the work:

- **kubelet**: an agent on each node that starts the Pods it's given and reports their health.
- **kube-proxy**: sets up the networking rules that make Services reach the right Pods.
- **Container runtime**: usually containerd, which actually runs the containers.

So `kubectl apply` means, step by step:

1. The API server validates your Deployment and stores it in etcd.
2. The **Deployment controller** creates a **ReplicaSet** for this version of the Pod template.
3. The **ReplicaSet controller** sees it wants 3 Pods and has 0, and creates three Pod objects.
4. The scheduler assigns each Pod to a node, and each node's kubelet starts the containers.

Each layer has one job. The ReplicaSet keeps the **count** right; the Deployment manages
**versions**, creating a new ReplicaSet for each new template and shifting Pods from the old one to
the new one during a rollout. When a Pod is deleted, it's the ReplicaSet that replaces it.

A namespace deserves a warning too. It scopes names (two teams can both have a `web`), and you attach
RBAC permissions and resource quotas to it. But by default, Pods in different namespaces can still
talk to each other over the network, and namespaces share nodes. Real isolation needs NetworkPolicies,
RBAC and sometimes separate node groups or clusters, all covered in the Security lesson.

## When you don't need Kubernetes

Kubernetes is powerful, and it's also a lot to run and to learn. Be honest about the job:

| Situation                                      | Often a better fit                      |
| ---------------------------------------------- | --------------------------------------- |
| One or two services, steady traffic            | One VM with Docker Compose              |
| Containers on AWS without managing a cluster   | Amazon ECS with Fargate, or App Runner  |
| Containers on Google Cloud or Azure            | Cloud Run, or Azure Container Apps      |
| A web app and no ops team                      | A PaaS such as Render, Fly.io or Heroku |
| Mixed workloads, containers and plain binaries | HashiCorp Nomad                         |

Kubernetes earns its cost with many services, several teams, real scaling needs, or the need
to run the same way across clouds. Until then, simpler is faster.

> **In production, use a managed control plane.** Running etcd and the control plane yourself is hard to get right. Most teams use EKS, GKE or AKS, where the cloud provider runs and upgrades the control plane and you manage the nodes and what runs on them.

## Mission: Watch Kubernetes replace a deleted Pod

Prove the control loop to yourself. On a local kind cluster, run three nginx Pods, record their names, delete one, and record the names again. The file should show that one Pod was replaced and three are still running. This tests Pod self-healing; node failure behaves differently, as described above.

- You need: A kind cluster named academy
- You'll have: ~/self-healing.txt

```sh
$ kind create cluster --name academy
$ kubectl create deployment web --image=nginx:1.27 --replicas=3
$ kubectl rollout status deployment/web
deployment "web" successfully rolled out
$ kubectl get pods -l app=web -o name > ~/self-healing.txt
$ kubectl delete $(head -n 1 ~/self-healing.txt)
pod "web-7c5d8bf7b-2xk9q" deleted
$ echo "--- after ---" >> ~/self-healing.txt
$ kubectl get pods -l app=web -o name >> ~/self-healing.txt
$ cat ~/self-healing.txt              # your Pod names will differ
pod/web-7c5d8bf7b-2xk9q
pod/web-7c5d8bf7b-8hjtm
pod/web-7c5d8bf7b-qz4wd
--- after ---
pod/web-7c5d8bf7b-8hjtm
pod/web-7c5d8bf7b-qz4wd
pod/web-7c5d8bf7b-vn5lp
$ kind delete cluster --name academy
```

The ReplicaSet controller saw two Pods instead of three and created `vn5lp` within seconds. This is
**Pod** self-healing: a deleted Pod is noticed immediately. A failed **node** takes longer, because
Kubernetes first has to decide the node is really gone, as the timeline above shows.
Nobody ran a restart command. `kubectl create deployment` labels the Pods `app=web`, which is
how `-l app=web` finds them.

## Try it

- Install `kubectl` and `kind`, then create a cluster with `kind create cluster --name academy`.
- Run `kubectl get nodes` and `kubectl get pods -n kube-system`. Match the pods you see to the control plane parts in this lesson.
- Create a Deployment with three nginx replicas and list its Pods.
- Delete one Pod and watch the Deployment replace it with `kubectl get pods -w`.
- Scale the Deployment to five replicas with `kubectl scale`, then delete the cluster.

## Quiz

1. You told Kubernetes to run 3 replicas. A node dies and takes one Pod with it. What happens?
   - Nothing until you run kubectl again
   - **After Kubernetes decides the node is gone, a controller sees 2 running instead of 3 and starts a new Pod on a healthy node** (answer)
   - The whole Deployment restarts
   Why: That's the control loop. Once Kubernetes decides the node is gone (in the course lab, about 80 seconds after the instance died; up to 5 minutes for an unreachable node), the ReplicaSet notices only 2 Pods and starts a new one on a healthy node.

2. Which component decides which node a new Pod runs on?
   - The kubelet
   - **The scheduler** (answer)
   - etcd
   Why: The scheduler picks a node that has room and meets the Pod's rules. The kubelet on that node then starts it, and etcd only stores the cluster's state.

3. What is the smallest thing Kubernetes deploys and schedules?
   - A container
   - **A Pod** (answer)
   - A Deployment
   Why: A Pod wraps one or more containers that share a network address and storage. Deployments manage Pods; you rarely create a bare Pod yourself.

4. A two-person startup runs one web app and one database with low, steady traffic. What is usually the best fit?
   - A self-managed Kubernetes cluster
   - **A single VM with Docker Compose, or a managed container service** (answer)
   - Three Kubernetes clusters, one per environment
   Why: Kubernetes pays off when you have many services, teams or scaling needs. For a small app, its running cost and learning curve buy you very little.

5. Where does the cluster keep its record of every object and its desired state?
   - **In etcd** (answer)
   - On each node's disk
   - In the container registry
   Why: etcd is the control plane's key-value store. The API server is the only component that talks to it; everything else goes through the API server.

## Resources

- [Kubernetes overview](https://kubernetes.io/docs/concepts/overview/) (Kubernetes Docs)
- [Kubernetes components](https://kubernetes.io/docs/concepts/overview/components/) (Kubernetes Docs)
- [Deployments](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) (Kubernetes Docs)
- [Install tools (kubectl, kind, minikube)](https://kubernetes.io/docs/tasks/tools/) (Kubernetes Docs)
- [kind quick start](https://kind.sigs.k8s.io/docs/user/quick-start/) (kind)
- [Large-scale cluster management at Google with Borg](https://research.google/pubs/large-scale-cluster-management-at-google-with-borg/) (Google Research)
- [Kubernetes the hard way](https://github.com/kelseyhightower/kubernetes-the-hard-way) (Kelsey Hightower)
