The API and the loopLesson 5 of 8
- Desired state and the reconcile loop, not reconciled
- Control plane and nodes, not reconciled
- API machinery: groups, versions and resource versions, not reconciled
- kubectl and kubeconfig, not reconciled
- Namespaces, labels and annotations, not reconciled
- Declarative management and server-side apply, not reconciled
- Owners, finalizers and garbage collection, not reconciled
- Custom resources and operators, not reconciled
Namespaces, labels and annotations
Namespaces scope names and policy, labels identify objects so that selectors can find them, and annotations carry everything else. Most of the wiring between Kubernetes objects is a label selector.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
A cluster holds thousands of objects, and almost none of them refer to each other by name. A Service does not list its pods; a Deployment does not keep a roster of the pods it runs. Each one carries a selector, a query over labels, and the API answers it. Namespaces decide which objects a query can see and which policy applies to them. Annotations hold the metadata that nothing selects on.
Reconcile, in 8 scenes
Namespaces scope names and policy
A namespaceA named scope inside one cluster. A namespaced object is identified by its kind, its namespace and its name, and most per-team policy attaches to the namespace. exists so that two teams can each have a Service called api. The API server stores and serves namespaced objects under the namespace in their path, /api/v1/namespaces/shop/services/api, so names only need to be unique per kind inside one namespace.
Policy hangs off the same boundary:
- RBAC. A Role and its RoleBinding grant rights inside one namespace.
- Quotas and defaults. A ResourceQuota caps the total requests, limits, storage and object counts in a namespace; a LimitRange sets per-container defaults and bounds.
- Pod Security Admission. Labels on the namespace choose which Pod Security Standard its pods must meet.
- NetworkPolicy. A policy selects pods in its own namespace and nowhere else.
Some kinds have no namespace because they describe the cluster as a whole: Nodes, PersistentVolumes, StorageClasses, ClusterRoles and ClusterRoleBindings, PriorityClasses, CustomResourceDefinitions, and Namespaces themselves. The API server reports the scope of every kind it serves:
kubectl api-resources --namespaced=false
NAME SHORTNAMES APIVERSION NAMESPACED KIND namespaces ns v1 false Namespace nodes no v1 false Node persistentvolumes pv v1 false PersistentVolume clusterrolebindings rbac.authorization.k8s.io/v1 false ClusterRoleBinding clusterroles rbac.authorization.k8s.io/v1 false ClusterRole priorityclasses pc scheduling.k8s.io/v1 false PriorityClass storageclasses sc storage.k8s.io/v1 false StorageClass
Pairs straddle the line. A PersistentVolumeClaim is namespaced and binds a cluster-scoped PersistentVolume. A Role is namespaced and a ClusterRole is not, though a RoleBinding can grant a ClusterRole’s rules inside one namespace.
Every cluster starts with default, kube-system (control plane add-ons), kube-public (readable by everyone, by convention) and kube-node-lease (one heartbeat Lease per node); kind adds local-path-storage for its volume provisioner. The kube- prefix is reserved for the system. Namespace names must be RFC 1123 DNS labels because they become part of Service names: api resolves inside its own namespace, and api.payments.svc.cluster.local resolves from anywhere. Do not create a namespace named after a public top-level domain such as com; Services in it would shadow public DNS names for every pod that looks up a name without a trailing dot.
kubectl sends a namespaced request to the namespace set in your context unless you pass -n, and -A lists across every namespace. Deleting a namespace deletes everything in it. That makes a namespace a convenient unit of cleanup and a dangerous one; the lesson on owners and finalizers covers what runs during that deletion and what makes it stall.
Policy attaches to the namespace
A namespace with its policy usually arrives as one manifest:
apiVersion: v1
kind: Namespace
metadata:
name: payments
labels:
team: payments
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/warn: restricted
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-and-storage
namespace: payments
spec:
hard:
requests.cpu: "8"
requests.memory: 16Gi
standard.storageclass.storage.k8s.io/requests.storage: 50Gi
count/deployments.apps: "20"
The pod-security.kubernetes.io/<mode> labels configure the built-in Pod Security Admission controller: enforce rejects pods that break the level, audit records them, warn returns a warning to the client, and the levels are privileged, baseline and restricted. Optional <mode>-version labels pin the standard to a Kubernetes minor. Pod Security Admission is stable since Kubernetes 1.25, the release that removed PodSecurityPolicy; clusters running 1.25 or later have no PodSecurityPolicy API. For rules beyond the standards, start with the built-in ValidatingAdmissionPolicy (CEL rules, GA in 1.30) and MutatingAdmissionPolicy (GA in 1.36); Gatekeeper and Kyverno remain options when you need image verification or generated resources.
A quota key per StorageClass has the form <class>.storageclass.storage.k8s.io/requests.storage, as above for kind’s standard class. Once a quota tracks a compute resource, every pod created in the namespace must declare that resource or the API server rejects it, but only that resource: a quota on requests.cpu demands CPU requests and says nothing about memory limits, and object-count quotas such as count/deployments.apps demand nothing of pods at all. A LimitRange can fill in defaults so that pods without explicit requests are not rejected.
Labels identify
A labelA key/value pair in metadata.labels that identifies an object so that selectors can find it. is short on purpose. A key is an optional prefix, which must be a DNS subdomain of at most 253 characters, then /, then a name of at most 63 characters (letters, digits, -, _ and ., starting and ending with a letter or digit). A value is at most 63 characters and may be empty. The prefixes kubernetes.io/ and k8s.io/ belong to Kubernetes components; keys without a prefix are yours.
The API server evaluates selectors on lists and watches, so kubectl get pods -l app=web returns only matching pods rather than downloading every pod in the namespace for kubectl to filter. Labels are mutable, and that is a feature. Change a pod’s labels so that its ReplicaSet and Service no longer select it, and the ReplicaSet starts a replacement while the old pod keeps running, out of the traffic path, for you to debug.
Selector syntax
A label selectorA set of requirements over labels. An object matches when it meets every requirement. has two families of requirement. Equality-based requirements compare one value; set-based ones test membership or presence:
| Requirement | Matches |
|---|---|
app=web or app==web | app is web |
tier!=cache | tier is anything but cache, including no tier label |
env in (prod,staging) | env is prod or staging |
env notin (dev) | env is not dev, including no env label |
canary | the key canary exists, with any value |
!canary | the key canary does not exist |
Commas join requirements with AND. There is no OR between different keys; in gives you OR within one key. The rows about missing keys catch people who know the basics:
kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS cache 1/1 Running 0 30s app.kubernetes.io/name=redis,tier=cache debug 1/1 Running 0 30s <none> web 1/1 Running 0 30s app.kubernetes.io/name=web,tier=frontend
kubectl get pods -l 'tier!=cache'
NAME READY STATUS RESTARTS AGE debug 1/1 Running 0 30s web 1/1 Running 0 30s
kubectl get pods -l 'tier,tier!=cache'
NAME READY STATUS RESTARTS AGE web 1/1 Running 0 30s
Quote selectors on the command line: ! and parentheses mean something to your shell.
In a manifest, matchLabels is a map of equality requirements and matchExpressions a list of set-based ones with the operators In, NotIn, Exists and DoesNotExist. Both may appear, and every requirement from both must hold:
apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout
labels:
app.kubernetes.io/name: checkout
app.kubernetes.io/instance: checkout-eu
app.kubernetes.io/version: "4.2.0"
app.kubernetes.io/component: api
app.kubernetes.io/part-of: payments
app.kubernetes.io/managed-by: kubectl
spec:
replicas: 2
selector:
matchLabels:
app.kubernetes.io/name: checkout
matchExpressions:
- key: app.kubernetes.io/instance
operator: In
values: [checkout-eu]
template:
metadata:
labels:
app.kubernetes.io/name: checkout
app.kubernetes.io/instance: checkout-eu
app.kubernetes.io/version: "4.2.0"
app.kubernetes.io/component: api
app.kubernetes.io/part-of: payments
annotations:
payments.example.com/runbook: https://runbooks.example.com/checkout
spec:
containers:
- name: checkout
image: ghcr.io/kx-labs/web:1.0.0
ports:
- containerPort: 8080
Not every selector field accepts both forms. A Service’s spec.selector is a plain map: equality only. An empty selector also means different things in different places. A NetworkPolicy with podSelector: {} selects every pod in its namespace; a Service with no selector gets no EndpointSlices from the control plane, which is how you point a Service at addresses you manage yourself; a Deployment must have a non-empty selector that matches its own template labels, or the API server rejects it.
Who selects whom
| Object | Field | Selects | When the labels drift |
|---|---|---|---|
| Service | spec.selector | pods in its namespace | EndpointSlices go empty while every pod is healthy |
| Deployment, ReplicaSet, StatefulSet, DaemonSet | spec.selector | the pods it owns | a relabelled pod is released and replaced; a selector that misses the template is rejected at creation |
| NetworkPolicy | podSelector, peer podSelector and namespaceSelector | pods it isolates, peers it admits | traffic dropped, or admitted from the wrong place |
| PodDisruptionBudget | spec.selector | pods a drain must respect | drains evict pods it was meant to protect |
| Topology spread, pod affinity | labelSelector | pods counted for placement | spreading counts the wrong pods |
nodeSelector, node affinity | node labels | nodes | pods stay Pending |
Workload controllers do more than read their selector. A ReplicaSet adopts any pod that matches its selector and has no controller, and it counts that pod toward its replicas. Two controllers with overlapping selectors in one namespace fight over the same pods, so keep each selector unique to its workload.
The Service row is the one that pages people. A label migration renames the pods’ labels, the Service keeps selecting the old ones, and the symptom is an empty endpoint list in front of healthy pods. The incident linked from this lesson runs exactly that failure.
To check any selector, read it off its object and run it yourself as a query. What the query returns is what the controller sees. Here a Service selects both the stable pods and a canary, which is intended: four pods, four endpoints.
kubectl -n shop get service web -o jsonpath='{.spec.selector}'
{"app.kubernetes.io/name":"web"}kubectl -n shop get pods -l app.kubernetes.io/name=web -L track
NAME READY STATUS RESTARTS AGE TRACK web-7c8596584-bf2qv 1/1 Running 0 30s stable web-7c8596584-btgkd 1/1 Running 0 30s stable web-7c8596584-rmn2p 1/1 Running 0 30s stable web-canary-c76f8f88-97zr4 1/1 Running 0 30s canary
kubectl -n shop get endpointslices -l kubernetes.io/service-name=web
NAME ADDRESSTYPE PORTS ENDPOINTS AGE web-jr5kk IPv4 80 10.244.3.3,10.244.2.5,10.244.1.4 + 1 more... 30s
If the second command prints nothing, the Service has nothing to route to, however healthy the pods are. The EndpointSlice controller labels each slice with kubernetes.io/service-name, which is itself a selector you can run.
Recommended labels
Kubernetes documents a shared vocabulary under the app.kubernetes.io/ prefix so that dashboards, cost tools and kubectl plugins can read workloads they did not create:
| Key | Meaning | Example |
|---|---|---|
app.kubernetes.io/name | the application | checkout |
app.kubernetes.io/instance | this installation of it | checkout-eu |
app.kubernetes.io/version | the running version | 4.2.0 |
app.kubernetes.io/component | its role in the architecture | api |
app.kubernetes.io/part-of | the larger system it belongs to | payments |
app.kubernetes.io/managed-by | the tool that manages it | Helm |
Select on name and instance. Let the others describe.
Annotations describe
An annotationA key/value pair in metadata.annotations for metadata that nothing selects on: tool state, configuration hints and notes for people. uses the same key syntax as a label, but its value can be any string, including JSON or several lines, up to 256 KiB for all of an object’s annotations together. The API server cannot select on annotations.
Annotations you will meet:
kubernetes.io/change-causerecords why a Deployment changed;kubectl rollout historyprints it.kubectl.kubernetes.io/last-applied-configurationis the copy of your manifest thatkubectl applykeeps for its next merge.deployment.kubernetes.io/revisionis written by the Deployment controller.- A checksum of a ConfigMap, placed in the pod template, forces a rollout when the configuration changes, because any change to the template does.
- Controllers read settings from annotations, such as the ones a load balancer controller reads from a Service.
The rule of thumb: if anything will ever select on it, it is a label; if it is for a tool or a person, or too long for 63 characters, it is an annotation.
kubectl annotate deployment checkout kubernetes.io/change-cause="raise replicas for the sale"
Field selectors
Labels describe what an object is. Some questions are about its state, such as which node a pod landed on or whether it finished. A field selectorA filter on the object fields that the API server supports for that kind, passed with --field-selector. answers those. Every kind supports metadata.name and metadata.namespace; pods add spec.nodeName, spec.restartPolicy, spec.schedulerName, spec.serviceAccountName, spec.hostNetwork, status.phase, status.podIP, status.podIPs and status.nominatedNodeName. Only =, == and != work, commas chain requirements, and the API server refuses a field it does not support:
kubectl -n shop get pods --field-selector status.phase=Succeeded
NAME READY STATUS RESTARTS AGE seed-catalog 0/1 Completed 0 30s seed-prices 0/1 Completed 0 30s
kubectl -n shop get pods --field-selector spec.nodeName=kx-worker2,status.phase=Running
NAME READY STATUS RESTARTS AGE web-7c8596584-btgkd 1/1 Running 0 30s
kubectl -n shop get pods --field-selector metadata.labels.tier=cache
Error from server (BadRequest): Unable to find {"" "v1" "pods"} that match label selector "", field selector "metadata.labels.tier=cache": field label not supported: metadata.labels.tierTypical uses are the pods on a node before you drain it, completed pods to clean up (kubectl delete pods --field-selector status.phase=Succeeded), and the events for one object (--field-selector involvedObject.name=checkout). Custom resources expose extra selectable fields through selectableFields in their definition, stable since Kubernetes 1.32.
The namespace name label
The control plane sets the label kubernetes.io/metadata.name on every namespace, with the namespace’s name as its value; the feature is stable since Kubernetes 1.22. The label is immutable in practice: an update that changes it is accepted, and the API server writes the name back.
kubectl get namespaces --show-labels
NAME STATUS AGE LABELS default Active 60s kubernetes.io/metadata.name=default kube-node-lease Active 60s kubernetes.io/metadata.name=kube-node-lease kube-public Active 60s kubernetes.io/metadata.name=kube-public kube-system Active 60s kubernetes.io/metadata.name=kube-system local-path-storage Active 60s kubernetes.io/metadata.name=local-path-storage shop Active 30s kubernetes.io/metadata.name=store
kubectl label namespace default kubernetes.io/metadata.name=prod --overwrite
namespace/default labeled
kubectl get namespace default --show-labels
NAME STATUS AGE LABELS default Active 60s kubernetes.io/metadata.name=default
This matters because a namespaceSelector matches namespace labels, never names. A policy that selects name: monitoring depends on someone having labelled the namespace that way; if nobody did, the selector matches nothing and the traffic it was meant to admit is dropped. The automatic label always exists and always equals the name:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: checkout-from-monitoring
namespace: payments
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: checkout
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
podSelector:
matchLabels:
app.kubernetes.io/name: prometheus
ports:
- port: 8080
The same label works anywhere a namespace selector appears, such as the namespaceSelector of an admission webhook or a ValidatingAdmissionPolicyBinding that should skip kube-system.
kubectl --context kind-kx create namespace storekubectl --context kind-kx -n store create deployment web --image=nginx:1.30 --replicas=3kubectl --context kind-kx -n store create deployment cache --image=redis:8.10kubectl --context kind-kx -n store label deployment web tier=frontendkubectl --context kind-kx -n store get pods --show-labelskubectl --context kind-kx -n store get pods -l 'app in (web,cache)' -L appkubectl --context kind-kx get pods -A --field-selector spec.nodeName=kx-worker2kubectl --context kind-kx get namespaces -l kubernetes.io/metadata.name=storekubectl --context kind-kx delete namespace store
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Labelling the Deployment does not label its pods: the pods take their labels from the pod template, which kubectl create deployment fills with app=<name>.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Write equality-based and set-based label selectors and predict which objects match. (not yet met)
- Say which kinds are namespaced and which are cluster-scoped. (not yet met)
- Choose between a label and an annotation for a piece of metadata. (not yet met)
- Select namespaces by the automatic kubernetes.io/metadata.name label. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 6. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 6 corrections
The notes saidPolicy enforcement 'through admission controllers. Tools like OPA Gatekeeper and Kyverno'
CorrectedTeach the built-ins first: Pod Security Admission (GA 1.25), ValidatingAdmissionPolicy with CEL (GA 1.30) and MutatingAdmissionPolicy (alpha 1.30, beta 1.34 to 1.35, GA 1.36). Gatekeeper and Kyverno (v1.20.0) remain options for richer policy, image verification and generation.
The notes saidQoS classes determined only by container-level requests/limits
CorrectedPod-level resources (spec.resources; PodLevelResources beta and on by default since 1.34, still beta in 1.37) also feed QoS: with pod-level CPU and memory requests equal to limits the pod is Guaranteed. In-place pod resize is GA in 1.35 (in-place resize of pod-level resources is beta in 1.36); a resize must keep the pod's original QoS class.
The notes said'Pod security standards… can be enforced'
CorrectedEnforcement is the built-in Pod Security Admission controller (GA 1.25), configured with namespace labels pod-security.kubernetes.io/enforce|audit|warn: privileged|baseline|restricted (plus optional -version labels). PodSecurityPolicy was removed in 1.25.
Sourcekubernetes.io/docs/concepts/security/pod-security-admission
The notes saidPer-StorageClass quota key 'requests.storage.standard: "50Gi"'
CorrectedThe key is <storage-class-name>.storageclass.storage.k8s.io/requests.storage, for example standard.storageclass.storage.k8s.io/requests.storage: 50Gi (and <class>.storageclass.storage.k8s.io/persistentvolumeclaims for counts).
Sourcekubernetes.io/docs/concepts/policy/resource-quotas#storage-resource-quota
The notes said'When quotas are enabled, pods must specify resource requests and limits'
CorrectedOnly resources the quota actually tracks must be specified: a quota on requests.cpu requires CPU requests but not memory limits, and object-count quotas require nothing. A LimitRange can inject defaults so pods are not rejected.
The notes said'kubelet evicts pods starting with BestEffort, then Burstable, then Guaranteed…'
CorrectedNode-pressure eviction ranks pods by (1) whether usage of the starved resource exceeds requests, (2) Pod priority, (3) usage relative to requests. QoS class is not the ranking key; it falls out of the first criterion (BestEffort/Burstable over requests go first), and priority is a major factor the note omits.
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/overview/working-with-objects/namespaces
- kubernetes.io/docs/concepts/overview/working-with-objects/labels
- kubernetes.io/docs/concepts/overview/working-with-objects/common-labels
- kubernetes.io/docs/concepts/overview/working-with-objects/annotations
- kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors
- kubernetes.io/docs/concepts/services-networking/network-policies
- kubernetes.io/docs/concepts/security/pod-security-admission
- kubernetes.io/docs/concepts/policy/resource-quotas
- kubernetes.io/docs/concepts/workloads/pods/pod-qos
- kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction
- kubernetes.io/docs/reference/access-authn-authz/validating-admission-policy
Namespaces, labels and annotations
↓ ↑ step, 1 to 8 scene, Esc leave