Skip to content

Service selector and label matching

In Kubernetes, a Service is an abstraction that defines a logical set of Pods and a policy by which to access them. Services utilize a system of labels and selectors to decouple network exposure from the lifecycle of specific, ephemeral Pod instances.^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]

Function

Selectors are used to identify the subset of Pods that should receive traffic routed through the Service^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]. This mechanism addresses the volatility of Pod management; because Pods are non-permanent resources that may be dynamically created or destroyed, using direct methods like port-forward on a specific Pod would result in service interruption if that Pod terminates^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

By matching against labels, a Service automatically maintains network policies even as the underlying Pods change. When an old Pod is deleted and a new one is created, the new Pod retains the required labels and automatically inherits the exposure rules defined by the Service^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

Configuration

Label matching is configured within the spec section of a Service manifest.

Defining Labels

Pods are assigned key-value pairs in their metadata.labels section^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]. For example, the following YAML assigns two labels to a Pod named foo: * app: foo * type: demo^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]

Defining Selectors

The Service uses the spec.selector field to filter Pods^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]. The Service will route traffic to any Pod that possesses the matching labels. For instance, a Service configured with type: demo in its selector will route traffic to all Pods (like foo and bar) that share the label type: demo^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md].

  • Kubernetes
  • [[Pods]]
  • [[Load Balancing]]
  • [[Networking]]

Sources

^[400-devops-06-kubernetes-k8s-ithelp-day7-readme.md]