liveBook · Manning

Label selector

As explained in Kubernetes for Developers

A label selector field is a Kubernetes resource field that identifies matching objects according to their labels.

A label selector identifies Kubernetes objects by their labels—arbitrary key-value pairs attached to those objects. It lets a Deployment identify the Pods it manages and a Service identify the Pods that receive traffic. The Service selects Pods directly; it does not reference or need to know about their Deployment. section 3.2.4 section 3.2.5

Match a Deployment to its Pods

A Deployment can set `spec.selector.matchLabels` to `pod: timeserver-pod` and give the same label to Pods in `spec.template.metadata.labels`. Although the Pod template sits inside the Deployment, the resulting Pods exist as separate objects. The matching label is the link between them. section 3.2.4 section 3.2.7

A Service can select those same Pods with `spec.selector: {pod: timeserver-pod}`. Unlike the Deployment selector, this form has no `matchLabels` subsection; both forms identify the relevant set of Pods. Keeping the Pod label consistent lets the Deployment manage them while the Service directs traffic to them. section 3.2.5 section 3.2.4

Selectors are also useful during operation:

  • Inspect just the matching Pods with `kubectl get pods --selector=pod=timeserver-pod`, rather than listing every Pod in the namespace. section 3.2.7
  • For a blue/green rollout, label the two versions differently. Update the inactive Deployment, wait for its rollout, then change the Service selector to the new version’s Pod label to switch traffic. section 4.2.3

Selectors can also be combined with node labels, taints, and tolerations to keep workloads on suitable nodes or separate from other workloads. section 8.4

How Kubernetes for Developers covers it

How deep it goes
Explains matching labels through Deployment and Service YAML and a kubectl query, without detailing selector internals.
Examples
Uses a timeserver Deployment and Service sharing a Pod label, a filtered kubectl query, and a blue/green traffic switch.
What it assumes
Introduces labels as arbitrary key-value pairs while using Pod, Deployment, and Service manifests as practical context.
What you can do after
Operate/configure it in Kubernetes YAML, query matching Pods with kubectl, and switch Service traffic between labeled versions.
How it connects
Connects labels and selectors to Pods, Deployments, Services, blue/green deployment, and node selection.

Also explained in

Compare how 7 books explain label selector →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kubernetes for Developers. The section links point to the parts of the book it draws on.