🐶
Kubernetes

Kubernetes: List Pods and Nodes (kubectl Commands)

By Jan on 01/21/2025

Learn how to efficiently list all pods and their corresponding nodes in a Kubernetes cluster for streamlined management and troubleshooting.

Kubernetes: List Pods and Nodes (kubectl Commands)

Table of Contents

Introduction

This guide provides some useful kubectl commands for listing pods and nodes in a Kubernetes cluster. You can use these commands to quickly get an overview of your cluster's resources and their status.

Step-by-Step Guide

  1. List all pods in all namespaces:

    kubectl get pods --all-namespaces
  2. List all pods and their nodes:

    kubectl get pods --all-namespaces -o wide
  3. List pods on a specific node:

    kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node_name>
  4. List all nodes:

    kubectl get nodes 

    Replace <node_name> with the actual name of the node.

Code Example

This Python code defines a function to execute kubectl commands and then uses it to list pods across all namespaces, list pods with their corresponding nodes, list pods on a specific node, and list all nodes in a Kubernetes cluster.

You've already provided the code examples in your request! These are valid kubectl commands to interact with your Kubernetes cluster.

Here's a breakdown of each command and how you might use them in a script:

import subprocess

def run_kubectl_command(command):
  """Runs a kubectl command and returns the output."""
  try:
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    print(result.stdout)
  except subprocess.CalledProcessError as e:
    print(f"Error executing command: {e}")

# 1. List all pods in all namespaces
run_kubectl_command("kubectl get pods --all-namespaces")

# 2. List all pods and their nodes
run_kubectl_command("kubectl get pods --all-namespaces -o wide")

# 3. List pods on a specific node
node_name = "your-node-name"  # Replace with the actual node name
run_kubectl_command(f"kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName={node_name}")

# 4. List all nodes
run_kubectl_command("kubectl get nodes")

Explanation:

  • run_kubectl_command function:

    • Takes a kubectl command as a string.
    • Uses subprocess.run to execute the command in a shell.
    • capture_output=True captures the command's output.
    • text=True decodes the output as text.
    • Prints the command's output or an error message if the command fails.
  • Using the function:

    • Each example calls run_kubectl_command with the specific kubectl command.
    • For listing pods on a specific node, you'll need to replace "your-node-name" with the actual name of the node you're interested in.

To use this code:

  1. Save it as a Python file (e.g., kubectl_commands.py).
  2. Make sure you have kubectl installed and configured on your system.
  3. Run the script from your terminal: python kubectl_commands.py

This will execute the kubectl commands and print the results to your terminal.

Additional Notes

General:

  • kubectl: These commands assume you have kubectl installed and configured to connect to your Kubernetes cluster.
  • Context: Ensure you've selected the correct Kubernetes context if you're working with multiple clusters.
  • Output Formatting: The -o wide option provides more information, but you can customize output further using different output formats (e.g., -o json, -o yaml).
  • Filtering: You can use labels to filter pods and nodes. For example: kubectl get pods -l app=nginx to list pods with the label "app=nginx".

Specific Commands:

  • kubectl get pods --all-namespaces: This command lists pods across all namespaces, giving you a cluster-wide view.
  • kubectl get pods --all-namespaces -o wide: The -o wide option adds extra columns like Node, IP address, and container image, providing a more detailed view.
  • kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node_name>: This command is useful for troubleshooting issues on a specific node.
  • kubectl get nodes: This command lists all nodes in your cluster and their status (Ready, NotReady, etc.). You can use this to check the health of your nodes.

Scripting:

  • Error Handling: The Python script includes basic error handling using try...except. You can expand this to provide more informative error messages or handle specific error types.
  • Automation: You can incorporate these commands into scripts or tools for automating tasks like monitoring, deployment, or resource management.

