CodeBlanks Logo Icon CodeBlanks

Label selector

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 immutable

Practice 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

terminal
# buraya yaz

Sample solution

terminal
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.

Question
selector:
  ____:
    - key: ortam
      operator: In
      values: [prod, staging]
Answer
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

All lessons in Intermediate