k8s.github.io

Labels and Selectors

In this section, we will take a look at Labels and Selectors

Labels and Selectors are standard methods to group things together.

Labels are properties attached to each item.

labels-ckc

Selectors help you to filter these items

sl

How are labels and selectors are used in kubernetes?

How do you specify labels?

    apiVersion: v1
    kind: Pod
    metadata:
     name: simple-webapp
     labels:
       app: App1
       function: Front-end
    spec:
     containers:
     - name: simple-webapp
       image: simple-webapp
       ports:
       - containerPort: 8080

lpod

Once the pod is created, to select the pod with labels run the below command

$ kubectl get pods --selector app=App1

Kubernetes uses labels to connect different objects together

    apiVersion: apps/v1
    kind: ReplicaSet
    metadata:
      name: simple-webapp
      labels:
        app: App1
        function: Front-end
    spec:
     replicas: 3
     selector:
       matchLabels:
        app: App1
     template:
       metadata:
         labels:
           app: App1
           function: Front-end
       spec:
         containers:
         - name: simple-webapp
           image: simple-webapp   

lrs

For services

  ```
  apiVersion: v1
  kind: Service
  metadata:
   name: my-service
  spec:
   selector:
     app: App1
   ports:
   - protocol: TCP
     port: 80
     targetPort: 9376 
   ```   ![lrs1](/k8s.github.io/images/lrs1.PNG)

Annotations

K8s Reference Docs: