Label selector
- Docker & Kubernetes course
- Intermediate
- Lesson 63/82
- 4 min
Learn to select resources with label selectors.
Label selector
A selector is a query selecting objects by label. Objects like Service, Deployment, ReplicaSet and NetworkPolicy select pods with a selector. In a Deployment there are two forms:
selector:
matchLabels: # equality: all must hold
app: web
matchExpressions: # set operations
- key: ortam
operator: In
values: [prod, staging]A Service's selector supports only plain equality (app: web).
A Deployment selector is immutable
After a Deployment is created, spec.selector can't be changed; otherwise it would break its link with the old pods. If the selector must change, the deployment is deleted and recreated. That is why only permanent labels (app) go in the selector; changing labels like the version are added to the template but not to the selector.
$ kubectl apply -f web.yaml
The Deployment "web" is invalid: spec.selector: Invalid value: ... field is immutablePractice A mixed selector
Write a Deployment's selector section (starting with selector:): app: web under matchLabels; key: ortam, operator: In, values: [prod, staging] under matchExpressions.
Starter code
# buraya yazSample solution
selector:
matchLabels:
app: web
matchExpressions:
- key: ortam
operator: In
values: [prod, staging]Expected output
deployment.apps/web created
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When matchLabels and matchExpressions are written together, when is a pod selected?
- When either holds
- Only matchLabels is checked
- It errors
- When the conditions of both hold Correct answer
Explanation: All conditions combine with AND.
2 Write the set-based condition.
selector:
____:
- key: ortam
operator: In
values: [prod, staging]
selector:
matchExpressions:
- key: ortam
operator: In
values: [prod, staging]
Explanation: matchExpressions takes a key, an operator and a value list.
3 Match.
| Term | Meaning |
|---|---|
matchLabels |
Equality conditions |
matchExpressions |
Set conditions |
Service selector |
Equality only |
spec.selector (Deployment) |
Immutable |