Bookmarks
ReferenceDevOps & cloudVerified

Kubernetes

Kubernetes (K8s) — a platform for orchestrating containers in a cluster. In this reference: kubectl, Pod, Deployment, Service, Ingress, ConfigMap, volumes, Helm and RBAC.

checked 1 Nov · next check 8 Nov · 59 min read

Sections
14
Reading
59 min
Current version
1.37.2
Written from
kubernetes.io/docs

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Kubernetes is and how it works

Kubernetes (K8s) is an open source platform for running containerised applications on a cluster of machines. You describe the desired state: which images to run, in how many replicas and how to expose them to the network. Kubernetes brings the cluster to that description and keeps it there.

Kubernetes is what you need when an application runs on several servers and must not sit idle. It restarts containers that have crashed, balances traffic between replicas, rolls out new versions at a controlled pace and rolls them back, and scales the application with CPU load. Kubernetes does not build images from source code and provides no ready-made databases, queues or caches: these run in the cluster like any other application.

What a cluster is made of

A cluster is the control plane and the worker nodes that run Pods — groups of the application’s containers. The control plane makes the decisions for the whole cluster. Its entry point is kube-apiserver: it serves the Kubernetes HTTP API that kubectl talks to. etcd stores all cluster data, kube-scheduler picks a node for each new Pod, and kube-controller-manager runs the controllers. In the cloud a cloud-controller-manager is added on top: it links the cluster to the cloud provider’s API, for example by creating load balancers.

On every node runs kubelet — an agent that keeps the containers of a Pod up and healthy. The containers themselves are run by the container runtime: containerd, CRI-O or another CRI implementation. kube-proxy sets up the node’s network rules for Services; with some networking plugins it is not needed.

In small and learning clusters the control plane and Pods may run on the same nodes.

Desired state and manifests

A Kubernetes object is a record of intent. In a manifest you set spec — the desired state — and Kubernetes fills in status — the actual one. Controllers keep narrowing the gap between the two: if a Deployment’s spec asks for three replicas and only two are running, the controller will start the third.

yamlweb.yaml
# API version and kind of the objectapiVersion: apps/v1kind: Deployment# name and metadatametadata:  name: web# desired statespec:  replicas: 3  selector:    matchLabels:      app: web  template:    metadata:      labels:        app: web    spec:      containers:      - name: web        image: nginx:1.30
bashon your machine
kubectl apply -f web.yaml# the full spec and status of the objectkubectl get deployment web -o yaml

Every manifest requires apiVersion, kind and metadata, and almost always spec. Manifests are written in YAML, and kubectl converts them to JSON for the API. By default, kubectl validates fields on the server in strict mode: a typo in a field name returns an error instead of disappearing silently.

How Kubernetes differs from Docker Compose

FeatureDocker ComposeKubernetes
Where it runsa single host with Dockera cluster: control plane and worker nodes
How it is describedone compose.yaml file: services, networks, volumesAPI objects in YAML manifests
Networkingservices are connected through Compose networksDNS names and traffic balancing between Pods
Updatescontainers of unchanged services are reusedrollout at a controlled pace, with rollback
What fordevelopment, test environments in CI, production on a single hostseveral nodes, self-healing, autoscaling

Choose Compose if the application fits on a single server, or you need an environment for development and testing. Choose Kubernetes when the application must run on several nodes, survive failures and update without downtime.

You set up a learning cluster on your own machine — see the section “Installation and first run”. Production clusters are deployed with kubeadm, kops or Kubespray, or you use managed Kubernetes from a cloud provider: the provider then runs the control plane for you.

What to know in advance

  • Containers and images: tags, registries, builds — the Docker reference, sections “Images and registries” and “Dockerfile instructions”.
  • YAML: indentation with spaces, dictionaries and lists — every manifest is written in it.
  • Networking: IP addresses, ports and DNS — the TCP/IP and DNS reference.
  • The Linux command line and permissions — the Linux reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday kubectl commands. The examples use the app web in the namespace shop — replace the names with your own. Flags and pitfalls are covered in the sections on Pod, workloads, Service and rollouts.

Contexts and namespaces

TaskCommand
Contexts from kubeconfigkubectl config get-contexts
Current contextkubectl config current-context
Switch to another clusterkubectl config use-context kind-kind
Create a namespacekubectl create namespace shop
Use shop by defaultkubectl config set-context --current --namespace=shop
One command in another namespacekubectl get pods -n kube-system
Across all namespaceskubectl get pods -A

Viewing

TaskCommand
Pod with node and IP addresskubectl get pods -o wide
Pod with labelskubectl get pods --show-labels
Filter by labelkubectl get pods -l app=web
Object state and eventskubectl describe pod web-6d4f8-x2k8q
Full object in YAMLkubectl get deployment web -o yaml
Events sorted by timekubectl get events --sort-by=.metadata.creationTimestamp
Warnings onlykubectl events --types=Warning
Manifest field referencekubectl explain pods
Available API objectskubectl api-resources

Applying manifests

TaskCommand
Create or update from a filekubectl apply -f web.yaml
All manifests in a directorykubectl apply -f k8s/
Preview changes without applyingkubectl diff -f web.yaml
Pod manifest scaffoldkubectl run web --image=nginx:1.30 --dry-run=client -o yaml
Add a labelkubectl label pods web-6d4f8-x2k8q tier=frontend

Rollouts and scaling

TaskCommand
Change the imagekubectl set image deployment/web web=nginx:1.31
Watch the rolloutkubectl rollout status deployment/web
Revision historykubectl rollout history deployment/web
Roll back to the previous revisionkubectl rollout undo deployment/web
Roll back to revision 2kubectl rollout undo deployment/web --to-revision=2
Restart all Pods one by onekubectl rollout restart deployment/web
Set the number of replicaskubectl scale deployment/web --replicas=5
Enable autoscalingkubectl autoscale deployment web --min=2 --max=10

Logs and debugging

TaskCommand
Follow a Pod’s logskubectl logs -f web-6d4f8-x2k8q
Logs of the container’s previous runkubectl logs web-6d4f8-x2k8q --previous
Logs of a Pod from a Deploymentkubectl logs deploy/web
Logs of all Pods with a labelkubectl logs -f -l app=web --all-containers
Shell into a containerkubectl exec -it web-6d4f8-x2k8q -- sh
A Service port on your machinekubectl port-forward svc/web 8080:80
Debug container in a Podkubectl debug -it web-6d4f8-x2k8q --image=busybox:1.38
Pod CPU and memory usagekubectl top pod

Nodes

TaskCommand
Cluster nodeskubectl get nodes -o wide
Stop new Pods from landing on a nodekubectl cordon node-2
Evacuate Pods before maintenancekubectl drain node-2 --ignore-daemonsets
Bring a node back into servicekubectl uncordon node-2

Deletion

TaskCommand
Delete the objects described in a filekubectl delete -f web.yaml
Delete a Podkubectl delete pod web-6d4f8-x2k8q
Delete Pods and Services by labelkubectl delete pods,services -l app=web
Delete a namespace with everything in itkubectl delete namespace shop

Section sources

the section is written from these pages

Installation and first run

You need kubectl, the Kubernetes command line client, and a cluster. On Linux, kubectl is installed from the official pkgs.k8s.io repository, a practice cluster runs in kind, and the connection is checked with kubectl cluster-info.

kubectl on Linux

The kubectl version may be no more than one minor release away from the cluster version: client 1.37 works with a control plane of 1.36, 1.37 or 1.38. The pkgs.k8s.io repository has a separate address for each minor branch — the branch number is part of the path.

