Label
Why Are Labels Required?
As resources increase, how to classify and manage resources becomes important. Kubernetes provides a mechanism to classify resources, that is, using labels. Labels are simple but powerful. Almost all resources in the Kubernetes can be organized by labels.
A label is a key-value pair, which can be set when a resource is created, or can be added or modified later.
Taking pods as an example, as the number of pods increases, pods become cluttered and difficult to manage, as shown in the following figure.
If we attach different labels to the pods, the situation is totally different, as shown in the following figure.
Adding a Label
A label is a key-value pair. As shown below, two labels app=nginx and env=prod are set for a pod.
apiVersion: v1 kind: Pod metadata: name: nginx labels: # Add the following two labels to the pod. app: nginx env: prod spec: containers: - image: nginx:latest name: container-0 resources: limits: cpu: 500m memory: 1024Mi requests: cpu: 500m memory: 1024Mi imagePullSecrets: - name: imagepull-secret
When a pod has labels, you can view the label of the pod by using --show-labels when querying the pod.
$ kubectl get pod --show-labels -n $namespace_name NAME READY STATUS RESTARTS AGE LABELS nginx 1/1 Running 0 50s app=nginx,env=prod
You can also use -L to query only certain labels.
$ kubectl get pod -L app,env -n $namespace_name NAME READY STATUS RESTARTS AGE APP ENV nginx 1/1 Running 0 1m nginx prod
For an existing pod, you can directly run the kubectl label command to add a label.
$ kubectl label po nginx creation_method=manual -n $namespace_name pod "nginx" labeled $ kubectl get pod --show-labels -n $namespace_name NAME READY STATUS RESTARTS AGE LABELS nginx 1/1 Running 0 50s app=nginx,env=prod,creation_method=manual
Modifying a Label
If you want to modify an existing label, you need to add --overwrite to the command, as shown below:
$ kubectl label po nginx env=debug --overwrite -n $namespace_name pod "nginx" labeled $ kubectl get pod --show-labels -n $namespace_name NAME READY STATUS RESTARTS AGE LABELS nginx 1/1 Running 0 50s app=nginx,env=debug,creation_method=manual
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot