Exercise 3: Labels

In this Exercise, you will create a pod that has labels associated with it. Labels make it easy to filter the pods later. Labels play a vital role in the Kubernetes ecosystem, so it’s important to understand their proper usage.

Task 1 - Assign A New Label To A Running Pod

  1. Assign a new label (key=value) pair to a running pod. This comes in handy when you are troubleshooting an issue and would like to distinguish between different pod(s). Assign a new label health=fair to the pod nginx-pod, which is already running.

    kubectl label pod nginx-pod health=fair
    kubectl label pod nginx-pod health=fair
  2. Use kubectl get pods to show the labels of running pods

    Hint

    You’ve used the relevant switch on kubectl get pods recently.

    Solution
    kubectl get pods nginx-pod --show-labels
    kubectl get pods nginx-pod --show-labels

Task 2 - Update An Existing Label That Is Assigned To A Running Pod

  1. Use kubectl to update the value of an existing label on a running pod. Change the value of the label kind=web to kind=db of the nginx-pod pod.

    Hint

    You’ve recently used the label sub-command for kubectl to label a pod. What happens if you try that again here?

    Solution
    kubectl label pod nginx-pod kind=db --overwrite
    kubectl label pod nginx-pod kind=db --overwrite
    Note

    --overwrite is needed to replace the existing label value.

  2. Show the pod labels again. Notice that kind has changed from web to db.

    kubectl get pods --show-labels
    kubectl get pods --show-labels

Task 3 - Delete A Label That Is Assigned To A Running Pod

  1. Delete the health label from the nginx-pod pod.

    Hint

    How might you expect to delete a pod label, given you are already aware of the kubectl label pod subcommand?

    Solution
    kubectl label pod nginx-pod health-
    kubectl label pod nginx-pod health-
    Note

    The actual command is probably slightly different from what you were expecting. Notice the hyphen (-) at the end of the command. You can also remove a label from all running pods by using the --all flag.

  2. Run the command below to show the pod labels again. Notice that the health label is no longer included on the list of labels.

    kubectl get pods --show-labels
    kubectl get pods --show-labels

Task 4 - Delete Pods Based On Their Labels

  1. Delete all the pods that have the target label with value dev.

    Hint

    You’ve already used the kubectl delete pod command to delete a pod, so how might you modify this command to target only pods that match a certain label?

    Solution
    kubectl delete pod -l target=dev
    kubectl delete pod -l target=dev