Development

How to List Kubernetes Pods

In this tutorial, we are going to learn the commands we can use to list the pods in a given kubernetes cluster and discover what each output from the command entails
Captain Salem 9 min read
How to List Kubernetes Pods

Kubernetes is a free and open-source platform for automating the deployment, scalability, and operation of application containers.

Kubernetes or k8s provides a framework for us to run distributed systems in a resilient manner. K8 takes care of all the scaling and failover operations for the pplications.

Kubernetes pods on the other hand are the smallest and basic deployable object units in Kubernetes. A pod refers to a single instance of a running process in the kubernetes cluster.

A pod can contain one or more container which are then managed by the k8 as a single entity. This allows the containers to share resources such as network and storage.

In Kubernetes, pods are ephemeral by nature; these means that Kubernetes can create, destroy, replicate, and manage them automatically based on the desired cluster state.

Kubernetes List Pods

In Kubernetes, we can use the command kubectl get pods to list all the pods within the cluster:

kubectl get pods

The command should return detailed information about every pod in the cluster; including the pod status.

This can quickly allow you to tell the health of the cluster and know which to target during troubleshooting.

What Does the Output Mean?

Once you have run the command above, you are going to get an example output as shown below:

NAME       READY   STATUS             RESTARTS        AGE
nginx      1/1     Running            0               97m
apache     1/1     Running            0               85m
minlinux   0/1     CrashLoopBackOff   6 (2m42s ago)   84m

Using the above output as inspiration, let us see what a typical output of the kubectl get pods command entails.

  1. NAME - This column displays the name of the pod. It is a unique identifier assigned to each pod within a Kubernetes namespace.
    • nginx - Name of the first pod.
    • apache - Name of the second pod.
    • minlinux - Name of the third pod.
  2. READY - This column shows the number of containers in the pod that are ready out of the total number of containers in the pod.
    • 1/1 - Both the nginx and apache pods have one container each, and both are ready.
    • 0/1 - The minlinux pod has one container, but it is not ready.
  3. STATUS - This column indicates the current status of the pod.
    • Running - The pod is running without issues. Both nginx and apache pods are in this state.
    • CrashLoopBackOff - The pod is in a start-failure loop, meaning it tries to start, crashes, and then Kubernetes attempts to restart it. This cycle has been repeating. The minlinux pod is in this state, indicating a problem with its execution.
  4. RESTARTS - This column shows the number of times the containers within the pod have been restarted. It provides insight into the stability and health of the application running inside the pod.
    • 0 - Both the nginx and apache pods have not restarted, indicating stable operations.
    • 6 (2m42s ago) - The minlinux pod has restarted 6 times. The additional detail (2m42s ago) indicates the last restart happened 2 minutes and 42 seconds ago, which helps in identifying how frequently the restarts are occurring and if the situation is improving or not.
  5. AGE - This column shows how long the pod has been running since it was created.
    • 97m, 85m, 84m: Indicates that the nginx, apache, and minlinux pods have been running for 97 minutes, 85 minutes, and 84 minutes, respectively.

Kubernetes Pod Status (All)

There are various status in which a pod can be. It is difficult to discuss what causes each problem but it can help you to narrow down the search area.

The supported kubernetes pod status include:

  1. Pending - The pod has been accepted by the Kubernetes system, but one or more of the container images may not have been created.
  2. Running - The pod has been bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting.
  3. Succeeded - All containers in the pod have terminated in success, and will not be restarted. This status is typical for pods that are meant to execute a task that will naturally complete, such as batch computations.
  4. Failed - All containers in the pod have terminated, and at least one container has terminated in failure. A container is considered to have failed if it exited with a non-zero status or was terminated by the system.
  5. Unknown - The state of the pod could not be obtained. This phase typically occurs due to an error in communicating with the node where the pod is scheduled.
  6. CrashLoopBackOff - Not an official pod phase, but a common status seen in the STATUS column of kubectl get pods. It indicates that a container in the pod is repeatedly crashing and being restarted by Kubernetes. This back-off mechanism slows down the rate of restarts after successive failures.
  7. ImagePullBackOff - Another common status (similar to CrashLoopBackOff), indicating that Kubernetes is having trouble pulling the container image. This could be due to the image not existing or the pod not having the correct permissions to pull the image.
  8. ContainerCreating -This status appears when the pod is in the process of creating containers but has not yet completed. This can be seen shortly after a pod transitions from Pending to Running status.
  9. Terminating - This status is observed when a pod is in the process of being shut down. Pods may remain in this state for a period if they are waiting for processes to gracefully shut down or for volumes to unmount.

The above are some common status you will see when you fetch information about the pods in the cluster.

Fetching Detailed Information

You can tell Kubernetes to provide you with additional information for each pods using the -o wide flag or --output wide option.

The command syntax is as shown:

kubectl get pods -o wide

When you run the above command, you will get an output as shown:

NAME       READY   STATUS              RESTARTS   AGE    IP              NODE       NOMINATED NODE   READINESS GATES
nginx      1/1     Running             0          105m   192.168.194.4   orbstack   <none>           <none>
apache     1/1     Running             0          93m    192.168.194.7   orbstack   <none>           <none>
minlinux   0/1     ContainerCreating   0          5s     <none>          orbstack   <none>           <none>

Here, you will more information such as:

  • IP - refers to the IP address of the pod.
  • NODE - denotes the node where the pod is running.
  • NOMINATED NODE - refers tot he preferred note to run the pod as indentified by the kubernetes scheduler based on the pod's requirements.
  • READINESS GATES - the conditions that must be met for the pd to be considered ready.

List Pood By Name

You can also list one or more pods by their name use the command shown below:

kubectl get pods <pod_name>

Where teh pod_name refers to a list of names separated by a space character.

For exmaple:

kubectl get pods apache nginx

The above command show list information about the apache, and nginx pods as specified. The reuslting output is as shown:

NAME     READY   STATUS    RESTARTS   AGE
apache   1/1     Running   0          96m
nginx    1/1     Running   0          108m
☝️
It is good to ensure that the specified pod name exists in the cluster. If not, the command will return an error indicating the specified command is not found in the cluster.

Kubernetes List Pods in Namespace

Kubernetes uses namespaces as a way to logically seperate resources within an app. Hence, to fetch all the pods in a given namesapce, you can use the command shown below:

kubetctl get pods -n <namespace>

Where namespace specifies the target namespace. For example, suppose we have the following namespaces:

NAME              STATUS   AGE
kube-system       Active   113m
default           Active   113m
kube-public       Active   113m
kube-node-lease   Active   113m

To list all the pods in the default namespaces, we can use the command:

kubectl get pods -n default

The above command will list all the Pods and their status in the default namesapce

Kubernetes List Pods in All Namespaces.

If you do not want to limit to a target namespace, you can tell Kubernetes to show you all the pods in all the available namespaces using the --all-namespaces' as:

kubectl get pods --all-namespaces

Example output:

NAMESPACE     NAME                                     READY   STATUS             RESTARTS        AGE
kube-system   coredns-576cfbb478-zkr4t                 1/1     Running            0               115m
kube-system   local-path-provisioner-957fdf8bc-722lw   1/1     Running            0               115m
default       nginx                                    1/1     Running            0               115m
default       apache                                   1/1     Running            0               102m
default       minlinux                                 0/1     CrashLoopBackOff   6 (3m42s ago)   9m48s

This includes the souce namespace, pods name, and other details.

Kubernetes List Pods By Label

Kubernetes allow us to create pod labels, which are key-value pairs attached to a Kubernetes objects. Labels help to organize resources based on specific criteria.

To list all pods based on a specific lable, we cna use the -l or --label flag as shown:

kubectl get pods -l <label>=<value>

Where the label represents the key of the label and value refers to the value associated with the label.

For example:

kubectl get pods -l run=loadbalancer

In this case, the above command will display all the pods with the label run=loadbalancer attached to them.

Kubernetes Show Pod Labels

If you are not sure about the labels attached to the pods, you can use the --shpw-label flag to tell Kubernetes to show you the pod and associated labels.

kubectl get pods --show-labels

Output:

NAME       READY   STATUS             RESTARTS        AGE    LABELS
nginx      1/1     Running            0               121m   run=nginx
apache     1/1     Running            0               108m   run=apache
minlinux   0/1     CrashLoopBackOff   7 (4m23s ago)   15m    run=minlinux

In this case, the command return an extra column showing the associated labels for each pod.

Kubernetes Output Pod Information as JSON and YAML

By default, the Kubernetes command will return the information about the pods in a tabular format. This is good for good glance.

However, if we want to interact with the data programmatically and parse it into other apps, we need to output the data in a more suitable format.

This is where the -o flag comes into play. It allows us to specify the target output format such as JSON or YAML. The command syntax is as shown:

kubectl get pods -o <output_format>

Where the output_format refers to either yaml or json.

For example to output the data in JSON format, run:

kubectl get pods -o json

Example output:

