Kubernetes Basics — DevOps

Kubernetes (K8s) is a container orchestration platform: a platform that runs and manages containers across many servers. You write a desired state (the state…

If web-1 died right now, who would start notes-api on another server? With Docker Compose, the answer is you, once someone tells you. Compose runs its command once, on that one server.

Kubernetes (K8s for short) takes that job over. It is a container orchestration platform: a platform that runs and manages containers across many servers. You write down the state you want, for example "3 notes-api containers from image e4b2d90". Then Kubernetes keeps making reality match it. Picture a cashier supervisor at a minimarket, with a board that says "3 tills open". Nobody has to tell them anything. Every few minutes they look at the tills. If a cashier goes home sick, they call a replacement. If the board changes to "5 tills", they open two more. A new cashier who is still counting the money in the drawer isn't asked to serve the queue yet. In this picture, the board is the state you write down, and the supervisor is Kubernetes. Each cashier is one notes-api container, and a cashier still counting the money is a container that isn't ready to serve requests yet. One honest note first: notes-api, which runs on a single VPS web-1 with Docker Compose, does not need Kubernetes yet. This lesson shows how Kubernetes works, and at the end we look at when it is worth using.

Desired state: you write the goal, not the steps

With Compose, docker compose up -d runs a command once. If the container dies because its server died, nobody starts it on another server.

Kubernetes works on a cluster: a group of servers Kubernetes manages. Each server in the cluster is a node. In the Lab, the cluster has two nodes, node-1 and node-2.

In that cluster you store a desired state (the state you want). Then a controller (a program inside Kubernetes that watches over something) runs a reconcile loop: three steps, repeated without stopping. The controller is the supervisor in the minimarket picture.

  1. Look at the real state (the actual state): how many pods (containers that Kubernetes runs), which image, healthy or not.
  2. Compare it with the desired state.
  3. If they differ, take the smallest action that makes them match. If they already match, do nothing.
Desired Actual What the controller does
3 pods 3 healthy pods nothing
3 pods 2 pods (one deleted) create 1 new pod
5 pods 3 pods create 2 new pods
1 pod 3 pods delete 2 pods (pods not running yet first, then usually the newest)

Pod, Deployment, Service

This is notes-api in Kubernetes' language, the same as in the Lab. One YAML file holds two objects: a Deployment and a Service.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes-api
spec:
  replicas: 3                     # desired state: 3 pods
  selector:
    matchLabels:
      app: notes-api
  template:                       # the mould for every pod
    metadata:
      labels:
        app: notes-api
    spec:
      containers:
        - name: app
          image: ghcr.io/budi/notes-api:e4b2d90
          ports:
            - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: notes-api
spec:
  selector:
    app: notes-api                # send requests to pods with this label
  ports:
    - port: 80
      targetPort: 3000

Delete one pod: the reconcile loop at work

This is the terminal as the file is applied, the pods are listed with kubectl get pods, and then one pod is deleted:

$ kubectl apply -f notes-api.yaml
deployment.apps/notes-api created
service/notes-api created
$ kubectl get pods
NAME                         READY   STATUS    RESTARTS   AGE
notes-api-7c9d8b6f5d-fprwl   1/1     Running   0          4m
notes-api-7c9d8b6f5d-jckhz   1/1     Running   0          4m
notes-api-7c9d8b6f5d-kw44q   1/1     Running   0          4m
$ kubectl delete pod notes-api-7c9d8b6f5d-fprwl
pod "notes-api-7c9d8b6f5d-fprwl" deleted

As soon as pod fprwl starts being deleted, the ReplicaSet sees only 2 active pods, where the desired state says 3. So the ReplicaSet creates a new pod right away. This is kubectl get pods for that replacement, second by second, exactly as in the Lab:

Second New pod's STATUS READY Why
0 Pending 0/1 created, waiting to be placed on a node
5 ContainerCreating 0/1 the node pulls the image and prepares the container
10 Running 0/1 the container runs, the app is still booting (starting up, which takes 10 seconds)
20 Running 1/1 the readiness probe (the "ready yet?" check, covered below) passes, the Service starts sending requests

So at second 20, three pods are 1/1 again, but the third has a new name, for example notes-api-7c9d8b6f5d-nn9rd. The deleted pod never comes back. Kubernetes doesn't care which pod. Kubernetes only makes sure the count matches the desired state.

The other commands you use in the Lab:

$ kubectl scale deployment notes-api --replicas=5
deployment.apps/notes-api scaled
$ kubectl set image deployment/notes-api app=ghcr.io/budi/notes-api:a41c9e2
deployment.apps/notes-api image updated

Readiness vs liveness

Kubernetes knows a pod is healthy through probes: requests Kubernetes sends to the container on a schedule. These are two probes for notes-api. Both are written inside the app container in the template, at the same level as image: and ports::

          readinessProbe:
            httpGet:
              path: /health
              port: 3000
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 15
            periodSeconds: 5
readinessProbe livenessProbe
The question ready to take requests? still alive?
When it fails the pod is taken out of the Service, not restarted after 3 failures, the container is restarted (RESTARTS goes up)
Protects against requests to an app that is still booting an app that hangs (stops answering) forever

When you need Kubernetes, and when you don't yet

notes-api today: one VPS, three containers (app, Postgres, Redis), one small team. Compose with restart: unless-stopped already restarts a crashed container, and deploys through GitHub Actions are already automatic. Kubernetes adds a control plane (the programs that run the cluster), much longer YAML, and new things to learn and pay for. For notes-api, that is cost with no benefit.

Kubernetes starts to be worth its cost in three situations:

Between Compose and Kubernetes sits PaaS (the Platform as a Service lesson), which runs the servers for you without Kubernetes YAML.

A small reconcile loop

In the exercise, you write the "act" part of the reconcile loop. Pods get simple names app-1, app-2, and so on. The function simulateScaling(currentPods, desiredReplicas) returns a list of actions. Each action is an object { action, pod }, with the key action first, then pod:

⚠️ Mistakes that make a cluster more fragile, not less

TL;DR: Kubernetes (K8s) is a container orchestration platform: a platform that runs and manages containers across many servers. You write a desired state (the state you want), and a reconcile loop maintains it without stopping: look at the actual state (the real state), compare, act. A Pod is the smallest unit (one container with one IP) and is disposable. A Deployment holds replicas (the number of pods) and its template (the mould for every pod). A Service gives one fixed address and spreads requests over the pods that are ready (ready to take requests). The command kubectl get pods shows the columns NAME, READY, STATUS, RESTARTS, AGE. A deleted pod is replaced by a new pod with a new name (Pending, ContainerCreating, Running 0/1, then 1/1). kubectl scale changes the number of pods. kubectl set image starts a rolling update: old pods are only stopped after new pods are ready. A readiness probe (a regular "ready yet?" check) decides when a pod gets requests, and a liveness probe (a "still alive?" check) restarts a container that hangs (stops answering). notes-api on one VPS doesn't need Kubernetes yet. Kubernetes is worth it with many servers, many services and many teams.

⚡ Write the goal, not the steps

Write:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes-api
spec:
  replicas: 3

Meaning: Kubernetes is a container orchestration platform: a platform that runs and manages containers across many servers. This file stores a desired state (the state you want) in a Deployment: replicas: 3 means 3 copies of notes-api must always be running. Then a controller (a watcher inside Kubernetes) keeps looking at the real state, comparing the two, and acting until they match.

⚡ Pod, Deployment, Service

Write:

kubectl apply -f notes-api.yaml
kubectl get pods

Meaning: kubectl apply sends the notes-api YAML file to Kubernetes, and kubectl get pods lists its pods. A Pod is the smallest unit (one container with one IP) and is disposable. A Deployment holds the replicas count and its template (the mould for every pod). A Service gives one fixed address and spreads requests over the pods that are ready (ready to take requests).

⚡ Delete one pod

Write:

kubectl delete pod notes-api-7c9d8b6f5d-fprwl
Guess first: this Deployment keeps 3 pods. Once deleted, does pod fprwl come back to life?

No. What comes back is the count. The ReplicaSet (which the Deployment creates to keep the pod count) sees 2 pods where the goal is 3, and creates a new pod under a new name. Kubernetes doesn't care which pod, it cares that the count matches.

Meaning: The replacement pod goes through Pending (waiting to be placed on a server), ContainerCreating (the container is being prepared), Running 0/1 (running, not ready yet), then 1/1 once it's ready to take requests.

⚡ Readiness and liveness

Write:

readinessProbe:
  httpGet:
    path: /health
    port: 3000

Meaning: A probe is a check Kubernetes sends to the container on a schedule, here to /health on port 3000. A readiness probe decides when a pod gets requests, so an app that is still booting (starting up) gets none. A liveness probe restarts a container that hangs (stops answering). notes-api on one VPS doesn't need Kubernetes yet. Kubernetes is worth it with many servers, many services and many teams.

What you will learn