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.
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
Deploymentwithreplicas: 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.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.How does the Kubernetes API work inside?
An object is a document with
apiVersion,kind,metadata,specandstatus, 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 checksresourceVersionand answers409 Conflicton 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.Installing a cluster with kubeadm
On three Ubuntu 26.04 nodes we disable swap, enable
net.ipv4.ip_forward, install containerd withSystemdCgroup = trueand kubeadm, kubelet and kubectl 1.36. On the master,kubeadm init --config kubeadm-config.yamlissues certificates and writes kubeconfigs and static pod manifests in under a minute; then Calico goes in through the Tigera operator and the workers join withkubeadm join. The key decision is a separate API name,k8s-api.example.com, incontrolPlaneEndpoint: without it the cluster can never be made highly available.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
hellowith a multi-stage Dockerfile anddocker buildx buildfor amd64 and arm64 on a distroless base, with no shell and a non-root user, and--pushit to the private GitHub Container Registry. The nodes get a read-only token via a Secret of typekubernetes.io/dockerconfigjsonattached to the ServiceAccount throughimagePullSecrets, and manifests use version tags or digests, neverlatest.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 withrestartPolicy: Always) and the main containers, watches them through probes, and on deletion gives themterminationGracePeriodSecondsto shut down on SIGTERM.How do Deployment and ReplicaSet work?
A ReplicaSet makes sure there are exactly
replicaspods 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 apod-template-hashlabel, and the controller moves replicas from the old one to the new one withinmaxSurgeandmaxUnavailable, taking the next step only when the new pods have become available by the readiness probe andminReadySeconds. Old ReplicaSets with zero replicas remain as the history thatkubectl rollout undoworks from.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 fromvolumeClaimTemplates, 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.How do Job and CronJob work?
A Job creates pods with
restartPolicyNeverorOnFailureand counts successful completions:completionsis how many successes are needed,parallelismis how many pods run at once,backoffLimitis how many failures are tolerated beforeFailed. InIndexedmode each pod gets its own number inJOB_COMPLETION_INDEX. A CronJob creates such Jobs on acronschedule in thetimeZonetime zone,concurrencyPolicy: Forbidkeeps a second run from starting on top of the first, and the jobs must be idempotent: a Job may be created twice.How do requests, limits and QoS work?
requestsare what a container is guaranteed: the scheduler checks whether their sum fits into the node'sallocatable, and the CPU request becomes thecpu.weightshare.limitsare the ceiling: the CPU limit turns into acpu.maxquota beyond which the threads are frozen until the end of the period (throttling), the memory limit intomemory.maxbeyond which the kernel kills the container (OOMKilled). From requests and limits a pod gets a QoS class —Guaranteed,BurstableorBestEffort— which determinesoom_score_adjand the eviction order when memory runs short.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
kubernetesfinalizer once the controller has cleaned out its contents. Labels are key-value pairs for selection: controllers find their pods bymatchLabelsandmatchExpressionsselectors, andkubectl -lfilters objects on the API server side. Annotations hold data nobody selects by: the reason for a change, a commit hash, settings of external controllers.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
..datalink, while variables and files mounted viasubPathstay unchanged until the container restarts. base64 is not encryption: in etcd secrets lie in plain text until encryption at rest is enabled withEncryptionConfiguration.How does the scheduler work?
kube-scheduler takes a pod with an empty
spec.nodeName, sifts the nodes through filters (room byrequests, 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 whosenodeNameis already set is invisible to it. The choice is shaped by pod fields —nodeSelector, affinity, tolerations,topologySpreadConstraintsandpriorityClassName— whilecordon,drainand a PodDisruptionBudget let you free a node in a planned way.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 fake169.254.1.1that 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 throughnatOutgoing.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-ipsverdict map.How does DNS work in the cluster?
Names in the cluster are resolved by CoreDNS — the
corednsDeployment behind thekube-dnsService at10.96.0.10: itskubernetesplugin builds answers from a watch on Services and EndpointSlices, and theforwardplugin sends everything else to the node's DNS servers. A Service gets the name<service>.<namespace>.svc.cluster.localwith an A record for its ClusterIP, a headless Service gets the addresses of all ready pods, named ports get SRV records. kubelet writesnameserver 10.96.0.10, thesearchsuffixes andndots:5into each pod's/etc/resolv.conf, so an external name likeapi.github.comis first tried with every cluster suffix: on our lab that is four queries instead of one.Setting up a LoadBalancer without a cloud using MetalLB
Without a cloud nobody hands out addresses to LoadBalancer services, so we install MetalLB: its
controllertakes an address from anIPAddressPool(192.168.10.200–220for us) and writes it intostatus.loadBalancer.ingress, and thespeakeron 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/32route 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.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, aGatewaywith listeners and certificates owned by the administrator, and anHTTPRouteowned by the team, attached throughparentRefsandallowedRoutes.How does cert-manager issue certificates?
Through a chain of objects: an
IssuerorClusterIssuersays who signs, aCertificatesays which names and which Secret, and the controller creates aCertificateRequest, for ACME also anOrderand aChallenge, and after validation puts the certificate and key into a Secret of typekubernetes.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.How does NetworkPolicy work?
While a namespace has no policies, its pods are not isolated; as soon as a pod is selected by the
podSelectorof at least one NetworkPolicy, it accepts and sends only what is explicitly allowed, separately forIngressandEgress. 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.How do volumes and CSI work?
A pod refers to a
PersistentVolumeClaim, the controller binds it to a suitablePersistentVolume, and with dynamic provisioning the provisioner from theStorageClasscreates the volume and thepvc-<uid>PV itself — withWaitForFirstConsumeronly 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 intoCreateVolume,ControllerExpandVolumeandCreateSnapshot, kubelet callsNodeStageVolumeandNodePublishVolume, 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'sfsGroupif the driver'sfsGroupPolicyallows it.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
rpcbindandrpc.statd, turn offmanage-gids, without whichfsGroupdoes not work, and export/srv/nfs/k8sby name to the three nodes withrw,sync,secure,no_root_squash,mp, whileufwlets only them reach port 2049. csi-driver-nfs needsno_root_squash, but withsec=systhe 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 norsecurekeeps pods out. A Calico GlobalNetworkPolicy in a separate tier withdefaultAction: Passdoes that: pods may not reach the server, while kubelet mounts the volumes from the host network.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 setsubDirwith${pv.metadata.name}for uniqueness,reclaimPolicy: Retain,onDelete: archiveandmountOptionsthat 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'sfsGroupwithfsGroupChangePolicy: OnRootMismatch, givenno_root_squashandmanage-gids=non the server, andxprtsec=tlsencryption needstlshdon every node plus a Secret with options for deleting volumes.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 withprovisioner: smb.csi.k8s.iosets 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, so0777andnopermare anti-examples; the driver turns the pod'sfsGroupintogid. New options and a new password take effect only on a new mount: volumes are remounted one node at a time withcordon, not withrollout restart.What other storage is there for the cluster?
Local node disks (local-path-provisioner, the
localvolume, 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 throughnodeAffinity, and local-path does not even limit the size; S3 gives no POSIX semantics — no atomicrename, 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.How does Kustomize work?
Kustomize does not template text; it layers changes on top of ordinary valid manifests: the
basedirectory holds the shared objects, and theoverlayof each environment holds only the differences, such asnamespace,imagesand strategic merge or JSON 6902 patches. It is built intokubectl:kubectl kustomizeprints the result,kubectl apply -kapplies 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.How does Helm work?
Helm packages an application into a chart — a directory with
Chart.yaml,values.yamland Go text/template templates — renders them with parameters fromvalues.yaml,-fand--set, and sends the result to the API as a release. The release state lives in the cluster itself: one Secretsh.helm.release.v1.<release>.v<revision>per revision, with the chart, the values and the manifest, sohelm rollbackworks 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.What are CRDs and operators?
A CRD is an
apiextensions.k8s.ioobject 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, servewatch,kubectl getand 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 writesstatus. 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.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,RBACauthorizers 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, andcreate podsorlist secretseffectively give away every secret of the namespace.How to secure pods
A pod's boundaries are set by
securityContextfields: the process runs as non-root (runAsNonRoot), without capabilities (drop: [ALL]), without privilege escalation (allowPrivilegeEscalation: false), with theseccompProfile: RuntimeDefaultfilter, and an application gets noprivileged,hostNetworkorhostPath. So that nobody has to remember the fields, the namespace is labelled for Pod Security Admission:enforce=restrictedrejects a violating pod,warnandauditonly report it. Custom rules such as banning thelatesttag are written in CEL in aValidatingAdmissionPolicy.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 --previousshows why the container died last time, and an image without a shell is entered with an ephemeral container viakubectl debug, in arestrictednamespace with--profile=restricted. When the API no longer helps,crictlandjournalctl -u kubeleton the node itself remain.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.ioAPI forkubectl topand the HorizontalPodAutoscaler, while Prometheus itself scrapes/metricsfrom exporters and applications and keeps the history on disk. The HPA computesceil(replicas × current / target), and the percentages are taken fromrequests, not from the limit or a core. Prometheus with Grafana and Alertmanager is installed by the kube-prometheus-stack chart; targets are added with aServiceMonitorobject and alerts with aPrometheusRule.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 bycontainerLogMaxSize; 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 thetraceparentheader. 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.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>, andresourceVersionis 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 forfdatasyncof the WAL, so etcd needs a local SSD. The backup is a scheduledetcdctl snapshot save, encrypted and uploaded outside the cluster.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 planand runkubeadm upgrade apply, which replaces the static pods one at a time and renews the certificates for another year; then on every workerkubectl drain,kubeadm upgrade node, the new kubelet anduncordon. 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/pkiand a compatibility check of Calico and the other components.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:NoScheduletaint and a RuntimeClass.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
kernelspacemode and Felix describe through its API. Of the plugins, Flannel, Calico and Antrea work on Windows; Cilium does not. We choose Calico in VXLANAlwayswith BGP off andstrictAffinity: 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.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: HNSand a direct API address in thekubernetes-services-endpointConfigMap. On the Windows node the sig-windows-tools scripts install containerd and kubelet as services,kubeadm joinwith aJoinConfigurationputs theos=windows:NoScheduletaint andmaxPods: 60on the node right away, Calico and kube-proxy arrive as HostProcess pods, and thewindows-2025RuntimeClass sends Nano Server-based Windows pods to the node.Running workloads, storage and observability on Windows
hellois built forwindows/amd64onnanoserverwithout aRUNinstruction, anddocker buildxputs the Windows variant into a shared tag with anos.versionfield 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 aVirtualAllocfailure 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 viadrain, a restart and anuncordononce Calico has recreated the network.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
GMSACredentialSpecingmsaCredentialSpecName; a webhook fills in the spec's JSON and checks theusepermission 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.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,pruneandselfHeal, 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.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 loadwithout a registry. k3s is a single binary with the control plane in goroutines of thek3s serverprocess, 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.