Location>code7788 >text

K8s newbies series Label label and Label selector

Popularity:803 ℃/2025-05-04 11:20:03

Overview

Official website:/zh-cn/docs/concepts/overview/working-with-objects/labels/

In K8s, Label is the core mechanism used to identify and organize cluster resources (such as Pod, Service, Deployment, Node, etc.). Its main function is to add representations on various resources to distinguish and select them.

Features of Label

  • A Label will be attached to various objects in the form of key/value key-value pairs, such as Node, Pod, Service, etc.
  • A resource object can define any number of labels, and the same label can also be added to any number of resource objects.
  • Label is usually determined when the resource object is defined, and of course it can also be dynamically added or deleted after the object is created.

Label definition rules

Key definition rules

  • /and /The prefix is ​​reserved for Kubernetes core components.
  • Format: [Prefix/] Name
  • Prefix (optional): DNS subdomain format (such as /), no more than 253 characters.
  • Name: No more than 63 characters, letters, numbers, -, _, ., and must start and end with letters or numbers

Value definition rules

  • Must be 63 characters or less (can be empty)
  • Unless the label value is empty, it must start and end with an alphanumeric character ([a-z0-9A-Z])
  • Contains dashes (-), underscores (_), dots (.), letters or numbers

Label operation

Add a Label to a resource

Method 1: Specify in the resource list

Can be found in the resource fileSpecify the tag in . Take defining a Pod as an example:

# Create a Pod
 [root@master01 ~/label]# cat
 apiVersion: v1
 kind: Pod
 metadata:
   name: pod-label
   # Add label tag, the tag is defined in the form of key: value
   labels:
     app: nginx
 spec:
   containers:
   - name: nginx-container
     image: nginx
 [root@master01 ~/label]# kubectl apply -f
 pod/pod-label created

 # Verify that the definition is successful
 [root@master01 ~/label]# kubectl get pod pod-label --show-labels
 NAME READY STATUS RESTARTS AGE LABELS
 pod-label 1/1 Running 0 49s app=nginx

Method 2: Add Label directly to existing resources

grammar:

kubectl label pods <pod-name> <labelKey=value>

Example: Add a new label to the above created pod

# Add label
 [root@master01 ~/label]# kubectl label pods pod-label env=dev
 pod/pod-label labeled
 # Verify that the addition is successful
 [root@master01 ~/label]# kubectl get pod pod-label --show-labels
 NAME READY STATUS RESTARTS AGE LABELS
 pod-label 1/1 Running 0 4m10s app=nginx,env=dev

Modify the LabelValue specified in the resource

The Label Key cannot be modified, so it can only be deleted, or add a new Key to delete the original Key, forming the illusion of modification. Here we mainly explain the value of modifying the Label

grammar:

kubectl label pods <pod-name> <labelKey=value> --overwrite

Example: Modify the value of the env of the above Pod to prod

# Modify Label
 [root@master01 ~/label]# kubectl label pods pod-label env=prod --overwrite
 pod/pod-label labeled
 # Verify that the modification is successful
 [root@master01 ~/label]# kubectl get pod pod-label --show-labels
 NAME READY STATUS RESTARTS AGE LABELS
 pod-label 1/1 Running 0 12m app=nginx,env=prod

View Labels in the resource

Example:

# View the Label of the specified resource
 [root@master01 ~/label]# kubectl get pod --show-labels
 NAME READY STATUS RESTARTS AGE LABELS
 pod-label 1/1 Running 0 13m app=nginx,env=prod
 static-web-node02 1/1 Running 0 18m role=myrole

 # View the Label column of the specified resource
 [root@master01 ~/label]# kubectl get pod -L env,app
 NAME READY STATUS RESTARTS AGE ENV APP
 pod-label 1/1 Running 0 13m prod nginx
 static-web-node02 1/1 Running 0 18m

Delete Labels in Resources

grammar:

# Note that there is a "-" minus sign after labelKey
 kubectl label pods <pod-name> <labelKey>-

Example: Delete the label of the env in the above pod

# Delete Label
 [root@master01 ~/label]# kubectl label pod pod-label env-
 pod/pod-label unlabeled

 # Verify that the deletion is successful
 [root@master01 ~/label]# kubectl get pod pod-label --show-labels
 NAME READY STATUS RESTARTS AGE LABELS
 pod-label 1/1 Running 0 18m app=nginx

