CodeBlanks Logo Icon CodeBlanks

Service selector

Learn to select Pods with a Service selector.

Service selector

A Service's selector matches pod labels; it has nothing to do with the deployment's name. This allows powerful patterns: if the pods of two versions carry the same label, traffic spreads over both; changing the label switches traffic to one version (blue-green deployment):

# blue: app=web, surum=v1    green: app=web, surum=v2
spec:
  selector:
    app: web
    surum: v2        # traffic only to v2

kubectl patch svc web -p '{"spec":{"selector":{"app":"web","surum":"v1"}}}'   # go back

A service without a selector

If no selector is written, Kubernetes doesn't fill in the endpoints automatically. This is used to reach a database outside the cluster from inside with a stable name; or the ExternalName type gives a DNS alias:

apiVersion: v1
kind: Service
metadata:
  name: dis-db
spec:
  type: ExternalName
  externalName: db.sirket.com     # dis-db -> db.sirket.com (CNAME)

Practice A version-based selector

Write a Service YAML: name web; a selector with two labels: app: web and surum: v2; port port: 80, targetPort: 8080.

Starter code

terminal
# buraya yaz

Sample solution

terminal
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
    surum: v2
  ports:
    - port: 80
      targetPort: 8080

Expected output

service/web created

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If a Service selector has several labels, what is needed for a pod to be selected?

  • Carrying none of them
  • Carrying all of the labels Correct answer
  • Carrying any one of them
  • Carrying the first label

Explanation: The labels are combined with AND.

2 Change the service's selector in place.

Question
kubectl ____ svc web -p '{"spec":{"selector":{"app":"web","surum":"v1"}}}'
Answer
kubectl patch svc web -p '{"spec":{"selector":{"app":"web","surum":"v1"}}}'

Explanation: patch changes part of an object.

3 Match.

Term Meaning
selector Matches pod labels
multiple labels Combined with AND
blue-green Traffic switch by label
ExternalName DNS alias

All lessons in Intermediate