Why Kubernetes

You state what should run; the cluster keeps it true

Your request: keep 3 copies of web runningNode ANode BNode CwebwebwebNode B has failedits copy of web is gone2 running: one shortwebnewa replacement starts here: 3 againYou say what should be running. Kubernetes keeps it true across many machines.One host is one point of failure, and Compose only starts things. Kubernetes joins many machinesinto a cluster and keeps watching it. When a machine dies, its work is started somewhere else,usually within minutes and without anyone being called.

A node fails. Its work is started elsewhere, with nobody called.

Why Kubernetes · Going deeper

Lab: make a cluster and try to break it

TypeLook forkind create clusterkubectl get nodeskubectl create deploy web --image=nginx --replicas=3kubectl get podskubectl delete pod -l app=web --wait=falsekubectl get podsa one-node cluster, ready in about a minuteone node with the status Readydeployment.apps/web createdthree pods named web-..., all Runningthree pods deletedthree new pods, a few seconds oldLab: make a cluster, then try to break what it runs.You need Docker, kubectl and kind ("minikube start" also works). Keep the cluster for the later labs.You deleted every copy, and Kubernetes replaced them all. "kind delete cluster" removes the cluster.

Create a cluster, run three pods, delete them, watch them return.

Desired state

Watch, compare, act: the loop that runs everything

TimeYou asked forActually runningWhat the controller does10:00nothing: they match10:05a node has failed: start 110:11nothing10:30you changed 3 to 5: start 210:31nothingWatch, compare, act, and repeat for ever. That loop is how Kubernetes works.A controller is a small program that compares the state you asked for with the state that existsand makes one change to close the gap. It does not care why they differ. A failed machine and anedited file are handled in exactly the same way.

A controller compares wanted with running and closes the gap.

Inside a cluster

A control plane decides; worker nodes run the containers

Control planeA worker node, one of manykubectlyouAPI serverthe only dooretcdthe recordcontrollersclose the gapsschedulerpicks nodeskubeletruns the podscontainerdthe runtimepodsyour containerskube-proxynetwork rulesA control plane decides. Worker nodes run the containers.Every part talks only to the API server, and only the API server reads and writes etcd, thedatabase that holds the state of the whole cluster. Lose a worker and its pods move elsewhere.Lose etcd without a backup and the cluster has forgotten everything.

API server, etcd, controllers, scheduler; and a kubelet on every node.

Where the parts run · Going deeper

Static pods, services and ports: where to find each part when it fails

PartHow it runs on a kubeadm clusterPortWhen it misbehaveskube-apiserverstatic pod on each control plane node6443crictl ps -a, then crictl logs IDetcdstatic pod2379, 2380the same: kubectl may not answerkube-schedulerstatic pod10259kubectl logs -n kube-system PODkube-controller-managerstatic pod10257kubectl logs -n kube-system PODkubeletsystemd service on every node10250systemctl status kubelet; journalctl -u kubeletcontainerdsystemd service on every nodea socketsystemctl status containerdkube-proxyDaemonSet: a pod on every node10256kubectl logs -n kube-system ds/kube-proxyCoreDNSDeployment in kube-system53kubectl logs -n kube-system deploy/corednsThe control plane runs as static pods: files in /etc/kubernetes/manifests that the kubelet starts by itself.That is how a cluster starts before there is an API server to ask. Change or remove a file there and the kubelet restarts orstops that part within seconds. So when kubectl gets no answer, go to the node: is the kubelet running, and what do itsjournal and crictl say? Certificates are in /etc/kubernetes/pki; the administrator's kubeconfig is /etc/kubernetes/admin.conf.

The control plane is static pods. The kubelet is a systemd service.

One request

One kubectl apply, followed through the cluster

Control planeA worker node, one of manykubectlyouAPI serverthe only dooretcdthe recordcontrollersclose the gapsschedulerpicks nodeskubeletruns the podscontainerdthe runtimepodsyour containerskube-proxynetwork rules11kubectl sends your file to the API server22the API server checks it and saves it in etcd33a controller sees 3 wanted and 0 existing: it creates 3 pods44the scheduler gives each new pod a node55the kubelet on that node sees its pod and starts it66the kubelet reports back: RunningNothing is pushed to the nodes. Each part watches the API server and does its own job.kubectl apply returns after step 2. Everything else happens because controllers notice the gap.

Six steps, and nothing is pushed: every part watches the API server.

Working with kubectl · Going deeper

Know your context, and let kubectl write the YAML

A context is a cluster, a user and a namespace. --dry-run=client -o yaml writes the draft.

Know where you are pointing

kubectl reads a kubeconfig file, by default ~/.kube/config. It lists clusters (an address and a certificate authority), users (a client certificate or a token) and contexts. A context is one cluster, one user and a default namespace.

  • kubectl config get-contexts every context; the current one is starred.
  • kubectl config use-context prod switch to another cluster.
  • kubectl config set-context --current --namespace=shop make shop the default namespace.
  • kubectl get pods -A every namespace at once.

Let kubectl write the first draft

Add --dry-run=client -o yaml to a create command and it prints the manifest and creates nothing. Save it, edit it, apply it.

  • kubectl create deployment web --image=nginx:1.27 --replicas=3 --dry-run=client -o yaml > web.yaml a complete Deployment.
  • kubectl run tmp --image=busybox:1.36 --dry-run=client -o yaml -- sleep 3600 a Pod, with its command.
  • kubectl expose deployment web --port=80 --dry-run=client -o yaml a Service whose selector matches (the Deployment must exist).
  • kubectl create cronjob report --image=acme/report:1.0 --schedule="0 2 * * *" --dry-run=client -o yaml a CronJob.

Check before you change

  • kubectl diff -f web.yaml what an apply would change in the cluster.
  • kubectl apply -f web.yaml --dry-run=server the API server validates it fully and saves nothing.
  • kubectl explain deployment.spec.strategy --recursive the field names, without leaving the terminal.
Get this wrong The right command sent to the wrong cluster is the classic outage. Read the current context before anything that deletes, and in a hands-on exam switch to the cluster or host each task names before you type anything else.

Manifests

Every object has the same shape: you write the spec

apiVersion: apps/v1kind: Deploymentmetadata: name: webspec: replicas: 3 selector: matchLabels: { app: web } template: metadata: labels: { app: web } spec: containers: - name: web image: nginx:1.27which API the kind belongs tothe kind of objectits namespec: the state you wanthow many copiesthe pod to copy, described in the next lessonthe image to runEvery object has the same four parts: apiVersion, kind, metadata and spec.You write the spec. The cluster adds a fifth part, status, and works to make the two agree.

apiVersion, kind, metadata, spec. The cluster writes status.

Manifests · Going deeper · 1 of 2

Lab: apply a manifest and read the result

TypeLook forkubectl apply -f web.yamlkubectl get deployment webkubectl apply -f web.yamlkubectl scale deployment web --replicas=5kubectl get deployment web -o yamlkubectl explain deployment.spec.replicasdeployment.apps/web created (or configured)READY 3/3deployment.apps/web unchangeddeployment.apps/web scaledyour spec, and a status the cluster wrotethe documentation for that one fieldLab: apply a manifest, then read what the cluster wrote back.Save the manifest from the previous page as web.yaml. Applying a file twice changes nothing."kubectl describe deployment web" shows the same object as a readable summary with recent events.

Apply it twice, scale it, then read the status the cluster wrote.

API groups · Going deeper · 2 of 2

The apiVersion depends on the kind: eighteen to know

kindapiVersionshortPodv1poServicev1svcConfigMapv1cmSecretv1PersistentVolumeClaimv1pvcServiceAccountv1saDeploymentapps/v1deployStatefulSetapps/v1stsDaemonSetapps/v1dskindapiVersionshortJobbatch/v1CronJobbatch/v1cjIngressnetworking.k8s.io/v1ingNetworkPolicynetworking.k8s.io/v1netpolHorizontalPodAutoscalerautoscaling/v2hpaRole, RoleBindingrbac.authorization.k8s.io/v1Nodev1noPersistentVolumev1pvStorageClassstorage.k8s.io/v1scThe oldest kinds are plain v1. Everything newer lives in a named group, and the manifest must say which.A wrong apiVersion is refused with: no matches for kind "Deployment" in version "v1". kubectl api-resources prints this tablefor your own cluster, and kubectl explain cronjob.spec lists the fields of any kind. The short names save typing: kubectl getdeploy,svc,cm. Kinds in purple belong to no namespace; nor do Namespace, ClusterRole and ClusterRoleBinding.

Pods and Services are v1. Deployments are apps/v1. Jobs are batch/v1.

Lesson complete

You finished “Why Kubernetes, and what is in a cluster”

Nicely done.

Open in a new tab