bashUbuntu and Debian
sudo apt-get updatesudo apt-get install -y apt-transport-https ca-certificates curl gnupgKEYRING=/etc/apt/keyrings/kubernetes-apt-keyring.gpgREPO=https://pkgs.k8s.io/core:/stable:/v1.37/deb/# key the repository is signed withsudo mkdir -p -m 755 /etc/apt/keyringscurl -fsSL "${REPO}Release.key" | sudo gpg --dearmor -o "$KEYRING"sudo chmod 644 "$KEYRING"# repository of the 1.37 branchecho "deb [signed-by=$KEYRING] $REPO /" \  | sudo tee /etc/apt/sources.list.d/kubernetes.listsudo apt-get updatesudo apt-get install -y kubectl

To move to the next minor branch, change the number in /etc/apt/sources.list.d/kubernetes.list and run apt-get update and apt-get upgrade again. On distributions with dnf, the same repository is added in rpm format — the file /etc/yum.repos.d/kubernetes.repo, installation with sudo dnf install -y kubectl.

Without a package manager, download the binary of the latest stable release and verify the checksum:

bashLinux x86-64
VER=$(curl -L -s https://dl.k8s.io/release/stable.txt)curl -LO "https://dl.k8s.io/release/$VER/bin/linux/amd64/kubectl"curl -LO "https://dl.k8s.io/release/$VER/bin/linux/amd64/kubectl.sha256"echo "$(cat kubectl.sha256)  kubectl" | sha256sum --checksudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

macOS and Windows

kubectl is available for Linux, macOS and Windows; instructions for each system are collected on the Install Tools page among the section sources. kind needs Docker or Podman installed.

A practice cluster in kind

kind runs a local Kubernetes cluster whose nodes are Docker containers. Download the kind binary and create a cluster:

bashon a machine with Docker
# on ARM64 — the file kind-linux-arm64curl -Lo ./kind \  https://kind.sigs.k8s.io/dl/v0.33.0/kind-linux-amd64chmod +x ./kindsudo mv ./kind /usr/local/bin/kindkind create cluster

kind create cluster creates a single-node cluster named kind and adds the kind-kind context to kubeconfig. The node image determines the Kubernetes version: by default it is picked by the kind version, another image is given with the --image flag. A cluster with separate worker nodes is described by a file:

yamlkind-cluster.yaml
# control plane and two worker nodeskind: ClusterapiVersion: kind.x-k8s.io/v1alpha4nodes:- role: control-plane- role: worker- role: worker
bashon a machine with Docker
kind create cluster --name shop --config kind-cluster.yamlkind get clusters

The context of such a cluster is kind-shop; it is deleted with kind delete cluster --name shop. kind does not see an image built locally until it is loaded into the nodes: kind load docker-image myapp:1.0 --name shop. Do not use the latest tag for such images: with it, Kubernetes downloads the image from the registry by default.

Another option for a local cluster is minikube: it runs a cluster of one or several nodes on Linux, macOS and Windows. For real clusters there is kubeadm — it creates a minimal, working and secured cluster.

kubeconfig and contexts

kubectl takes the cluster address and credentials from kubeconfig — by default from the file ~/.kube/config. It describes clusters, users and contexts. A context ties a cluster, a user and a namespace together under one name, and commands go to the current context.

bashon your machine
kubectl config viewkubectl config use-context kind-kind# attach a second file: the lists are mergedexport KUBECONFIG=~/.kube/config:~/.kube/staging.yamlkubectl get nodes --context kind-shop

The KUBECONFIG variable is a list of files separated by colons (semicolons on Windows). If a key appears in several files, the first one wins. The --kubeconfig flag takes exactly one file with no merging, --context selects a context for a single command.

Check

bashon your machine
kubectl version --clientkubectl cluster-info --context kind-kindkubectl get nodes
textexample output
NAME                 STATUS   ROLES           AGE   VERSIONkind-control-plane   Ready    control-plane   2m    v1.37.0

kubectl cluster-info prints the control plane address in response. The message The connection to the server ... was refused - did you specify the right host or port? means that kubectl is not configured or the cluster is not running: check the current context and the list of clusters with kind get clusters.

Section sources

the section is written from these pages

Pods and their life cycle

A pod is the smallest unit that Kubernetes runs and manages: one or more containers with a shared network and shared volumes. Pods are rarely created by hand — workload controllers such as a Deployment create them.

Usually a pod has one container, and the pod is a wrapper around it. Several containers share a pod only when they are tightly coupled: for example, a web server and a sidecar container that keeps its files up to date. A pod’s containers always run on the same node, share an IP address and reach each other via localhost.

A pod is not long-lived. It is scheduled onto a node once and runs there until it completes or is deleted. If the node fails, the pod does not move: a controller creates a replacement, with a different UID.

The pod manifest

yamlpod.yaml
apiVersion: v1kind: Podmetadata:  name: web  labels:    app: webspec:  containers:  - name: web    image: nginx:1.30    ports:    - containerPort: 80    env:    - name: APP_ENV      value: production
bashon your machine
kubectl apply -f pod.yamlkubectl get pod web -o widekubectl describe pod web

Pod phases and container states

The phase (status.phase) is a brief summary of where the pod is in its life cycle. Pending — the cluster has accepted the pod, but it is still waiting for a node or pulling images. Running — the pod is bound to a node, its containers are created and at least one is running. Succeeded and Failed — all containers have terminated: successfully, or at least one with an error. Unknown — the state cannot be obtained, usually because the connection to the node was lost.

Each container has its own state: Waiting, Running or Terminated. CrashLoopBackOff is not a phase but a waiting reason: the container crashes and kubelet restarts it with a growing back-off delay. The delay is 10 s, 20 s, 40 s and so on, but never more than 5 minutes. After the container runs without crashing for 10 minutes, the back-off counter starts from the beginning.

While a container is restarting, the pod phase remains Running.

What happens to a terminated container is set by the pod’s restartPolicy in spec:

restartPolicyWhen it restartsWhere it is used
Always (default)after any terminationDeployment — the only value it accepts
OnFailureonly on a non-zero exit codeJob
NeverneverJob and one-off pods

Probes: liveness, readiness, startup

A probe is a check that kubelet performs on a container at regular intervals. Readiness decides whether the pod receives traffic: until it succeeds, the pod’s IP address is excluded from the EndpointSlice of every one of its Services. Liveness decides whether the container is alive: after several failures in a row kubelet restarts it. Startup gives a slow application time to boot: until it succeeds, the other two probes do not run.

yamlpod.yaml, excerpt
spec:  containers:  - name: web    image: nginx:1.30    ports:    - containerPort: 80    # traffic only after the check succeeds    readinessProbe:      httpGet:        path: /        port: 80      periodSeconds: 5    # restart after 3 failures in a row    livenessProbe:      httpGet:        path: /        port: 80      periodSeconds: 10      failureThreshold: 3    # up to 30 checks, 10 s each, to start    startupProbe:      httpGet:        path: /        port: 80      periodSeconds: 10      failureThreshold: 30
FieldWhat it setsDefault
initialDelaySecondsdelay from container start to the first check0
periodSecondsinterval between checks10
timeoutSecondshow many seconds to wait for a response1
failureThresholdhow many failures in a row count as a failure3
successThresholdhow many successes in a row are needed after a failure; for liveness and startup the only value is 11

There are four ways to check. httpGet succeeds with a response code from 200 to 399, tcpSocket — if the port accepts a connection, exec — if the command in the container exits with code 0. grpc calls a gRPC health check and expects the SERVING status.

Init and sidecar containers

Init containers (initContainers) run when the pod starts, before the main containers, and must complete successfully: for example, wait for the database or prepare files. An init container with restartPolicy: Always becomes a sidecar container: it starts before the main ones and runs for the whole life of the pod.

yamlpod.yaml, excerpt
spec:  initContainers:  # waits until the Service name db appears in DNS  - name: wait-db    image: busybox:1.38    command:    - sh    - -c    - until nslookup db.shop.svc.cluster.local; do sleep 2; done  containers:  - name: web    image: nginx:1.30

Image pull policy

imagePullPolicy decides when kubelet pulls an image. IfNotPresent — only if the image is not on the node, Always — on every container start, Never — only the local image. If the field is not set, the policy is Always for the latest tag or no tag, and IfNotPresent for any other tag or a digest.

The policy is chosen when the object is created and does not change on its own afterwards. In production, specify a concrete tag, such as nginx:1.30, or the image digest: with latest it is hard to tell which version is running and to roll back.

Graceful shutdown

On pod deletion kubelet sends the main process of each container the TERM signal — or the signal from the image’s STOPSIGNAL — and waits terminationGracePeriodSeconds, 30 seconds by default. Processes that do not finish in that time are sent KILL. If a preStop hook is set, it runs before TERM is sent.

At the same time, the endpoint of the deleted pod is marked not ready in the EndpointSlice, and load balancers stop sending it regular traffic. The application must handle TERM by finishing the requests it has started and closing connections. If it needs more than 30 seconds, increase terminationGracePeriodSeconds in the pod’s spec.

Section sources

the section is written from these pages

Workloads: Deployment, StatefulSet, Job

A workload is an application running in a cluster, and objects such as Deployment, StatefulSet, DaemonSet, Job and CronJob manage its Pods for you. Their controllers create Pods from a template and maintain the right number of them: a Deployment for interchangeable replicas, a StatefulSet when every replica has its own name and data.

ObjectWhat it is forExample
Deploymenta stateless application: any replica can replace any othera web server, an API
StatefulSetreplicas with stable names and storage of their owna database
DaemonSetone Pod on every matching nodea networking plugin, a node agent
Joba task that runs until it completes successfullya database migration
CronJoba Job on a cron schedulebackups, reports

Deployment

A Deployment does not create Pods itself: it creates a ReplicaSet, and the ReplicaSet keeps the given number of replicas. Every change to the Pod template (spec.template) produces a new ReplicaSet — rollouts and rollbacks are built on this. Do not edit the ReplicaSets owned by a Deployment by hand.

A StatefulSet has no intermediate ReplicaSet: it manages its Pods itself.
yamldeploy.yaml
apiVersion: apps/v1kind: Deploymentmetadata:  name: web  labels:    app: webspec:  replicas: 3  # which Pods to manage: labels as in the template  selector:    matchLabels:      app: web  template:    metadata:      labels:        app: web    spec:      containers:      - name: web        image: nginx:1.30        ports:        - containerPort: 80        readinessProbe:          httpGet:            path: /            port: 80
bashon your machine
kubectl apply -f deploy.yamlkubectl get deployment webkubectl get rs,pods -l app=web
textexample output
NAME   READY   UP-TO-DATE   AVAILABLE   AGEweb    3/3     3            3           18s

READY is how many replicas are ready out of the desired number, UP-TO-DATE is how many already run the current template, AVAILABLE is how many are available to users. The name of a ReplicaSet is the name of the Deployment plus the hash of the template, for example web-6d4f8; the Pods take their names from it.

Labels and selectors

A label is a “key: value” pair in metadata.labels. The selector of a Deployment picks Pods by labels, so spec.selector must match the labels in spec.template. Selectors of different controllers must not overlap: Kubernetes does not forbid it, but the controllers will start fighting each other for the same Pods.

The selector of an existing Deployment is not edited: the Deployment is deleted and created anew. By default, deleting a Deployment deletes its Pods as well; with the --cascade=orphan flag the Pods keep running.

StatefulSet

A StatefulSet gives every replica a persistent identity: an ordinal number, a name such as db-0 or db-1, and storage of its own that stays with it after recreation. Pods are created in order: db-1 starts only when db-0 is Running and ready. Pods are deleted in reverse order.

The Pods of a StatefulSet get their network names through a headless Service (clusterIP: None): you create the Service yourself and put its name in serviceName. Volumes for the replicas are described by the volumeClaimTemplates template: every replica gets its own PersistentVolumeClaim.

yamldb.yaml
apiVersion: apps/v1kind: StatefulSetmetadata:  name: dbspec:  # a headless Service with clusterIP: None  serviceName: db  replicas: 1  selector:    matchLabels:      app: db  template:    metadata:      labels:        app: db    spec:      containers:      - name: postgres        image: postgres:18        env:        - name: POSTGRES_PASSWORD          valueFrom:            secretKeyRef:              name: db-credentials              key: password        volumeMounts:        - name: data          mountPath: /var/lib/postgresql  volumeClaimTemplates:  - metadata:      name: data    spec:      accessModes: ["ReadWriteOnce"]      resources:        requests:          storage: 10Gi

The db-credentials Secret is created by the command from the section “Configuration: ConfigMaps and Secrets”. Deleting a StatefulSet and scaling down the number of replicas do not delete their volumes: data matters more than automatic clean-up, and the claims remain until you delete them yourself.

DaemonSet

A DaemonSet keeps one Pod on every matching node: when a node is added to the cluster, the control plane places a Pod of this DaemonSet on it. The cluster’s networking plugins and the agents that look after the node itself usually work this way.

Job and CronJob

A Job starts Pods and re-creates them until the required number has completed successfully: completions, 1 by default. Failed Pods are re-created with a back-off of 10 s, 20 s, 40 s and so on, never more than 10 minutes. After backoffLimit failures (6 by default) the Job counts as failed.

yamljob.yaml
apiVersion: batch/v1kind: Jobmetadata:  name: migratespec:  backoffLimit: 4  # delete the Job an hour after it finishes  ttlSecondsAfterFinished: 3600  template:    spec:      restartPolicy: Never      containers:      - name: migrate        image: registry.example.com/shop/web:1.4        command: ["python", "manage.py", "migrate"]

Only restartPolicy: Never and OnFailure are allowed in a Job. activeDeadlineSeconds limits the time of the whole Job: once it passes, the running Pods are stopped and the Job finishes with the reason DeadlineExceeded. The Job itself is not restarted after a failure.

A CronJob creates Jobs on a cron schedule — the same string as a line in a crontab. Without timeZone the schedule is interpreted in the time zone of kube-controller-manager.

yamlcronjob.yaml
apiVersion: batch/v1kind: CronJobmetadata:  name: reportspec:  # every day at 03:00, Tashkent time  schedule: "0 3 * * *"  timeZone: Asia/Tashkent  # do not start while the previous run is still going  concurrencyPolicy: Forbid  jobTemplate:    spec:      template:        spec:          restartPolicy: OnFailure          containers:          - name: report            image: registry.example.com/shop/web:1.4            command: ["python", "manage.py", "report"]

The default is concurrencyPolicy: Allow, and runs may overlap; Replace cancels a run that has not finished and starts a new one. A CronJob keeps the 3 most recent successful Jobs and 1 failed one — successfulJobsHistoryLimit and failedJobsHistoryLimit change this. A CronJob name is no longer than 52 characters.

Section sources

the section is written from these pages

Services, Ingress and Gateway API

A Service gives a group of Pods a stable address: it selects Pods by labels, gets a virtual IP and a DNS name such as web.shop.svc.cluster.local, and distributes requests across the Pods. From outside the cluster, HTTP traffic reaches a Service through Gateway API or Ingress.

Pods come and go, and their IP addresses change. A Service decouples clients from particular Pods: the Service controller watches for Pods with matching labels and writes their addresses into EndpointSlice objects. The client talks to a single address, and the cluster decides what sits behind it.

Gateway and HTTPRoute are installed separately; every cluster has a Service.
yamlsvc.yaml
apiVersion: v1kind: Servicemetadata:  name: webspec:  # Pods with this label receive traffic  selector:    app: web  ports:  - name: http    port: 80    targetPort: 80
bashon your machine
kubectl apply -f svc.yamlkubectl get service webkubectl get endpointslices -l kubernetes.io/service-name=web# check from your machine: http://localhost:8080kubectl port-forward svc/web 8080:80

port is the Service port, targetPort is the container port; if targetPort is not set, it equals port. Instead of a number, targetPort can take a port name from the Pod manifest: then the port can change in a new version of the application without touching clients. The default protocol is TCP.

Service types

TypeHow it is availableWhen to choose it
ClusterIP (the default)an internal IP address, from inside the cluster onlycommunication between parts of an application
NodePortthe same port on every node (by default from 30000–32767) plus a ClusterIPyour own load balancer, a test environment
LoadBalanceran external load balancer provisioned by the cloud providerproduction in the cloud
ExternalNamea CNAME DNS record pointing to an external name, no proxyingan external database by name
headless (clusterIP: None)no IP address: DNS returns the addresses of all PodsStatefulSet, choosing Pods yourself

Kubernetes itself does not provision a load balancer: LoadBalancer requires a cloud integration or your own implementation, and the address appears in status.loadBalancer. kube-proxy does not process headless Services: there is no balancing, and the client picks a Pod on its own.

DNS for Services and Pods

The cluster DNS — usually CoreDNS — creates a web.shop.svc.cluster.local record for a Service, where shop is the namespace and cluster.local is the cluster domain. From your own namespace, the name web is enough; from another one, web.shop. /etc/resolv.conf, which the kubelet prepares for every Pod, completes the short names.

basha temporary Pod in the cluster
kubectl run dns-test -it --rm --restart=Never \  --image=busybox:1.38 -- nslookup web.shop.svc.cluster.local

Named ports also get SRV records: _http._tcp.web.shop.svc.cluster.local returns the number of the http port. An ordinary Service answers with its virtual IP; a headless one returns the addresses of all selected Pods.

Ingress

Ingress is a set of routing rules for HTTP and HTTPS traffic from the outside to a Service: by hostname and path. The object itself does nothing: an Ingress controller is needed to enforce it. The Ingress API is frozen — it is stable and will not be removed, but it is no longer developed, and the Kubernetes project recommends Gateway API.

yamlingress.yaml
apiVersion: networking.k8s.io/v1kind: Ingressmetadata:  name: webspec:  # the IngressClass of the installed controller  ingressClassName: nginx-example  rules:  - host: shop.example.com    http:      paths:      - path: /        pathType: Prefix        backend:          service:            name: web            port:              number: 80

pathType is required: Prefix matches the path segment by segment, Exact matches it in full and case-sensitively, and ImplementationSpecific leaves the decision to the controller. If several paths match, the longest one wins.

Gateway API

Gateway API is a set of objects installed into the cluster separately, as CRDs, together with an implementation. A GatewayClass describes the implementation; a Gateway is the entry point for traffic: a cloud load balancer or a proxy inside the cluster. An HTTPRoute sets the rules by which requests travel from the Gateway to Services. By default, a Gateway accepts routes only from its own namespace.

yamlgateway.yaml
apiVersion: gateway.networking.k8s.io/v1kind: Gatewaymetadata:  name: shopspec:  # the class — from the installed implementation  gatewayClassName: example-class  listeners:  - name: http    protocol: HTTP    port: 80---apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:  name: webspec:  parentRefs:  - name: shop  hostnames:  - "shop.example.com"  rules:  - matches:    - path:        type: PathPrefix        value: /    backendRefs:    - name: web      port: 80

Gateway API is the successor to Ingress, but the Ingress object is not part of it: existing Ingress objects are migrated to Gateway and HTTPRoute once, following the migration guide. A NetworkPolicy object restricts which Pods may talk to each other — it is covered in the section “Cluster security”.

Section sources

the section is written from these pages

Configuration: ConfigMaps and Secrets

A ConfigMap stores non-secret settings, a Secret stores passwords, tokens and keys; both separate configuration from the image, so one image works in all environments. An application receives values as environment variables or as files in a volume. By default a Secret is not encrypted.

ConfigMap

yamlconfig.yaml
apiVersion: v1kind: ConfigMapmetadata:  name: web-configdata:  # simple values  LOG_LEVEL: info  DB_HOST: db  # a file value  app.properties: |    cache.size=256    feature.search=true

Values in data are UTF-8 strings; binary data goes into binaryData in base64. A ConfigMap and the Pod that uses it must be in the same namespace. A ConfigMap holds at most 1 MiB of data: keep large files in a volume or separate storage.

Secret

bashon your machine
kubectl create secret generic db-credentials \  --from-literal=user=shop \  --from-literal=password='change-me'kubectl get secret db-credentials -o yaml

In the output the values are base64-encoded — that is not encryption: anyone who can read the Secret gets the password with the base64 -d command. In a manifest, values go into data in base64 or into stringData as plain text — Kubernetes itself will move them into data. A single Secret is up to 1 MiB in size.

The default type is Opaque — arbitrary data. Built-in types cover the common cases: kubernetes.io/tls for a certificate and key, kubernetes.io/dockerconfigjson for access to a private image registry, and kubernetes.io/basic-auth and kubernetes.io/ssh-auth.

How to pass settings into a container

yamldeploy.yaml, excerpt
spec:  containers:  - name: web    image: nginx:1.30    # all keys of the ConfigMap as environment variables    envFrom:    - configMapRef:        name: web-config    env:    # one Secret key into a variable    - name: DB_PASSWORD      valueFrom:        secretKeyRef:          name: db-credentials          key: password    volumeMounts:    - name: config      mountPath: /etc/web      readOnly: true  volumes:  # each key will become a file in /etc/web  - name: config    configMap:      name: web-config

Keys whose names do not fit the rules for environment variable names will not reach the environment, but the Pod will still start. In a volume, each key becomes a file with the same name; the items list lets you pick only the keys you need.

MethodChanges are visibleWhen to choose it
env and envFromno, the Pod needs a restartsimple values that are read at startup
files in a volumeyes, with the kubelet sync delayconfiguration files, certificates
a file in a volume via subPathnowhen one file is needed in an existing directory

For the application to see new values from environment variables, its Pod has to be recreated — the command for that is described in the section “Rollouts and rollbacks”.

Immutable ConfigMaps and Secrets

immutable: true forbids changing the object’s data. This protects against an accidental edit that would take the application down and reduces the load on kube-apiserver: the kubelet stops watching such objects. The flag cannot be undone — the object is deleted and recreated, and the Pods are recreated too.

Namespaces

A namespace is an area of names inside a cluster: object names are unique only within their own namespace. ConfigMaps and Secrets are available only to Pods of their own namespace, so it is safer to spread the Secrets of different teams and environments across different namespaces.

bashon your machine
kubectl create namespace shopkubectl config set-context --current --namespace=shopkubectl get namespaces

A new cluster has four namespaces: default, kube-system for system objects, plus kube-public and kube-node-lease. Nodes, PersistentVolumes and StorageClasses belong to no namespace. In production, do not use default, and do not name your own namespaces with the kube- prefix: it is reserved.

Section sources

the section is written from these pages

Storage: volumes and PersistentVolume

Files written inside a container are lost when the container restarts, so data is kept in volumes. The ephemeral emptyDir volume lives as long as the Pod does, while persistent data is kept in a PersistentVolume: a Pod requests it with a PersistentVolumeClaim (PVC), and the volume outlives the Pod.

Volumes are listed in the Pod’s spec.volumes and mounted into containers through volumeMounts. Data in any volume survives a container restart. emptyDir is created empty when the Pod is scheduled onto a node and is deleted together with the Pod; it is used for caches and for sharing files between containers.

yamlExcerpt from pod.yaml
spec:  containers:  - name: web    image: nginx:1.30    volumeMounts:    - name: cache      mountPath: /var/cache/nginx  volumes:  - name: cache    emptyDir: {}

PersistentVolume and PersistentVolumeClaim

A PersistentVolume (PV) is a piece of storage in the cluster: a cloud disk, NFS, iSCSI. Its lifecycle is independent of any Pod. A PersistentVolumeClaim (PVC) is a request for storage of the required size and access mode. A control plane controller binds the claim and the volume, one to one.

PVs are usually not created by hand. The claim names a StorageClass, and the class’s provisioner creates a volume for the claim — this is dynamic provisioning. If no suitable volume exists and none can be created, the claim stays unbound.

This is how dynamic provisioning works; a PV created by an administrator in advance is bound the same way.
yamlpvc.yaml
apiVersion: v1kind: PersistentVolumeClaimmetadata:  name: pgdataspec:  # no storageClassName — the default class  accessModes:  - ReadWriteOnce  resources:    requests:      storage: 10Gi---apiVersion: v1kind: Podmetadata:  name: dbspec:  containers:  - name: postgres    image: postgres:18    env:    - name: POSTGRES_PASSWORD      valueFrom:        secretKeyRef:          name: db-credentials          key: password    volumeMounts:    - name: data      mountPath: /var/lib/postgresql  volumes:  - name: data    persistentVolumeClaim:      claimName: pgdata
bashon your machine
kubectl apply -f pvc.yamlkubectl get pvc pgdatakubectl get pv

The claim and the Pod must be in the same namespace. If the class has volumeBindingMode: WaitForFirstConsumer, the volume is created only once a Pod with that claim appears: that way the volume ends up where the Pod can run. The default is Immediate — the volume is created immediately.

Access modes

ModeIn outputWhat it allows
ReadWriteOnceRWOread and write from a single node; Pods on that node can use the volume together
ReadOnlyManyROXread-only from many nodes
ReadWriteManyRWXread and write from many nodes
ReadWriteOncePodRWOPread and write by a single Pod across the whole cluster; CSI volumes only

Which modes are available depends on the storage: hostPath supports only RWO, NFS — RWO, ROX and RWX. The mode is used to match volumes and does not enforce write protection. A volume can be mounted in only one mode at a time, even if the storage supports several.

What happens to the volume after a claim is deleted

When a PVC is deleted, the fate of the volume is decided by its reclaim policy (reclaimPolicy). Delete removes the PV along with the disk in the external storage. Retain keeps the PV and the data: the volume moves to the Released phase, and an administrator must reclaim it manually. The Recycle policy is deprecated — dynamic provisioning is used instead.

Kubernetes does not delete a claim that a Pod is using straight away: it stays in the Terminating status until the Pod stops using it. A PV bound to a claim is protected in the same way.

StorageClass

A StorageClass describes a kind of storage: who creates the volumes (provisioner), with which parameters (parameters) and reclaim policy. The default class is marked with the annotation storageclass.kubernetes.io/is-default-class: "true", and claims without storageClassName get it. A claim with storageClassName: "" does not use dynamic provisioning.

yamlstorageclass.yaml
apiVersion: storage.k8s.io/v1kind: StorageClassmetadata:  name: retained# provisioner name — from the storage documentationprovisioner: csi-driver.example-vendor.examplereclaimPolicy: RetainallowVolumeExpansion: truevolumeBindingMode: WaitForFirstConsumer

If the class has allowVolumeExpansion: true, a volume can be grown: edit resources.requests.storage in the claim, and the existing volume expands — no new volume is created. To list the cluster’s classes: kubectl get storageclass.

Volumes for StatefulSets

A StatefulSet creates claims from volumeClaimTemplates: each replica gets its own PVC and, after being recreated on a different node, mounts the same claim. By default, claims remain both after the StatefulSet is deleted and after the replica count is scaled down — persistentVolumeClaimRetentionPolicy governs this, with the values Retain, the default, and Delete.

Docker volumes on a single host work differently — they are covered in the Docker reference, section “Volumes, bind mounts and tmpfs”.

Section sources

the section is written from these pages

Resources and scaling

A resource request is how much CPU and memory a container needs: the scheduler uses it to choose a node, and the kubelet reserves that share. A limit is the ceiling: the container will not be given more than that. The HorizontalPodAutoscaler changes the number of replicas to match the load, and for CPU it relies on requests.

Requests and limits

yamldeploy.yaml, template fragment
spec:  containers:  - name: web    image: nginx:1.30    resources:      requests:        cpu: 250m        memory: 128Mi      limits:        cpu: 500m        memory: 256Mi

CPU is specified in cores: 1 is one physical or virtual core, 500m (500 millicores) is half. You cannot specify anything finer than 1m. Memory is specified in bytes with suffixes: M is megabytes (10⁶ bytes), Mi is mebibytes (2²⁰ bytes, MiB). Case matters: 400m of memory is 0.4 bytes, not 400 MiB.

ResourceAbove the requestAbove the limit
CPUallowed if the node has spare CPUnot allowed: the kernel throttles the process
Memoryallowed, but if the node runs short of memory the Pod will likely be evictedthe kernel may kill the process: OOMKilled, exit code 137

The memory limit does not take effect straight away: the kernel kills the process only when it notices a memory shortage, so a container may exceed the limit briefly. If only a limit is set, the request is taken to be equal to it. A Pod whose requests do not fit on any node stays Pending with a FailedScheduling event.

QoS classes

Based on requests and limits, Kubernetes assigns every Pod a quality of service (QoS) class. When a node runs out of resources, the class decides which Pods are evicted first.

ClassConditionWhen the node runs short of resources
Guaranteedevery container has requests and limits set for CPU and memory, and they are equalevicted last
Burstableat least one request or limit is setafter all BestEffort
BestEffortno requests or limits set anywhereevicted first

Manual scaling

bashon your machine
kubectl scale deployment/web --replicas=5kubectl get deployment web

Horizontal scaling changes the number of replicas; vertical scaling changes the resources of already running Pods. Horizontal scaling does not apply to a DaemonSet: the number of its Pods cannot be changed.

HorizontalPodAutoscaler

The HorizontalPodAutoscaler (HPA) is an object and a controller in the control plane. Every 15 seconds it compares the metric against the target and changes replicas on a Deployment or StatefulSet. CPU and memory metrics are provided by the Metrics Server and the metrics.k8s.io API; the Metrics Server is installed in the cluster separately.

yamlhpa.yaml
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata:  name: webspec:  scaleTargetRef:    apiVersion: apps/v1    kind: Deployment    name: web  minReplicas: 2  maxReplicas: 10  metrics:  - type: Resource    resource:      name: cpu      target:        # average utilisation — 70% of requests.cpu        type: Utilization        averageUtilization: 70
bashon your machine
kubectl apply -f hpa.yaml# the same in one commandkubectl autoscale deployment web --min=2 --max=10 --cpu=70%kubectl get hpa webkubectl describe hpa web

Utilisation is calculated against the request: 70% with cpu: 250m means 175m on average per Pod. If a container has no CPU request, the HPA does nothing for CPU. The desired number of replicas is the current number multiplied by the ratio of the current metric to the target, rounded up.

The HPA ignores changes within the tolerance — 10% by default. It scales up straight away, but scales down no sooner than after the stabilisation window — 300 seconds by default — to keep the number of replicas from jumping around. The tolerance and the windows are configured in spec.behavior.

Scaling to zero

As of 1.37, scaling to zero is a beta feature enabled by default. minReplicas: 0 is allowed if the HPA has at least one metric of type Object or External, such as queue length. With no load, the HPA scales the replicas down to zero; when the metric again calls for at least one replica, it brings them back up. CPU and memory cannot scale to zero: they are measured only on running Pods.

Vertical scaling and nodes

The resources of a running Pod can be changed in place, without recreating it: since 1.35 this has been a stable feature. The VerticalPodAutoscaler picks requests automatically, but it is an add-on: it is installed separately, it needs the Metrics Server, and it cannot change resources in place yet. When the nodes themselves run short, the cluster is expanded with node autoscaling.

Section sources

the section is written from these pages

Rolling out updates and rolling back

A Deployment rollout starts whenever the pod template changes: a new ReplicaSet scales up while the old one scales down, and the specified minimum of pods is available at every moment. If the new version is faulty, a rollback restores the previous revision with kubectl rollout undo.

Rollout strategies

StrategyHow it replaces podsDowntime
RollingUpdate (default)gradual: the old ReplicaSet scales down while the new one scales upnone: some pods are always available
Recreatedeletes all the old pods first, then creates the new onesyes, while the new pods are starting

With Recreate, the old and new versions never run at the same time. Two fields set the pace of RollingUpdate. maxUnavailable — how many pods below the desired number may be unavailable during a rollout; maxSurge — how many may be created above it.

Both fields default to 25%; the percentage is rounded up for maxSurge and down for maxUnavailable. With 3 replicas that gives 1 and 0: Kubernetes first starts the fourth pod, waits for it to become ready and only then removes an old one. Both fields cannot be zero at once.

A rollout with the default values; the pod that is starting is shown dashed.
  1. 3 pods of the old version v1 are running.
  2. A new ReplicaSet is created and the first v2 pod starts — 4 pods in total.
  3. The v2 pod is ready: the old ReplicaSet is scaled down to 2 and the second v2 pod starts.
  4. The second v2 pod is ready: 1 v1 pod remains and the third v2 pod starts.
  5. 3 v2 pods are running; the old ReplicaSet is scaled down to 0 and kept for rollback.
yamldeploy.yaml, excerpt
spec:  replicas: 3  # how many old ReplicaSets to keep for rollback  revisionHistoryLimit: 10  # 10 minutes without progress means a stuck rollout  progressDeadlineSeconds: 600  # a pod counts as available after 10 s of readiness without crashes  minReadySeconds: 10  strategy:    type: RollingUpdate    rollingUpdate:      maxSurge: 1      maxUnavailable: 0

Rollout commands

bashon your machine
# a new image version starts a rolloutkubectl set image deployment/web web=nginx:1.31kubectl rollout status deployment/webkubectl rollout history deployment/web# roll back to the previous revision or to a specific onekubectl rollout undo deployment/webkubectl rollout undo deployment/web --to-revision=2
CommandWhat it does
kubectl rollout pause deployment/webpauses rollouts: template changes accumulate
kubectl rollout resume deployment/webstarts a single rollout with all the changes
kubectl rollout restart deployment/webrestarts the pods of the Deployment, for example to pick up a new ConfigMap
kubectl rollout history deployment/web --revision=2shows the template of revision 2
kubectl annotate deployment/web kubernetes.io/change-cause="nginx 1.31"annotates the revision: the text is visible in the CHANGE-CAUSE column of the history

A new revision appears only when spec.template changes: kubectl scale does not start a rollout. The --record flag for annotating revisions is deprecated — use the kubernetes.io/change-cause annotation instead.

A stuck rollout

A rollout is considered stuck if it has not made progress within progressDeadlineSeconds — 600 seconds by default. That happens when quota runs out or the new pods keep failing. The Deployment then gets a Progressing condition with status False and reason ProgressDeadlineExceeded, and kubectl rollout status exits with code 1.

textsample output
Waiting for rollout to finish: 2 out of 3 new replicas have been updated...error: deployment "web" exceeded its progress deadline

Kubernetes itself does not roll back a stuck rollout: fix the cause or run kubectl rollout undo. Rollback needs the old ReplicaSets: they are kept up to revisionHistoryLimit, 10 by default, and a deleted ReplicaSet is a lost revision.

PodDisruptionBudget

Node maintenance is a voluntary disruption: kubectl drain evicts pods through the Eviction API. A PodDisruptionBudget (PDB) limits how many of an application’s pods may be unavailable at the same time during such disruptions, and drain waits until the budget allows evicting the next pod.

yamlpdb.yaml
apiVersion: policy/v1kind: PodDisruptionBudgetmetadata:  name: webspec:  # at most 1 pod unavailable at a time  maxUnavailable: 1  selector:    matchLabels:      app: web
bashon your machine
kubectl apply -f pdb.yamlkubectl get poddisruptionbudgets

A PDB sets either maxUnavailable or minAvailable. maxUnavailable: 1 works with any number of replicas, while minAvailable is convenient when the share of running pods matters: for example, minAvailable: 90% for a stateless web application. A PDB does not constrain the rollouts of Deployments and StatefulSets and does not stop a pod or a Deployment from being deleted directly. The budget does not prevent hardware failures, but they count against it.

Canary release

A canary release is done with two Deployments. The main one has the label track: stable and 3 replicas; the canary one has track: canary, 1 replica and the new image version. The Service matches pods only by the shared label app: web, so the new version receives a share of requests in the proportion 3 to 1.

yamlweb-canary.yaml
apiVersion: apps/v1kind: Deploymentmetadata:  name: web-canaryspec:  replicas: 1  selector:    matchLabels:      app: web      track: canary  template:    metadata:      labels:        app: web        track: canary    spec:      containers:      - name: web        image: nginx:1.31

So that the selectors of the canary and main Deployments do not overlap, the main one must also select pods by track: stable. Set this label at creation time: the selector of an existing Deployment cannot be changed. Once you are satisfied with the new version, update the main Deployment and delete the canary.

Section sources

the section is written from these pages

Helm: charts and releases

Helm is a package manager for Kubernetes. A chart is a package of manifest templates with default values in values.yaml. A release is an instance of a chart installed in a cluster, with its own name and revision history.

Installing Helm

bashLinux
curl -fsSL -o get_helm.sh \  https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-4chmod 700 get_helm.sh./get_helm.sh

The script installs Helm 4. Prebuilt binaries for every OS are available in the project’s releases. On macOS, Helm is installed through Homebrew (brew install helm), on Windows through winget (winget install Helm.Helm): these packages are maintained by the community, not by the Helm project.

Your first chart and release

bashon your machine
# chart scaffold in the web directoryhelm create webhelm lint webhelm install web ./web --namespace shophelm list --namespace shophelm status web --namespace shop

helm install takes a release name and a chart: from a repository, a .tgz archive, a directory or a URL. Helm does not wait for the resources to come up. With the --wait flag it waits for Pods to become ready, PVCs to bind and Services to get addresses — up to --timeout, 5 minutes by default.

Repositories

bashon your machine
helm repo add example https://charts.example.comhelm repo updatehelm search repo examplehelm show values example/web

Helm has no default repository — each one is added with the helm repo add command. helm search repo searches a local copy of the index, while helm search hub searches the Artifact Hub catalogue.

Custom values: -f and --set

Default values live in the chart’s values.yaml; you can view them with helm show values. Override them with a file — the -f (--values) flag, several can be given and the rightmost wins — or with the --set flag, which takes precedence over files.

yamlvalues-prod.yaml
replicaCount: 3image:  tag: "1.31"resources:  requests:    cpu: 250m    memory: 128Mi
bashon your machine
# installs the release if it does not exist, otherwise upgrades ithelm upgrade --install web ./web \  --namespace shop \  -f values-prod.yaml \  --set replicaCount=4helm get values web --namespace shop

helm upgrade --install installs the release if it does not exist yet and upgrades an existing one: a single command works both for the first installation and for upgrades. An upgrade changes only what has changed since the previous release. Values from --set are stored in the release Secret, and --reset-values clears them.

Revisions, rollback and removal

bashon your machine
helm history web --namespace shophelm rollback web 1 --namespace shophelm uninstall web --namespace shop

Every installation, upgrade and rollback increases the revision number by 1. The --rollback-on-failure flag of helm upgrade rolls a failed upgrade back to the last successful release. helm uninstall deletes the release along with its history, and it cannot be rolled back afterwards; --keep-history preserves the history.

Chart anatomy

textchart structure
web/  Chart.yaml          name, chart version, appVersion  values.yaml         default values  values.schema.json  values schema, optional  charts/             dependency charts  templates/          manifest templates  templates/NOTES.txt hint shown after installation

Chart.yaml is required: it holds apiVersion: v2, the name and a version following SemVer, while appVersion is the version of the application itself. The archive is named after version: helm package web creates web-0.1.0.tgz.

Charts in OCI registries

Charts are best stored in registries with OCI support — the same ones that hold container images: Docker Hub, Harbor, cloud registries. A chart address starts with oci://; helm pull, helm push, helm show, helm template, helm install and helm upgrade all understand it.

bashon your machine
helm registry login -u shop registry.example.comhelm package webhelm push web-0.1.0.tgz oci://registry.example.com/charts# the chart’s rendered manifestshelm template web oci://registry.example.com/charts/web \  --version 0.1.0helm upgrade --install web \  oci://registry.example.com/charts/web --version 0.1.0

In helm push the address is given without the chart name and tag: Helm takes them from Chart.yaml. In the other commands the chart name in the address is required, and the version is set by --version.

Section sources

the section is written from these pages

Cluster security

The main threats to a cluster are excess permissions in the API, containers with access to the node and an open network between Pods. Three mechanisms address them: RBAC restricts actions in the API, Pod Security Admission keeps unsafe Pods out, and NetworkPolicy restricts traffic.

RBAC: roles and bindings

Four objects describe RBAC (role-based access control). A Role is a set of permissions in a single namespace, a ClusterRole covers the whole cluster or any namespace. A RoleBinding grants a role to a user, a group or a ServiceAccount in a namespace, a ClusterRoleBinding across the whole cluster.

Permissions only add up: RBAC has no deny rules. A role for reading Pods and their logs:

yamlrbac.yaml
apiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata:  namespace: shop  name: pod-readerrules:- apiGroups: [""]  resources: ["pods", "pods/log"]  verbs: ["get", "list", "watch"]---apiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata:  namespace: shop  name: ci-reads-podssubjects:- kind: ServiceAccount  name: ci  namespace: shoproleRef:  kind: Role  name: pod-reader  apiGroup: rbac.authorization.k8s.io

The service account and the role can also be created with commands. Instead of a role of your own, you can grant the built-in ClusterRole view: within a namespace it gives read access to most objects, but not to Secrets and not to the roles themselves.

bashon your machine
kubectl create serviceaccount ci -n shopkubectl create role pod-reader --verb=get,list,watch \  --resource=pods,pods/log -n shop# the built-in view role in the shop namespacekubectl create rolebinding ci-view --clusterrole=view \  --serviceaccount=shop:ci --namespace=shop

Check permissions with the command kubectl auth can-i: it answers yes or no with any authorisation method. The --as flag checks the permissions of another user or service account — this requires permission to impersonate.

bashon your machine
kubectl auth can-i create deployments --namespace shop# permissions of the ci service accountkubectl auth can-i list pods --namespace shop \  --as=system:serviceaccount:shop:ci
  • List specific resources and verbs instead of *: a wildcard also grants access to resources that appear later.
  • Grant cluster-admin only to administrators: in a ClusterRoleBinding this role gives full control over every resource in the cluster.
  • Do not grant unnecessary permissions on Secrets: once they are read, the permissions of the service accounts of your own namespace can be obtained.

Pod Security Standards

Pod Security Standards define three levels. privileged has no restrictions. baseline forbids the known privilege escalation paths: privileged containers, hostNetwork, hostPath volumes. restricted is a strict profile based on best practices. The built-in Pod Security Admission controller applies the levels to namespaces through labels.

bashon your machine
kubectl label namespace shop \  pod-security.kubernetes.io/enforce=restricted \  pod-security.kubernetes.io/warn=restricted
ModeWhat happens on a violation
enforcethe Pod is rejected
auditan event is flagged in the audit log, the Pod is created
warnthe user sees a warning, the Pod is created

enforce checks only the Pods themselves, while warn and audit also check the templates in Deployments, Jobs and other workloads, so a violation becomes visible earlier. Start with warn, fix the manifests and only then enable enforce.

A container under the restricted profile

Run containers without privileges: a privileged container bypasses isolation and gains access to the node.

yamldon’t do this
spec:  containers:  - name: web    image: registry.example.com/shop/web:1.4    securityContext:      # bypasses container isolation      privileged: true
yamlthe restricted profile
spec:  securityContext:    # the image must run as non-root    runAsNonRoot: true    seccompProfile:      type: RuntimeDefault  containers:  - name: web    image: registry.example.com/shop/web:1.4    securityContext:      allowPrivilegeEscalation: false      capabilities:        drop: ["ALL"]

The restricted profile forbids hostPath and allows only configMap, secret, emptyDir, persistentVolumeClaim volumes and a few more. Of the dropped capabilities, only NET_BIND_SERVICE can be added back.

NetworkPolicy

By default, a Pod is not isolated: it accepts and opens any connections. Once a Pod is selected by at least one NetworkPolicy with the type Ingress or Egress, only what the policies allow is permitted in that direction. Policies add up, and their order does not matter.

yamlnetpol.yaml
# deny all incoming connections in shopapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: default-deny-ingress  namespace: shopspec:  podSelector: {}  policyTypes:  - Ingress---# the database accepts only web on port 5432apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:  name: db-from-web  namespace: shopspec:  podSelector:    matchLabels:      app: db  policyTypes:  - Ingress  ingress:  - from:    - podSelector:        matchLabels:          app: web    ports:    - protocol: TCP      port: 5432

A connection goes through only if both the sender’s egress policy and the receiver’s ingress policy allow it. Traffic between a Pod and its own node is always allowed. How to store Secrets and who gets access to them is covered in the section “Configuration: ConfigMaps and Secrets”.

Section sources

the section is written from these pages

Common errors and diagnostics

Begin diagnostics with the Pod's status and events: kubectl get pods shows the status and restart count, kubectl describe pod — the events where the scheduler and the kubelet record the reason. Next, look at the logs of the previous run and, if needed, attach a debug container.

Order of checks

  1. kubectl get pods -o wide — status, restarts and the node.
  2. kubectl describe pod web-6d4f8-x2k8q — the containers' state (State, Last State, Reason) and the events at the bottom of the output.
  3. kubectl logs web-6d4f8-x2k8q --previous — the output of the previous, failed run of the container.
  4. kubectl get events --namespace=shop — the events of the whole namespace.
  5. kubectl debug -it web-6d4f8-x2k8q --image=busybox:1.38 --target=web — a debug container for when the image has no shell.

ImagePullBackOff

Cause: the kubelet cannot pull the image — the name or tag is wrong, the image is missing from the registry, or the registry is private and imagePullSecrets is not set. Kubernetes retries with a growing pause, up to 5 minutes.

bashcheck
kubectl describe pod web-6d4f8-x2k8q# whether the image can be pulled manuallydocker pull nginx:1.31
bashfix: private registry
kubectl create secret docker-registry regcred \  --docker-server=registry.example.com \  --docker-username=ci \  --docker-password="$REGISTRY_PASSWORD"

Then reference the Secret in the Pod template: imagePullSecrets: [{name: regcred}]. The Secret must be in the same namespace as the Pod.

CrashLoopBackOff

Cause: the container's main process exits with an error, the kubelet restarts it, and the status shows CrashLoopBackOff. In kubectl describe pod the container has State: Waiting and Last State: Terminated with an exit code.

bashcheck
kubectl logs web-6d4f8-x2k8q --previouskubectl describe pod web-6d4f8-x2k8q
bashfix: investigate in the copy
# a copy of the Pod that runs sh instead of the applicationkubectl debug web-6d4f8-x2k8q -it --copy-to=web-debug \  --container=web -- shkubectl delete pod web-debug

In the copy, check the environment variables and the configuration files, and run the application's command manually. Fix the manifest or the image, then delete the copy.

Pod stuck in Pending

Cause: the scheduler found no suitable node — there is not enough CPU or memory for the requests, the nodes carry a taint the Pod does not tolerate, or the Pod occupies a hostPort. The Pod events will show FailedScheduling with an explanation, for example 0/3 nodes available: insufficient cpu.

bashcheck
kubectl describe pod web-6d4f8-x2k8q# how much resource on the nodes is already in usekubectl describe nodes
  • Reduce the requests or the number of replicas, or delete the Pods you do not need.
  • Add nodes. Make sure the Pod fits on at least one node: compare the requests with the node's Allocatable, not with its Capacity.
  • Check the node taints: if the Pod does not tolerate them, the scheduler considers only the remaining nodes.
  • Remove the hostPort: use a Service to access the Pod.

OOMKilled

Cause: the container exceeded its memory limit and the kernel killed the process. In kubectl describe pod the container has Last State: Terminated, Reason: OOMKilled and Exit Code: 137, and the Restart Count keeps rising.

bashcheck
kubectl describe pod web-6d4f8-x2k8q
textexample output
    Last State:     Terminated      Reason:       OOMKilled      Exit Code:    137    Ready:          False    Restart Count:  5
  • Check the application for a memory leak.
  • If the consumption is normal for the application, raise limits.memory and requests.memory.

Service does not respond

Cause: the Service has no endpoints because its selector does not match the Pod labels, or the Service's targetPort does not match the port the container listens on.

bashcheck
kubectl get endpointslices -l kubernetes.io/service-name=webkubectl get pods --selector=app=webkubectl get service web -o yaml
  • If the EndpointSlice is empty, make the labels in the Pod template match the Service selector.
  • The number of addresses in the EndpointSlice must match the number of the application's Pods.
  • Check the Service's targetPort against the container's containerPort.

Forbidden

Cause: authorisation denied the request — the user or the service account lacks the required permission, and the API responds with HTTP 403 (Forbidden).

bashcheck
kubectl auth can-i list pods --namespace=shopkubectl auth can-i list pods --namespace=shop \  --as=system:serviceaccount:shop:ci

Fix: grant the missing permission through a Role and a RoleBinding — see the “Cluster security” section.

Other symptoms

SymptomCauseWhat to do
Pod stays in Terminating for a long timethe Pod has a finalizer and an admission webhook blocks removing itcheck the ValidatingWebhookConfiguration and MutatingWebhookConfiguration for UPDATE on pods
Pod evicted from a node when memory runs shortthe container used more memory than its request and the node ran out of memoryset requests.memory based on actual usage; node utilisation — kubectl describe nodes
kubectl exec cannot find a shellthe image has no sh, for example distrolesskubectl debug -it with an image that has the tools

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Kubernetes 1.37. The latest release is 1.37.2, released on 28 October 2026. The project supports the three most recent minor branches, and each receives patch releases for about a year.

BranchStatusLatest releaseSupported until
1.37current, covered here1.37.2, 28 October 202628 October 2027
1.36supported1.36.6, 28 October 202628 June 2027
1.35supported1.35.10, 28 October 202628 February 2027
1.34no longer supported1.34.13, 28 October 202627 October 2026

Component versions may differ within the compatibility rules (version skew). kubectl may be one minor version ahead of or behind kube-apiserver. kubelet and kube-proxy are never newer than kube-apiserver and may lag behind it by no more than three minor versions. kube-controller-manager and kube-scheduler are also never newer than kube-apiserver and may lag behind by no more than one.

What changed in 1.37

  • Resources and scaling: HorizontalPodAutoscaler scales to zero — beta, enabled by default. minReplicas: 0 works with Object and External metrics, but not with CPU and memory.
  • Resources and scaling: the configurable HPA tolerance — the tolerance field — is now stable.
  • Resources and scaling: the metrics.k8s.io API, which serves the HPA and kubectl top, is now stable — version v1 is now available; v1beta1 keeps working during the transition.
  • Workloads: in StatefulSet, maxUnavailable for rolling updates works by default again. The Recreate strategy for StatefulSet arrives as an alpha feature behind the StatefulSetRecreateStrategy feature gate.
  • Storage: PVC has gained an Unused condition (beta, enabled by default) — its lastTransitionTime shows the moment since which the claim has not been used by any Pod.
  • Cheat sheet: kubectl get -o kyaml output is now stable. KYAML is a stricter subset of YAML for Kubernetes; any KYAML file is ordinary YAML, and old manifests need no changes.

Deprecated and removed

  • kube-dns is deprecated: move to CoreDNS — the default DNS add-on since 1.13. No new kube-dns packages are expected after 1.40.
  • The ipvs mode of kube-proxy is deprecated in 1.37: the plan is to disable it by default by 1.40 and remove it by 1.43.
  • The --filename (-f) flag of kubectl run is deprecated: a Pod is built from command-line arguments only anyway.
  • Static Pods can no longer reference a Secret or a ConfigMap: the bug has been fixed and the PreventStaticPodAPIReferences feature gate has been removed.
  • cgroup v1: since 1.35, kubelet does not start by default on nodes with cgroup v1. Temporarily this can be turned off with failCgroupV1: false, but move to cgroup v2 — support for v1 will be removed.

To find out which mode kube-proxy runs in:

bashon your machine
kubectl -n kube-system get configmap kube-proxy \  -o jsonpath='{.data.config\.conf}' | grep 'mode:'

Security updates

IdentifierWhat is affectedFixed in
CVE-2026-76654kubelet on Windows nodes: a subPath pointing to a network share leaks the NTLM hash of the kubelet account1.37.1, 1.36.5, 1.35.9, 1.34.12
CVE-2026-2270kube-controller-manager: write access to StatefulSet and ControllerRevision allows creating a Pod in another namespace1.37.1, 1.36.5, 1.35.9, 1.34.12
CVE-2026-19444kubectl cp on Windows: files from a malicious container are written to an arbitrary path1.36.5, 1.35.9, 1.34.12

How to upgrade

  1. Upgrade all components to the latest patch release of the current minor branch.
  2. Upgrade kube-apiserver to the next minor version. Skipping a minor version is not allowed even in a cluster with a single API server.
  3. Upgrade kube-controller-manager, kube-scheduler and cloud-controller-manager — in any order.
  4. Upgrade the nodes: evict Pods from the node with kubectl drain, upgrade kubelet and kube-proxy, and return the node to service.
  5. Check kubectl: it must be no more than one minor version away from the new kube-apiserver.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Kubernetes” topic
13 sections
Another reference · DevOps & cloud

Docker

Verified 31 Oct
All references · 61