Skip to main content
In this lesson, we explore practical examples using labels and selectors in Kubernetes. You will learn how to filter pods by environment, business unit, and tier, and how to troubleshoot and fix issues in a ReplicaSet definition.

1. Listing Pods and Filtering by Environment

Begin by listing all the pods to review what is currently deployed:
Example output:
Each pod is labeled with keys such as ENV and BU. To filter pods in the development environment (assumed key “env” with value “dev”), use the following command:
If you want to remove the header and count the pods automatically, add the --no-headers option and pipe the output to the word count command:
This command indicates that there are 7 pods in the development environment.

2. Counting Pods in the Finance Business Unit

To determine the number of pods belonging to the finance business unit (assumed label bu=finance), execute:
This command returns 6 pods associated with the finance BU.

3. Counting All Objects in the Production Environment

First, list only the pods in the production environment (assumed label env=prod):
For a more comprehensive view that includes services and ReplicaSets, use:
An example output might look like this:
By counting the number of lines using wc -l, you determine that there are 7 objects in total in the production environment.

4. Identifying a Specific Pod with Multiple Labels

To find the pod that meets all three criteria—being in the production environment, belonging to the finance business unit, and operating in the front-end tier—follow these steps:
  1. List the pods in the production environment:
    Example output:
  2. Combine selectors for environment, business unit, and tier:
    The command returns:
This confirms that the pod “app-1-zzxdf” meets all specified criteria.

5. Fixing a ReplicaSet Definition

The final task involves resolving a label mismatch error in a ReplicaSet YAML definition file. Below is the original ReplicaSet configuration:
When you create the ReplicaSet using:
you see the following error:
The error occurs because the label in the selector (tier: front-end) does not match the label in the pod template (tier: nginx). These values must be identical.
To resolve the error, update the template labels to match the selector. For example, change the label in the pod template to tier: front-end:
After saving the changes, create the ReplicaSet again:
You should see an output similar to:
To verify that the ReplicaSet was successfully created, run:
Example output:
Ensure that selector labels and template labels always match to avoid deployment errors and ensure that your ReplicaSet manages the correct pods.

This concludes the lesson on using labels and selectors in Kubernetes. For more information on Kubernetes object management, consider checking out the following resources:

Watch Video