Kubernetes – Labels & Selectors

Kubernetes – Labels & Selectors

Labels

Labels are key-value pairs that are attached to pods, replication controllers,s and services. They are used as identifying attributes for objects such as pods and replication controllers. They can be added to an object at creation time and can be added or modified at the run time.

Labels are intended to be used to specify identifying attributes of objects that are meaningful and relevant to users but do not directly imply semantics to the core system. Labels can be used to organize and select subsets of objects. Labels can be attached to objects at creation time and subsequently added and modified at any time. Each object can have a set of key/value labels defined. Each Key must be unique for a given object.

"metadata": {
  "labels": {
    "key1" : "value1",
    "key2" : "value2"
  }
}

Labels allow for efficient queries and watches and are ideal for use in UIs and CLIs.

For example, here’s the configuration file for a Pod that has two labels environment: production and app: nginx :


apiVersion: v1
kind: Pod
metadata:
  name: label-demo
  labels:
    environment: production
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort: 80

 

Selectors

Labels do not provide uniqueness. In general, we can say many objects can carry the same labels. Labels selectors are core grouping primitive in Kubernetes. They are used by the users to select a set of objects.

Kubernetes API currently supports two types of selectors −

  • Equality-based selectors
  • Set-based selectors

Equality-based Selectors

They allow filtering by key and value. Matching objects should satisfy all the specified labels.

Set-based Selectors

Set-based selectors allow the filtering of keys according to a set of values.

apiVersion: v1
kind: Service
metadata:
   name: sp-neo4j-standalone
spec:
   ports:
      - port: 7474
      name: neo4j
   type: NodePort
   selector:
      app: salesplatform ---------> 1
      component: neo4j -----------> 2

In the above code, we are using the label selector as app: salesplatform and component as component: neo4j.

Once we run the file using the kubectl command, it will create a service with the name sp-neo4j-standalone which will communicate on port 7474. The ype is NodePort with the new label selector as app: salesplatform and component: neo4j.

 

Leave a Reply