Series42 partsВиталий Лещенко

Kubernetes for beginners

Kubernetes for beginners

A series for those who already know Linux and networking and want to understand how Kubernetes works: what happens between kubectl apply and a running container, who decides which node it runs on and how, where a pod gets its address and how a packet reaches it from outside, where the data lives and what happens when a node disappears.

The series has three principles.

First: for every component, not only why it is needed but how it works. Which objects appear in the API, which controller reacts to them, which rules appear on the node, what lies in etcd. That is why almost every part has kubectl, crictl and nft output and a walk-through of what it says.

Second: your own cluster, not a cloud one. The lab cluster is installed with kubeadm on three Ubuntu Server virtual machines: this way you can see the control plane, the certificates and etcd that the cloud hides. Every object is described by a YAML manifest and applied with kubectl; Kustomize and Helm come only once the manifests are clear.

Third: best practices, not "it works anyway". Where a default setting or a popular recipe from the internet is better not repeated, there is an explanation of why, and how to do it right.

The order: first the foundation (architecture, the API, installing the cluster, images), then workloads, configuration and scheduling, networking bottom-up — from a pod's address to Ingress and certificates, storage with separate parts on NFS and SMB, packaging, security, observability, cluster maintenance, a hybrid cluster with Windows workers and finally GitOps. Protocols covered in the Networking for beginners series are not explained again: where they come up, there is a link and the gist in two sentences. A highly available control plane and publishing services over BGP are in the Highly available Kubernetes on BGP series.

  1. Part 1

    Why is Kubernetes needed?

    Kubernetes runs containers on a group of machines and keeps exactly what is described running. Instead of ordering "run a container on node 1", the administrator stores the desired state in the cluster — say, a Deployment with replicas: 3 — and controllers in a reconciliation loop compare it with reality and remove the difference: they recreate crashed pods, move them off a lost node and update without downtime. It does not build images, store application data or implement the network itself; CI, external storage and a CNI plugin do that.

  2. Part 2

    How is a Kubernetes cluster built?

    A cluster is a control plane plus worker nodes. The master runs kube-apiserver, etcd, kube-scheduler and kube-controller-manager; every node runs kubelet, containerd, kube-proxy and Calico. The main rule: only kube-apiserver talks to etcd, and all the other components are its clients: they subscribe to changes through watch on port 6443, do their step and write the result back through the API, never contacting each other directly. kubelet starts the control plane itself as static pods from the manifests in /etc/kubernetes/manifests.

  3. Part 3

    How does the Kubernetes API work inside?

    An object is a document with apiVersion, kind, metadata, spec and status, stored by kube-apiserver in etcd and served at paths like /apis/apps/v1/namespaces/default/deployments/web. A request passes authentication, authorization, admission and schema validation; a write checks resourceVersion and answers 409 Conflict on a mismatch so clients do not overwrite each other's changes. Controllers watch for changes instead of polling, deletion goes through finalizers, and server-side apply tracks who owns which field.

  4. Part 4

    Installing a cluster with kubeadm

    On three Ubuntu 26.04 nodes we disable swap, enable net.ipv4.ip_forward, install containerd with SystemdCgroup = true and kubeadm, kubelet and kubectl 1.36. On the master, kubeadm init --config kubeadm-config.yaml issues certificates and writes kubeconfigs and static pod manifests in under a minute; then Calico goes in through the Tigera operator and the workers join with kubeadm join. The key decision is a separate API name, k8s-api.example.com, in controlPlaneEndpoint: without it the cluster can never be made highly available.

  5. Part 5

    How to build an image and where to keep it

    An image is a tree of JSON documents and layers linked by digest, so a tag can be overwritten and a digest cannot. We build the Go app hello with a multi-stage Dockerfile and docker buildx build for amd64 and arm64 on a distroless base, with no shell and a non-root user, and --push it to the private GitHub Container Registry. The nodes get a read-only token via a Secret of type kubernetes.io/dockerconfigjson attached to the ServiceAccount through imagePullSecrets, and manifests use version tags or digests, never latest.

  6. Part 6

    What is a Pod?

    A Pod is the smallest unit Kubernetes schedules and runs: not a single container but a group of containers with a shared IP address, shared volumes and a shared fate on one node. The shared namespaces are held by the service container pause, so restarting any container does not change the pod's address. The kubelet runs init containers one by one, then sidecars (init containers with restartPolicy: Always) and the main containers, watches them through probes, and on deletion gives them terminationGracePeriodSeconds to shut down on SIGTERM.

  7. Part 7

    How do Deployment and ReplicaSet work?

    A ReplicaSet makes sure there are exactly replicas pods made from its template: it creates the missing ones and deletes the extra ones. A Deployment is responsible for versions: every change of the pod template is a new ReplicaSet with a pod-template-hash label, and the controller moves replicas from the old one to the new one within maxSurge and maxUnavailable, taking the next step only when the new pods have become available by the readiness probe and minReadySeconds. Old ReplicaSets with zero replicas remain as the history that kubectl rollout undo works from.

  8. Part 8

    How do StatefulSet and DaemonSet work?

    A StatefulSet gives each pod a number: the name web-1, a DNS name through a headless Service and its own volume claim from volumeClaimTemplates, which returns to the same number after the pod is recreated; pods are created and updated one at a time, and there is never more than one pod with a given name. A DaemonSet keeps exactly one pod on every suitable node: it binds the pod to the node through node affinity and adds tolerations for the node's taints by itself. Neither of them does replication or leader election — that is the job of the application or an operator.

  9. Part 9

    How do Job and CronJob work?

    A Job creates pods with restartPolicy Never or OnFailure and counts successful completions: completions is how many successes are needed, parallelism is how many pods run at once, backoffLimit is how many failures are tolerated before Failed. In Indexed mode each pod gets its own number in JOB_COMPLETION_INDEX. A CronJob creates such Jobs on a cron schedule in the timeZone time zone, concurrencyPolicy: Forbid keeps a second run from starting on top of the first, and the jobs must be idempotent: a Job may be created twice.

  10. Part 10

    How do requests, limits and QoS work?

    requests are what a container is guaranteed: the scheduler checks whether their sum fits into the node's allocatable, and the CPU request becomes the cpu.weight share. limits are the ceiling: the CPU limit turns into a cpu.max quota beyond which the threads are frozen until the end of the period (throttling), the memory limit into memory.max beyond which the kernel kills the container (OOMKilled). From requests and limits a pod gets a QoS class — Guaranteed, Burstable or BestEffort — which determines oom_score_adj and the eviction order when memory runs short.

  11. Part 11

    Why are namespaces, labels and annotations needed?

    A namespace is a scope for unique names and a boundary for the API: RBAC permissions, quotas, LimitRange and network policies apply within it, but on its own it isolates neither the network, nor nodes, nor DNS, and it is deleted through the kubernetes finalizer once the controller has cleaned out its contents. Labels are key-value pairs for selection: controllers find their pods by matchLabels and matchExpressions selectors, and kubectl -l filters objects on the API server side. Annotations hold data nobody selects by: the reason for a change, a commit hash, settings of external controllers.

  12. Part 12

    How do ConfigMap and Secret work?

    A ConfigMap holds settings as key-value pairs; a Secret is built the same way, but its values are stored in base64, the kubelet keeps its volumes in tmpfs, and reading it is restricted by RBAC. Both reach a pod as environment variables or volume files: the kubelet updates files when the object changes by atomically switching the ..data link, while variables and files mounted via subPath stay unchanged until the container restarts. base64 is not encryption: in etcd secrets lie in plain text until encryption at rest is enabled with EncryptionConfiguration.

  13. Part 13

    How does the scheduler work?

    kube-scheduler takes a pod with an empty spec.nodeName, sifts the nodes through filters (room by requests, taints, affinity, topology spread), scores the remaining ones and records its choice as a single Binding object. The decision is made once: it does not move running pods, and a pod whose nodeName is already set is invisible to it. The choice is shaped by pod fields — nodeSelector, affinity, tolerations, topologySpreadConstraints and priorityClassName — while cordon, drain and a PodDisruptionBudget let you free a node in a planned way.

  14. Part 14

    How is the Kubernetes network built?

    Kubernetes does not build the network itself but requires it from a CNI plugin: every pod has its own IP, any pod reaches any other without NAT, and a node reaches its pods. On the lab this is done by Calico: a pod is connected to the node by a cali… veth pair, its address is a /32, its gateway is the fake 169.254.1.1 that the node answers for via proxy ARP, and from there the node's kernel routes the packet. Between nodes of one subnet packets travel without encapsulation along routes to /26 blocks that Felix writes on every node from the IPAM data; VXLAN is needed only between subnets, and pods reach the outside through natOutgoing.

  15. Part 15

    How do Service and kube-proxy work?

    A Service gives a group of pods a stable virtual ClusterIP address that exists on no interface: it lives only as a key in the netfilter rules kube-proxy writes on every node. A packet to the ClusterIP gets DNAT to the address of one of the ready pods before routing, chosen at random once per connection, and conntrack returns the reply on behalf of the service. The list of ready pods is kept by the EndpointSlice controller from readiness probes; in nftables mode the service is found with a single lookup in the service-ips verdict map.

  16. Part 16

    How does DNS work in the cluster?

    Names in the cluster are resolved by CoreDNS — the coredns Deployment behind the kube-dns Service at 10.96.0.10: its kubernetes plugin builds answers from a watch on Services and EndpointSlices, and the forward plugin sends everything else to the node's DNS servers. A Service gets the name <service>.<namespace>.svc.cluster.local with an A record for its ClusterIP, a headless Service gets the addresses of all ready pods, named ports get SRV records. kubelet writes nameserver 10.96.0.10, the search suffixes and ndots:5 into each pod's /etc/resolv.conf, so an external name like api.github.com is first tried with every cluster suffix: on our lab that is four queries instead of one.

  17. Part 17

    Setting up a LoadBalancer without a cloud using MetalLB

    Without a cloud nobody hands out addresses to LoadBalancer services, so we install MetalLB: its controller takes an address from an IPAddressPool (192.168.10.200–220 for us) and writes it into status.loadBalancer.ingress, and the speaker on the nodes announces it to the network. In L2 mode one leader node, chosen by hash among the live speakers, answers for the address: it replies to ARP with its interface's MAC address, and when the leader changes, the new leader sends gratuitous ARP — on the lab within a fraction of a second after a speaker left. In BGP mode every eligible node advertises a /32 route to the router, and the router spreads traffic over the nodes with ECMP — checked on the lab against a router running FRR. MetalLB does not proxy traffic: the packet hits the kube-proxy rules and is DNATed to a pod.

  18. Part 18

    How do Ingress and Gateway API work?

    Both APIs describe rules for a reverse proxy: send a request with this site name and path to this Service. The object itself does nothing — it is read by an ingress controller, here Traefik, which takes pod addresses from EndpointSlice and sends traffic to them directly, bypassing the ClusterIP. Ingress is one object for everything, with the TLS secret in the application's namespace and controller annotations; Gateway API splits the roles: GatewayClass, a Gateway with listeners and certificates owned by the administrator, and an HTTPRoute owned by the team, attached through parentRefs and allowedRoutes.

  19. Part 19

    How does cert-manager issue certificates?

    Through a chain of objects: an Issuer or ClusterIssuer says who signs, a Certificate says which names and which Secret, and the controller creates a CertificateRequest, for ACME also an Order and a Challenge, and after validation puts the certificate and key into a Secret of type kubernetes.io/tls. Control of a name is proven with HTTP-01 — a solver pod and a route on port 80 reachable from the internet — or with DNS-01 through a TXT record at the DNS provider; only DNS-01 gives a wildcard. Renewal starts at two thirds of the lifetime, and Traefik picks up the new Secret on the fly.

  20. Part 20

    How does NetworkPolicy work?

    While a namespace has no policies, its pods are not isolated; as soon as a pod is selected by the podSelector of at least one NetworkPolicy, it accepts and sends only what is explicitly allowed, separately for Ingress and Egress. Allows add up, the standard API has no deny rules, and Calico compares addresses and ports after DNAT — so you write the container port, not the service port. The network plugin enforces the policies: Felix in Calico turns them into nftables chains and address sets on every pod's interface, and for cluster-wide restrictions there are GlobalNetworkPolicy and tiers.

  21. Part 21

    How do volumes and CSI work?

    A pod refers to a PersistentVolumeClaim, the controller binds it to a suitable PersistentVolume, and with dynamic provisioning the provisioner from the StorageClass creates the volume and the pvc-<uid> PV itself — with WaitForFirstConsumer only after the scheduler has picked a node. A CSI driver is a program with the gRPC services Identity, Controller and Node: sidecar containers turn API events into CreateVolume, ControllerExpandVolume and CreateSnapshot, kubelet calls NodeStageVolume and NodePublishVolume, and the volume's directory under /var/lib/kubelet/pods/ is bind-mounted into the container. Permissions on the volume are set by the pod's fsGroup if the driver's fsGroupPolicy allows it.

  22. Part 22

    Setting up an NFS server for the cluster

    On Ubuntu Server with a separate XFS disk we keep only NFSv4.1 and 4.2, mask rpcbind and rpc.statd, turn off manage-gids, without which fsGroup does not work, and export /srv/nfs/k8s by name to the three nodes with rw,sync,secure,no_root_squash,mp, while ufw lets only them reach port 2049. csi-driver-nfs needs no_root_squash, but with sec=sys the server trusts the credential in the request, pods leave through NAT with the node's address, and containerd 2 lets them use ports below 1024 — so neither the address nor secure keeps pods out. A Calico GlobalNetworkPolicy in a separate tier with defaultAction: Pass does that: pods may not reach the server, while kubelet mounts the volumes from the host network.

  23. Part 23

    Connecting NFS with csi-driver-nfs

    We install csi-driver-nfs v4.13.6 from the project's manifests: the controller runs in hostNetwork, mounts the export with the class options for every PVC and creates a subdirectory in it as root, and the node plugin, on kubelet's command, mounts that subdirectory into the pod's directory without an attach step. In the StorageClass we set subDir with ${pv.metadata.name} for uniqueness, reclaimPolicy: Retain, onDelete: archive and mountOptions that are identical for the whole server (nfsvers=4.2, hard, nconnect=4): a node has a single NFS client for all volumes, and the connection options are set by the first mount. Permissions come from the pod's fsGroup with fsGroupChangePolicy: OnRootMismatch, given no_root_squash and manage-gids=n on the server, and xprtsec=tls encryption needs tlshd on every node plus a Secret with options for deleting volumes.

  24. Part 24

    Connecting SMB with csi-driver-smb

    The driver is installed from release manifests into kube-system, the service account's password goes into a Secret in a separate namespace, and a StorageClass with provisioner: smb.csi.k8s.io sets the share, that Secret and the mount options — vers=3, seal, nobrl, nolease, hard. The cifs kernel module mounts the share once per node and PV and talks to the server over one session as one account, emulating file owners and modes from the options, so 0777 and noperm are anti-examples; the driver turns the pod's fsGroup into gid. New options and a new password take effect only on a new mount: volumes are remounted one node at a time with cordon, not with rollout restart.

  25. Part 25

    What other storage is there for the cluster?

    Local node disks (local-path-provisioner, the local volume, TopoLVM), S3 buckets mounted through FUSE by a driver such as k8s-csi-s3, and the distributed systems Longhorn, Ceph and OpenEBS that replicate between nodes. A local volume is the fastest but ties the pod to its node through nodeAffinity, and local-path does not even limit the size; S3 gives no POSIX semantics — no atomic rename, no locks between nodes, and another node sees new files with a delay; distributed storage survives node loss at the cost of network and operational complexity. Databases are kept on local disks with replication by the database itself under an operator, backups go to S3.

  26. Part 26

    How does Kustomize work?

    Kustomize does not template text; it layers changes on top of ordinary valid manifests: the base directory holds the shared objects, and the overlay of each environment holds only the differences, such as namespace, images and strategic merge or JSON 6902 patches. It is built into kubectl: kubectl kustomize prints the result, kubectl apply -k applies it, and the cluster knows nothing about Kustomize. The ConfigMap and Secret generators append a content hash to the name and fix the references to it, so a configuration change triggers a rolling update by itself.

  27. Part 27

    How does Helm work?

    Helm packages an application into a chart — a directory with Chart.yaml, values.yaml and Go text/template templates — renders them with parameters from values.yaml, -f and --set, and sends the result to the API as a release. The release state lives in the cluster itself: one Secret sh.helm.release.v1.<release>.v<revision> per revision, with the chart, the values and the manifest, so helm rollback works without the original chart. Helm 4 applies new releases with server-side apply, waits for readiness via kstatus and rolls back a failure with --rollback-on-failure.

  28. Part 28

    What are CRDs and operators?

    A CRD is an apiextensions.k8s.io object that makes kube-apiserver serve a new resource type without a single line of code: store it in etcd, validate it against a schema and CEL rules, serve watch, kubectl get and RBAC. Behaviour is added by a controller: an informer caches objects, a queue collapses events into keys, and Reconcile each time brings the world to the desired state again and writes status. An operator is such a controller with the knowledge of an administrator of a specific system: CloudNativePG does PostgreSQL failover, updates and backups by itself.

  29. Part 29

    How do authentication and RBAC work?

    Kubernetes has no "user" object: kube-apiserver takes the name and groups from the credential presented — an X.509 client certificate (CN and O), a ServiceAccount JWT or an OIDC ID token from an external provider. Then the Node,RBAC authorizers decide whether the verb on the resource is allowed: permissions come only from the allow rules in Role and ClusterRole granted through RoleBinding and ClusterRoleBinding, there are no denies. People get OIDC, a certificate cannot be revoked before it expires, and create pods or list secrets effectively give away every secret of the namespace.

  30. Part 30

    How to secure pods

    A pod's boundaries are set by securityContext fields: the process runs as non-root (runAsNonRoot), without capabilities (drop: [ALL]), without privilege escalation (allowPrivilegeEscalation: false), with the seccompProfile: RuntimeDefault filter, and an application gets no privileged, hostNetwork or hostPath. So that nobody has to remember the fields, the namespace is labelled for Pod Security Admission: enforce=restricted rejects a violating pod, warn and audit only report it. Custom rules such as banning the latest tag are written in CEL in a ValidatingAdmissionPolicy.

  31. Part 31

    How to troubleshoot a cluster

    Top down — from the object a person works with to the node: Deployment, events, pod, container, node — and at every level one question: did things get as far as the next link. Events (kubectl events --for) name the cause in plain words but live only an hour; kubectl logs --previous shows why the container died last time, and an image without a shell is entered with an ephemeral container via kubectl debug, in a restricted namespace with --profile=restricted. When the API no longer helps, crictl and journalctl -u kubelet on the node itself remain.

  32. Part 32

    How do metrics and autoscaling work?

    A cluster has two independent pipelines: every 15 seconds metrics-server takes pod CPU and memory from the kubelet and serves them through the metrics.k8s.io API for kubectl top and the HorizontalPodAutoscaler, while Prometheus itself scrapes /metrics from exporters and applications and keeps the history on disk. The HPA computes ceil(replicas × current / target), and the percentages are taken from requests, not from the limit or a core. Prometheus with Grafana and Alertmanager is installed by the kube-prometheus-stack chart; targets are added with a ServiceMonitor object and alerts with a PrometheusRule.

  33. Part 33

    How to collect logs and traces

    A container writes to stdout and stderr, containerd puts the lines into /var/log/pods/ on the node, and the kubelet rotates the files by containerLogMaxSize; the Grafana Alloy agent in a DaemonSet reads them, adds pod labels and sends them to Loki, which indexes only the labels and keeps chunks in S3. An application sends traces over OTLP to the OpenTelemetry Collector, and the collector sends them to Tempo; services are linked by the traceparent header. In Grafana the three sources are stitched together by shared labels and the trace id: from an exemplar on a graph to a trace, from a log line to a trace and back.

  34. Part 34

    How does etcd work?

    etcd is a key-value store with version history: kube-apiserver puts every object under a key of the form /registry/<resource>/<namespace>/<name>, and resourceVersion is an etcd revision. A write counts as done once a majority of members has confirmed it through the Raft protocol, which is why the number of members is odd, and losing quorum stops the API. Every write waits for fdatasync of the WAL, so etcd needs a local SSD. The backup is a scheduled etcdctl snapshot save, encrypted and uploaded outside the cluster.

  35. Part 35

    Upgrading the cluster

    Control plane first, then the nodes one by one: on the master you switch the package repository to the new minor version, install kubeadm, review kubeadm upgrade plan and run kubeadm upgrade apply, which replaces the static pods one at a time and renews the certificates for another year; then on every worker kubectl drain, kubeadm upgrade node, the new kubelet and uncordon. Minor versions cannot be skipped, and the kubelet must not be newer than the apiserver. Before you start — an etcd snapshot, a copy of /etc/kubernetes/pki and a compatibility check of Calico and the other components.

  36. Part 36

    How do Windows nodes work in a cluster?

    From the API's point of view a Windows node is just a node: its kubelet connects to kube-apiserver, renews its Lease and receives pods, and the scheduler and controllers work with it unchanged. The differences are below the API: kubelet and containerd run as Windows services, a container is created by the HCS service as a server silo built on a job object instead of namespaces and cgroups, and system components that need access to the node itself run in HostProcess containers — Windows has no privileged ones. Kubernetes supports only process isolation, so the OS build in the image must match the host's build, and pods are steered to nodes with the os=windows:NoSchedule taint and a RuntimeClass.

  37. Part 37

    How does Windows node networking work, and which CNI should you choose?

    The network of a Windows node is built by the HNS service and enforced by VFP, an extension of the Hyper-V switch: instead of a veth a pod has a vNIC in a network compartment, and instead of routes and nftables there are HNS policies that the CNI plugin, kube-proxy in kernelspace mode and Felix describe through its API. Of the plugins, Flannel, Calico and Antrea work on Windows; Cilium does not. We choose Calico in VXLAN Always with BGP off and strictAffinity: CrossSubnet does not work on Windows, and the lab cluster with BGP would not accept such a node — so a separate test cluster is built for it.

  38. Part 38

    Building a hybrid cluster with kubeadm

    The test cluster is built with kubeadm from a Linux master, two Linux workers and a Windows Server 2025 worker. Calico 3.33 is installed in VXLAN without BGP from the start, with strictAffinity, windowsDataplane: HNS and a direct API address in the kubernetes-services-endpoint ConfigMap. On the Windows node the sig-windows-tools scripts install containerd and kubelet as services, kubeadm join with a JoinConfiguration puts the os=windows:NoSchedule taint and maxPods: 60 on the node right away, Calico and kube-proxy arrive as HostProcess pods, and the windows-2025 RuntimeClass sends Nano Server-based Windows pods to the node.

  39. Part 39

    Running workloads, storage and observability on Windows

    hello is built for windows/amd64 on nanoserver without a RUN instruction, and docker buildx puts the Windows variant into a shared tag with an os.version field that containerd uses to pick the manifest for its build. Windows has no cgroups and no OOM killer: limits become properties of a job object, requests never reach the kernel, and a process over its memory limit gets a VirtualAlloc failure and crashes on its own, so every Windows pod gets limits. Volumes come from csi-driver-smb, logs are collected by Alloy in a HostProcess pod into the test cluster's Loki, metrics by windows-exporter, and the node is updated monthly via drain, a restart and an uncordon once Calico has recreated the network.

  40. Part 40

    How do Windows pods join Active Directory with gMSA?

    A pod gets a domain identity through a gMSA, an account whose password Active Directory itself computes, rotates and hands out only to permitted hosts. The manifest names only the GMSACredentialSpec in gmsaCredentialSpecName; a webhook fills in the spec's JSON and checks the use permission of the pod's ServiceAccount, and on the node CCG fetches the gMSA password from the domain controller and passes it to the container. For this the node is joined to the domain and added to a group allowed to read the password, and the application must run as Network Service or Local System.

  41. Part 41

    How to set up GitOps with Argo CD

    The source of truth about the cluster becomes a Git repository, and the changes are fetched by Argo CD with a read-only deploy key: the controller renders the manifests through Kustomize or Helm, compares them with the live objects and reconciles the difference by itself. An application is described by an Application with syncPolicy.automated, prune and selfHeal, and a manual edit is rolled back within seconds; the order of applying is set by waves and hooks, and the Applications themselves are generated by App of Apps and ApplicationSet. An AppProject restricts where delivery may come from and where it may go, and secrets are not put into Git.

  42. Part 42

    How to run a cluster on a laptop: kind, k3s and minikube

    kind makes each node a Docker or Podman container with systemd and kubelet inside and installs Kubernetes with the same kubeadm, and a local image gets into the cluster through kind load without a registry. k3s is a single binary with the control plane in goroutines of the k3s server process, state in SQLite through kine and built-in Flannel, Traefik and ServiceLB. minikube brings up a node as a VM or a container depending on the driver and enables components through addons. The API is the same everywhere, but what lies below it differs: LoadBalancer, volumes and the network do not behave the way they do on a real cluster.