A label selector is a query that finds Kubernetes resources whose labels match specified criteria. Services use selectors to discover destination Pods without tightly coupling the objects. section 15.2
A selector can model different relationships:
- No matching Pods means a Service has nowhere to forward traffic. section 15.2
- One matching Pod receives all traffic. section 15.2
- Multiple matching Pods receive distributed traffic because the Service acts as a load balancer. section 15.2
- Deployments use selectors to identify the Pods they manage and maintain the desired number of replicas. section 15.3
Find and route to the numbers API
A Pod can carry labels app: numbers and component: api. Query it with kubectl get po --selector app=numbers,component=api. A Service using the same selector identifies that Pod, adds its IP to the Service endpoints, and routes curl requests sent to the Service port. section 15.2
Listing 15.3 A Service spec with a selector to identify Pods
apiVersion: v1
kind: Service
metadata:
name: numbers-api
spec:
ports:
- port: 8015
targetPort: http
selector:
app: numbers
component: api
type: LoadBalancer
Inspect the Service YAML to see matching app and component labels expressed as a selector. section 15.2
Listing 15.4 Deployment spec that includes the templated Pod spec
apiVersion: v1
kind: Deployment
metadata:
name: numbers-api
spec: # this is the Deployment spec
replicas: 1 # the number of Pods to create
selector: # selector to find Pods
matchLabels:
app: numbers
component: api
template: # this is the template for creating Pods
metadata:
labels: # labels the Deployment selector uses
app: numbers
component: api
spec: # and this is the Pod spec
containers:
- name: api # full container spec snipped
Compare a Deployment selector with the labels in its Pod template; the selector must identify the Pods the Deployment creates. section 15.3






