K8s by Example: Labels & Selectors
| Labels are key-value pairs attached to resources. They’re the foundation of loose coupling in Kubernetes. Services find Pods, Deployments manage ReplicaSets, and NetworkPolicies target Pods, all through label selectors. |
| pod-labels.yaml | |
| Labels go in the | |
| Add version and environment labels for filtering and deployment strategies. | |
| recommended-labels.yaml | |
| Use recommended labels from Kubernetes documentation for consistency. These enable tooling integration, cost allocation, and monitoring dashboards. | |
| Organizational labels: | |
| selector.yaml | |
| Label selectors use AND logic. For a Pod to match, it must have ALL specified labels. | |
| Pods can have extra labels. Only the selector’s labels need to match. | |
| match-expressions.yaml | |
| Two selector types: | |
| Operators: | |
| labels-vs-annotations.yaml | |
| Labels are for selection and grouping (queryable). Use labels for anything you need to filter on. | |
| Annotations are for metadata that tools consume (not queryable). Store descriptions, owners, and tool config here. | |
| terminal | |
| Use | |
| terminal | |
| Set-based selectors use | |
| terminal | |
| Use | |
| terminal | |
| Add or modify labels with | |
| terminal | |
| Warning: changing labels on running Pods can break Service routing or cause Deployments to create new Pods. The Pod becomes orphaned from its Deployment. | |