Sobes.tech
Junior

What is a selector?

sobes.tech AI

Answer from AI

A selector in the context of Kubernetes (and not only) is a label (or set of labels) used to select (filter) specific resources. It allows linking resources to each other based on their metadata.

Applications of selectors in Kubernetes:

  • Pod Selector in Deployment/ReplicaSet: Defines which pods are managed by this controller.
  • Service Selector: Indicates which pods will receive traffic directed to the service.
  • Node Selector in Pod Specification: Defines the cluster nodes on which the pod can be run.
  • NetworkPolicy Selector: Used to apply network policies to specific pods or namespaces.
  • ResourceQuota Scope Selector: Can limit resource quotas for specific objects.

Example of Pod Selector in Service YAML:

// Service definition
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app // Selector: the service will direct traffic to pods with the label app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

Example of Pods with corresponding labels:

// Pod definition 1
apiVersion: v1
kind: Pod
metadata:
  name: my-app-pod-1
  labels: // Pods with these labels will be selected by the service
    app: my-app
    version: v1
spec:
  containers:
  - name: my-container
    image: my-image

// Pod definition 2 (also will be selected by the service)
apiVersion: v1
kind: Pod
metadata:
  name: my-app-pod-2
  labels:
    app: my-app
    env: production
spec:
  containers:
  - name: my-container
    image: my-image

Selectors come in two types:

  • Equality-based: Based on exact match of key and/or value. Operator examples: =, ==, !=.
  • Set-based: Use sets of values. Operator examples: in, notin, exists (check for key presence), !exists (check for key absence).

Example of a Set-based selector:

// Select pods with label "environment" with value "production" or "staging"
selector:
  matchLabels:
    app: frontend
  matchExpressions: // Set-based expression
    - key: environment
      operator: In
      values:
        - production
        - staging

// Select pods that do not have the label "beta"
selector:
  matchExpressions:
    - key: beta
      operator: DoesNotExist

Thus, selectors are a fundamental mechanism in Kubernetes for ensuring connections and managing resources based on their metadata.