Further Exploration:

  • kubectl describe: Get detailed information about a specific pod or node.
  • kubectl logs: View the logs of a pod's containers.
  • kubectl exec: Execute commands inside a running container.
  • Kubernetes Documentation: Refer to the official Kubernetes documentation for a comprehensive guide to kubectl and other Kubernetes concepts: https://kubernetes.io/docs/

Summary

Task Command
List pods in all namespaces kubectl get pods --all-namespaces
List pods and their nodes kubectl get pods --all-namespaces -o wide
List pods on a specific node kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node_name>
List all nodes kubectl get nodes

Note: Replace <node_name> with the actual name of the node.

Conclusion

This guide explored essential kubectl commands for managing Kubernetes resources. You learned how to list pods across different scopes, retrieve detailed information about them, and identify their associated nodes. These commands are fundamental for monitoring your applications, troubleshooting issues, and understanding the state of your cluster. By mastering these basic operations, you'll be well-equipped to navigate and manage your Kubernetes environment effectively. For a deeper dive, explore the wealth of information available in the official Kubernetes documentation and other online resources.

References

  • How to List All Pods and Its Nodes in Kubernetes | Baeldung on Ops How to List All Pods and Its Nodes in Kubernetes | Baeldung on Ops | Explore commands to retrieve information about all pods and their assigned nodes.
  • Kubernetes: list all pods and its nodes - Stack Overflow Kubernetes: list all pods and its nodes - Stack Overflow | Feb 26, 2018 ... You can use kubectl get pods --all-namespaces to list all the pods from all namespaces and kubectl get nodes for listing all nodes.
  • Viewing Pods and Nodes | Kubernetes Viewing Pods and Nodes | Kubernetes | Learn how to troubleshoot Kubernetes applications using kubectl get, kubectl describe, kubectl logs and kubectl exec.
  • Get Pods descending sorted from age - Discuss Kubernetes Get Pods descending sorted from age - Discuss Kubernetes | Hello I want to call the API to get the latest pods. I have a label filter to get only the specific pod I want to, but the first pod that will shown up is the oldest one. How can I get the youngest one (latest)? In Short: How to get the latest instantiated pod from the API in Kubernetes?
  • kubectl Quick Reference | Kubernetes kubectl Quick Reference | Kubernetes | This page contains a list of commonly used kubectl commands and flags. Note:These instructions are for Kubernetes v1.32. To check the version, use the kubectl version command. Kubectl autocomplete BASH source <(kubectl completion bash) # set up autocomplete in bash into the current shell, bash-completion package should be installed first. echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell. You can also use a shorthand alias for kubectl that also works with completion:
  • Start regular pods after all daemonset pods are Running - General ... Start regular pods after all daemonset pods are Running - General ... | I’ve run out of ideas regarding this subject and am looking for new ideas. I don’t believe the specifics of the cluster are all that important but we run a custom Kubernetes 1.12.2 cluster on GCE that uses cluster-autoscaler to scale GCE Migs when we need node capacity. We observe the following when a new node is needed: CA boots a new node in the appropriate MIG The VM boots and starts the kubelet as the kubelet starts up it gets a set of daemonset pods to run that provide services at a node...
  • Assigning Pods to Nodes | Kubernetes Assigning Pods to Nodes | Kubernetes | You can constrain a Pod so that it is restricted to run on particular node(s), or to prefer to run on particular nodes. There are several ways to do this and the recommended approaches all use label selectors to facilitate the selection. Often, you do not need to set any such constraints; the scheduler will automatically do a reasonable placement (for example, spreading your Pods across nodes so as not place Pods on a node with insufficient free resources).
  • What is Kubectl Get Nodes and How to Use It What is Kubectl Get Nodes and How to Use It | What does the kubectl get nodes command do? Learn how and when to run it and how to view the labels created in nodes.
  • List All Container Images Running in a Cluster | Kubernetes List All Container Images Running in a Cluster | Kubernetes | This page shows how to use kubectl to list all of the Container images for Pods running in a cluster. Before you begin You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait