Label selectors are passed to
kubectl with --selector (or -l). Combine multiple selectors with commas, for example --selector env=prod,bu=finance. You can apply selectors to most kubectl get commands (e.g., pods, services, replicasets, or all).Quick reference: common selector commands
1) How many pods exist in the dev environment?
Assuming the environment label key is env and development is labeled dev, use the selector and count the returned lines. The --no-headers flag prevents the header row from being counted.
env=dev.
2) How many pods are in the finance business unit?
Use the bu label with value finance and the same counting technique:
bu=finance.
3) How many objects are in the prod environment (pods, ReplicaSets, services, etc.)?
To list every resource type in a namespace use kubectl get all. Add --selector to filter by label and --no-headers to make counting straightforward.
env=prod.
4) Identify the pod that is in prod, BU finance, and frontend tier
Combine the three selectors (comma-separated) so the command returns only objects matching all three labels:
app-1-zzxdf matches env=prod, bu=finance, and tier=frontend.
5) Fixing a ReplicaSet definition: selector does not match template labels
Kubernetes controllers (like ReplicaSet) requirespec.selector.matchLabels to match the labels on the pod template (spec.template.metadata.labels). If they differ, the API server will reject the manifest with a validation error because the controller cannot determine which Pods it should manage.
Problematic manifest (selector and template labels do not match):
selector.matchLabels is tier: front-end while the pod template labels are tier: nginx. They must be identical (or the selector must be a subset of the template labels).
Corrected manifest — make selector.matchLabels and template.metadata.labels identical (here we choose tier: nginx):
Pro tip: Always ensure
spec.selector.matchLabels is a subset of (or exactly equals) spec.template.metadata.labels. The pod template must include the selector labels so the controller can identify and adopt the pods. A mismatch results in a validation error and prevents creation.Additional resources
- Kubernetes labels and selectors: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
- ReplicaSet concept and fields: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/
- kubectl reference: https://kubernetes.io/docs/reference/kubectl/overview/