{
    "apiVersion": "v1",
    "items": [
        {
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "creationTimestamp": "2024-02-10T19:42:42Z",
                "labels": {
                    "run": "nginx"
                },
                "name": "nginx",
                "namespace": "default",
                "resourceVersion": "393",
                "uid": "3ca6b05d-b176-4b4f-8341-88b13c696c2c"
            },
            "spec": {
                "containers": [
                    {
                        "image": "nginx",
                        "imagePullPolicy": "Always",
                        "name": "nginx",
                        "resources": {},
                        "terminationMessagePath": "/dev/termination-log",
                        "terminationMessagePolicy": "File",
                        "volumeMounts": [
                            {
                                "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
                                "name": "kube-api-access-n64v6",
                                "readOnly": true
                            }
                        ]
                    }
                ],
                "dnsPolicy": "ClusterFirst",
                "enableServiceLinks": true,
                "nodeName": "orbstack",
                "preemptionPolicy": "PreemptLowerPriority",
                "priority": 0,
                "restartPolicy": "Always",
                "schedulerName": "default-scheduler",
                "securityContext": {},
                "serviceAccount": "default",
                "serviceAccountName": "default",
                "terminationGracePeriodSeconds": 30,
                "tolerations": [
                    {
                        "effect": "NoExecute",
                        "key": "node.kubernetes.io/not-ready",
                        "operator": "Exists",
                        "tolerationSeconds": 300
                    },
                    {
                        "effect": "NoExecute",
                        "key": "node.kubernetes.io/unreachable",
                        "operator": "Exists",
                        "tolerationSeconds": 300
                    }
                ],
                "volumes": [
                    {
                        "name": "kube-api-access-n64v6",
                        "projected": {
                            "defaultMode": 420,
                            "sources": [
                                {
                                    "serviceAccountToken": {
                                        "expirationSeconds": 3607,
                                        "path": "token"
                                    }
                                },
                                {
                                    "configMap": {
                                        "items": [
                                            {
                                                "key": "ca.crt",
                                                "path": "ca.crt"
                                            }
                                        ],
                                        "name": "kube-root-ca.crt"
                                    }
                                },
                                {
                                    "downwardAPI": {
                                        "items": [
                                            {
                                                "fieldRef": {
                                                    "apiVersion": "v1",
                                                    "fieldPath": "metadata.namespace"
                                                },
                                                "path": "namespace"
                                            }
                                        ]
                                    }
                                }
                            ]
                        }
                    }
                ]
            },
            "status": {
                "conditions": [
                    {
                        "lastProbeTime": null,
                        "lastTransitionTime": "2024-02-10T19:42:42Z",
                        "status": "True",
                        "type": "Initialized"
                    },
                    {
                        "lastProbeTime": null,
                        "lastTransitionTime": "2024-02-10T19:42:55Z",
                        "status": "True",
                        "type": "Ready"
                    },
                    {
                        "lastProbeTime": null,
                        "lastTransitionTime": "2024-02-10T19:42:55Z",
                        "status": "True",
                        "type": "ContainersReady"
                    },
                    {
                        "lastProbeTime": null,
                        "lastTransitionTime": "2024-02-10T19:42:42Z",
                        "status": "True",
                        "type": "PodScheduled"
                    }
                ],
                "containerStatuses": [
                    {
                        "containerID": 
                        
                        
----------------truncated---------------------------

Both JSON and YAML format will inlcude more detailed information about the pods and the actual cluster.

Such output is more then useful when you are using tools like Elasticsearch for health monitoring or interacting with Kubernetes programmatically.

Kubernetes Filter Pods By Field Selector.

We can also filter the list of pods based on a given field using the --field-selector flag. The command syntax is as shown:

kubectl get pods --field-selector=<field_name>=<field_value>

Where:

  • field_name - refers to a JSONPath expression used for selecting a specific field.
  • field_value - specifies the value for the specified field.

For exampel to filter the pods on the running status, we can use the command:

kubectl get pods --field-selector=status.phase=Running

Check out this resource to learn more.

JSONPath Support
Kubectl supports JSONPath template. JSONPath template is composed of JSONPath expressions enclosed by curly braces {}. Kubectl uses JSONPath expressions to filter on specific fields in the JSON object and format the output. In addition to the original JSONPath template syntax, the following functions and syntax are valid: Use double quotes to quote text inside JSONPath expressions. Use the range, end operators to iterate lists. Use negative slice indices to step backwards through a list.

Kubernetes Sort Pod Information

We can also sort the resulting pod information by using the sort-by flag. The command is as shown:

kubectl get pods --sort-by=<expression>

Where:

  • expression - refers to a JSONPath expression.

For example to list all all Pods sorted by their names in ascending order.

kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{range .status.containerStatuses[*]}{.restartCount}{"\n"}{end}{end}' | sort -k3 -n

in the command above:

  • --all-namespaces or -A: Fetches pods from all namespaces. If you want to get pods from a specific namespace, you can omit this option and add -n <namespace> instead.
  • -o jsonpath=... - Specifies a custom output format using jsonpath
  • This part:
    • {range .items[*]}- iterates over all pods.
    • {.metadata.namespace}- prints the namespace of the pod.
    • {.metadata.name} - prints the name of the pod.
    • {range .status.containerStatuses[*]}{.restartCount} - iterates over all containers in a pod and prints their restart count.
    • Note that if a pod has multiple containers, this will print multiple lines for the same pod, each with a different restart count.
    • {"\n"}- adds a newline after each restart count for proper formatting.
  • | sort -k3 -n: Pipes the output to sort, sorting numerically (-n) by the third column (-k3), which is the restart count.

This is a more advanced way of filtering and you do not need to use it. You can refence the JSONPath documentation on the kubernetes docs to learn more.

Conclusion

In this detailed guide, we explored everything you need to know about listing pod information within a Kubernetes cluster using the kubectl get pods command. We hope you learned from this tutorial.

Please share, leave a comment and we will see you, in the next one.

:) see you later, alligator!

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.