🐶
Kubernetes

Kubernetes API: List Pods on Specific Nodes

By Jan on 01/16/2025

Learn how to effectively use the Kubernetes API to retrieve and filter pods running on specific nodes in your cluster.

Kubernetes API: List Pods on Specific Nodes

Table of Contents

Introduction

Managing and troubleshooting applications deployed on Kubernetes often requires interacting with individual pods. This guide provides essential kubectl commands to retrieve information about pods and perform actions on them.

Step-by-Step Guide

  1. List pods on a specific node:

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

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

  2. Get detailed information about a pod:

    kubectl describe pod <pod_name> -n <namespace>

    Replace <pod_name> with the name of the pod and <namespace> with the namespace it belongs to.

  3. View logs from a pod:

    kubectl logs <pod_name> -n <namespace>

    Replace <pod_name> and <namespace> as needed.

  4. Execute a command inside a pod:

    kubectl exec -it <pod_name> -n <namespace> -- <command>

    Replace <pod_name>, <namespace>, and <command> accordingly.

  5. List all pods and their nodes:

    kubectl get pods -o wide -A

    The -o wide flag shows the node name in the output.

  6. Get the node name for a specific pod:

    kubectl get pod <pod_name> -n <namespace> -o jsonpath='{.spec.nodeName}'

    Replace <pod_name> and <namespace> as needed.

Code Example

This Python script utilizes the Kubernetes Python client library to interact with a Kubernetes cluster. It demonstrates various operations such as listing pods on a specific node, retrieving detailed pod information, viewing pod logs, executing commands inside a pod, listing all pods and their corresponding nodes, and obtaining the node name for a specific pod. The script assumes that the user has installed the Kubernetes Python client library, configured kubectl to connect to their cluster, and replaced placeholder values with actual node, pod, and namespace names.

from kubernetes import client, config

# Load Kubernetes configuration
config.load_kube_config()

# Create an instance of the Kubernetes API client
v1 = client.CoreV1Api()

# --- 1. List pods on a specific node ---
node_name = "your-node-name"
field_selector = f"spec.nodeName={node_name}"
pods = v1.list_pod_for_all_namespaces(field_selector=field_selector).items
for pod in pods:
    print(f"Pod: {pod.metadata.name}, Namespace: {pod.metadata.namespace}")

# --- 2. Get detailed information about a pod ---
pod_name = "your-pod-name"
namespace = "your-namespace"
pod = v1.read_namespaced_pod(name=pod_name, namespace=namespace)
print(pod)

# --- 3. View logs from a pod ---
pod_name = "your-pod-name"
namespace = "your-namespace"
logs = v1.read_namespaced_pod_log(name=pod_name, namespace=namespace)
print(logs)

# --- 4. Execute a command inside a pod ---
pod_name = "your-pod-name"
namespace = "your-namespace"
command = ["ls", "-l"]
resp = stream(v1.connect_get_namespaced_pod_exec,
              pod_name,
              namespace,
              command=command,
              stderr=True, stdin=False,
              stdout=True, tty=False)
print(f"Response: {resp}")

# --- 5. List all pods and their nodes ---
pods = v1.list_pod_for_all_namespaces().items
for pod in pods:
    print(f"Pod: {pod.metadata.name}, Node: {pod.spec.node_name}")

# --- 6. Get the node name for a specific pod ---
pod_name = "your-pod-name"
namespace = "your-namespace"
pod = v1.read_namespaced_pod(name=pod_name, namespace=namespace)
print(f"Node: {pod.spec.node_name}")

Before running the code:

  1. Install the Kubernetes Python client library:

    pip install kubernetes
  2. Configure kubectl: Make sure you have kubectl installed and configured to connect to your Kubernetes cluster.

Replace the placeholder values:

  • Replace "your-node-name", "your-pod-name", and "your-namespace" with the actual names of your node, pod, and namespace, respectively.
  • For example 4, replace ["ls", "-l"] with your desired command.

This code provides Python examples for each of the kubectl commands listed in the article. You can run this code to interact with your Kubernetes cluster programmatically.

Additional Notes

General:

  • Namespaces: Always specify the namespace (-n <namespace>) unless you want to interact with pods in all namespaces (-A or --all-namespaces).
  • Output Formatting: Use -o (or --output) with options like wide, json, yaml, or jsonpath to customize the output format for easier scripting or analysis.
  • Resource Limits: Be mindful of resource limits (CPU, memory) when executing commands inside pods, especially in production environments.
  • Troubleshooting: kubectl describe pod <pod_name> provides extensive information about a pod's status, events, and conditions, which is crucial for troubleshooting.

Specific Commands:

  1. kubectl get pods --field-selector: You can use other field selectors to filter pods based on various criteria (e.g., status, labels). Refer to the Kubernetes documentation for a complete list of field selectors.

  2. kubectl describe pod: This command provides a wealth of information, including:

    • Pod status (Running, Pending, Failed)
    • Node the pod is scheduled on
    • Container images used
    • Resource requests and limits
    • Events related to the pod (e.g., scheduling, pulling images, starting containers)
  3. kubectl logs:

    • Use -f or --follow to stream logs continuously.
    • Use -c <container_name> to view logs from a specific container within a pod (if it has multiple containers).
    • Use --previous to view logs from a previous instance of the pod (if it has restarted).
  4. kubectl exec:

    • The -it flags allocate a pseudo-terminal (-t) and keep STDIN open (-i) for interactive sessions.
    • You can use this command for tasks like debugging, running shell commands, or accessing the application's command-line interface.
  5. kubectl get pods -o wide -A: This is useful for getting a quick overview of all pods and their corresponding nodes across all namespaces.

  6. kubectl get pod -o jsonpath: JSONPath is a powerful way to extract specific information from Kubernetes resources. Learn more about JSONPath syntax to query for other pod details.

Beyond the Basics:

  • Labels and Selectors: Use labels to organize your pods and selectors to target specific groups of pods for commands or deployments.
  • Kubernetes Dashboard: Consider using the Kubernetes Dashboard for a graphical interface to manage and monitor your pods and other cluster resources.

Summary

This cheat sheet provides a quick reference for common Kubernetes commands related to pods.

Task Command Notes
List pods on a specific node kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node_name> Replace <node_name>
Get detailed pod information kubectl describe pod <pod_name> -n <namespace> Replace <pod_name> and <namespace>
View pod logs kubectl logs <pod_name> -n <namespace> Replace <pod_name> and <namespace>
Execute a command inside a pod kubectl exec -it <pod_name> -n <namespace> -- <command> Replace <pod_name>, <namespace>, and <command>
List all pods and their nodes kubectl get pods -o wide -A Uses -o wide to show node names
Get the node name for a specific pod kubectl get pod <pod_name> -n <namespace> -o jsonpath='{.spec.nodeName}' Replace <pod_name> and <namespace>

Conclusion

Mastering these kubectl commands and techniques will significantly enhance your ability to manage, monitor, and troubleshoot applications running in Kubernetes. For further exploration, delve into topics like resource limits, labels, selectors, and the Kubernetes Dashboard to unlock the full potential of container orchestration. This guide equipped you with the essential knowledge and tools to effectively interact with pods, a fundamental building block of Kubernetes applications. As you continue your Kubernetes journey, remember that the command line and the Kubernetes Python client library are your allies in harnessing the power of container orchestration.

References

  • 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.
  • kubernetes - How to list all the pods running in a particular worker ... kubernetes - How to list all the pods running in a particular worker ... | May 25, 2020 ... You can get pods running on specific node by using this command: kubectl get pods --all-namespaces -o wide --field-selector spec.
  • 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:
  • Kubernetes API service not responding - General Discussions ... Kubernetes API service not responding - General Discussions ... | Hello, I’m a newbie was trying to setup a basic Kubernetes environment with one Master node and one Worker node. I’m facing this problem where constantly my master node API service abruptly stops responding, and if I restart ‘kubelet’ service it works for couple of minutes and again it stops and gives following error. Please help me fix this problem because I stuck with this issue since last three days and i’m not able to figure out the root cause for this problem. Thank you. ubadmin@kuber...
  • How to get the node on which a pod is running? · Issue #399 ... How to get the node on which a pod is running? · Issue #399 ... | kubectl get pods -o wide returns a NODES column that shows where each pod is running. Given a pod name, how can I get the corresponding node name? I couldn't find a way to get it from v1.Pod.
  • The connection to the server <host>:6443 was refused - did you ... The connection to the server :6443 was refused - did you ... | Hello guys. Everything was working on a kubernetes cluster with a master and three nodes. After a restart in all machines I started receiving this error when trying to run any kubectl command. #> kubectl version Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.0", GitCommit:"925c127ec6b946659ad0fd596fa959be43f0cc05", GitTreeState:"clean", BuildDate:"2017-12-15T21:07:38Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"} The connection to the server 135.122.6.50:644...
  • 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.
  • Placing pods on specific nodes using node selectors - Controlling ... Placing pods on specific nodes using node selectors - Controlling ... | The developers can add a node selector to the pods they create to ensure the pods get scheduled on those nodes. A pod is not scheduled if the Pod object ...

Were You Able to Follow the Instructions?

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