Label selector

Official website documentation:/zh-cn/docs/concepts/overview/working-with-objects/labels/#label-selectors

In Kubernetes, the Label Selector is the core mechanism used to filter and operate resources based on labels.
Two types of Label selectors are supported in Kubernetes

Equation selector

Filter resources by precisely matching the keys and values ​​of the tags, the following operators are supported:

  • =or==: Match the resource whose key is equal to the specified value
# Select all Pods containing the `env=prod` tag
 kubectl get pods -l env=prod
  • !=: Matching resources whose key value is not equal to the specified value
# Select all pods that do not contain the `tier=frontend` tag
 kubectl get pods -l tier!=frontend

Collection selector

Flexible filtering of resources through collection operators (such as in, notin, exists) supports more complex conditions.

  • in: The value of the specified key is in the specified collection
# Select `env` as a `prod` or `staging` pod
 kubectl get pods -l "env in (prod, staging)"
  • notin: The value of the key is not in the specified collection
kubectl get pods -l "env notin (frontend, backend)"
  • exists: key must exist (do not care about value)
# Select the Pod with the key that exists env
 kubectl get pods -l "env,app"
  • doesntexist: key must not exist
# Select a pod that does not contain the `tier` and `test` tags.
 # Notice!  !  !  Single quotes are needed here, and double quotes may cause bash to not parse
 kubectl get pods -l '!tier,!test'

Operation of K8s resources through Label

View specified resources through Label

grammar:

kubectl get <resource-type> -l <label-operation> -n <namespace>

Example:

# Check the Pod with label app=nginx
 [root@master01 ~/label]# kubectl get pod -l "app=nginx"
 NAME READY STATUS RESTARTS AGE
 pod-label 1/1 Running 0 37m

 # Check the pods of the specified Label under the calico-system namespace
 [root@master01 ~/label]# kubectl get po -l "/name" -n calico-system
 NAME READY STATUS RESTARTS AGE
 calico-kube-controllers-585c6db9c7-9wm4p 1/1 Running 1 (6d22h ago) 6d23h
 calico-node-64sq8 1/1 Running 0 22h
 calico-node-kgkmk 1/1 Running 0 22h
 calico-node-vn47d 1/1 Running 0 22h
 calico-typha-666d79c78b-65szp 1/1 Running 1 (6d22h ago) 6d23h
 calico-typha-666d79c78b-n9mjq 1/1 Running 1 (6d22h ago) 6d23h
 csi-node-driver-92w48 2/2 Running 4 (6d22h ago) 6d23h
 csi-node-driver-96tfv 2/2 Running 2 (6d22h ago) 6d23h
 csi-node-driver-wbf7v 2/2 Running 2 (6d22h ago) 6d23h

Delete resources via Label

grammar:

kubectl delete <resource-type> -l <label> -n <namespace>

Example:

# Delete Pods via label
 [root@master01 ~/label]# kubectl delete po -l "app=nginx"
 pod "pod-label" deleted

 # Verify that the deletion is successful
 [root@master01 ~/label]# kubectl get po pod-label
 Error from server (NotFound): pods "pod-label" not found

Use selectors in resource files

Example: Used in Deployment

In Deployment, it is used to select the target Pod. Commonly usedmatchLabelsormatchExpressions

apiVersion: apps/v1
 kind: Deployment
 metadata:
   name: nginx-deployment
 spec:
   selector:
     matchLabels:
       app: nginx # exact matching tag app=nginx
     matchExpressions: # Collection selector (optional)
       - {key: env, operator: In, values: [prod, staging]}
   template:
     metadata:
       labels:
         app: nginx
         env: prod
     # ... Pod configuration

Example: Used in Service

Service selects Pod via:

apiVersion: v1
 kind: Service
 metadata:
   name: nginx-service
 spec:
   selector:
     app: nginx # Select all pods containing the app=nginx tag
   Ports:
     - protocol: TCP
       port: 80
       targetPort: 9376

Label and Label selector usage scenarios

  • Batch operation resources: batch operation of resources that meet the conditions through the tag selector
  • Service discovery: Service connects Pods through selectors to realize dynamic traffic routing
  • Multi-dimensional grouping: manage resources according to business, environment, hierarchy and other multi-dimensional
  • Distinguish between new and old versions of Pods through tags and gradually switch traffic