What are labels & selectors in Kubernetes (k8s)?

In Kubernetes, labels are metadata that can be added to objects in the cluster, such as pods, services, and deployments. Labels are key-value pairs that are stored in the object’s metadata and are used by the Kubernetes control plane to identify and manage objects in the cluster.

Labels are intended to be used to store information that is relevant to the object, and that is used by the control plane to manage the object. They can be used to store information such as:

  • The name or type of the object
  • The environment or environment type that the object is used in (e.g. development, staging, production)
  • The version or revision number of the object
  • Custom tags or labels that are used to group or classify the object

Selectors are used in Kubernetes to filter and group objects in the cluster based on their labels. Selectors can be used to select a subset of objects in the cluster based on their labels, and are often used in conjunction with other Kubernetes features, such as Replication Controllers and Services, to manage and orchestrate the objects in the cluster.

Here are a few examples of how labels and selectors can be used in Kubernetes:

  • Labeling an object with the name and type of the object:
metadata:
  labels:
    name: my-app
    type: web
  • Labeling an object with the environment and environment type:
metadata:
  labels:
    environment: staging
    type: development
  • Labeling an object with the version or revision number:
metadata:
  labels:
    version: v1.2.3
  • Using a selector to select a subset of objects based on their labels:
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    name: my-app
    type: web
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

In this example, the service will select all pods that have the name: my-app and type: web labels, and will create a service that exposes those pods to the rest of the cluster.

Labels and selectors are a powerful and flexible way to manage and orchestrate objects in a Kubernetes cluster. They can be used to filter and group objects based on their metadata, and are often used in conjunction with other Kubernetes features, such as Replication Controllers and Services, to manage and orchestrate the objects in the cluster.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *