Last modified: Oct 19, 2026
Manage Kubernetes Pods with Python
The Kubernetes Python client lets you control pods from your own code. You can list, create, inspect, update, and delete pods without touching kubectl.
This guide walks you through each operation with clear examples. It is written for beginners who want a reliable and clean setup.
Prerequisites
You need Python 3.7 or newer and access to a Kubernetes cluster. A local cluster like minikube or kind works well for learning.
If you have not installed the client yet, follow a guide to install the Kubernetes Python client in a virtual environment.
You also need a valid kubeconfig file for local development. Inside a pod, the service account must be mounted for in-cluster authentication.
Configure Authentication
Every script starts by loading configuration. Without it, the client cannot authenticate with the API server.
For local development, call load_kube_config() to read the default kubeconfig file.
from kubernetes import client, config
# Load the default kubeconfig
config.load_kube_config()
# Create a CoreV1Api client
v1 = client.CoreV1Api()
print("Client ready.")
Client ready.
Inside a pod, use load_incluster_config() instead. It reads the mounted service account token automatically.
from kubernetes import client, config
# Load credentials from the pod's service account
config.load_incluster_config()
v1 = client.CoreV1Api()
print("In-cluster client ready.")
In-cluster client ready.
Choose the correct method based on where your code runs. Mixing them up causes authentication errors.
List Pods
Listing pods is the simplest operation. It verifies your setup and shows the current state of the cluster.
Call list_namespaced_pod() to fetch pods in a specific namespace. The method returns a list object with metadata and status for each pod.
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
# List pods in the default namespace
pods = v1.list_namespaced_pod(namespace="default")
for pod in pods.items:
print(f"{pod.metadata.name} -> {pod.status.phase}")
nginx-deployment-6b474476c4-2xj9k -> Running
redis-cache-0 -> Running
For cluster-wide listing, use list_pod_for_all_namespaces instead. Be careful with large clusters because the response can be big.
Create a Pod
You can create a pod from a manifest object. The client provides model classes for every Kubernetes resource.
Call create_namespaced_pod() with a namespace and a pod body. The body follows the same structure as a YAML manifest.
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
# Define a simple nginx pod
pod_manifest = client.V1Pod(
metadata=client.V1ObjectMeta(name="demo-nginx"),
spec=client.V1PodSpec(
containers=[
client.V1Container(
name="nginx",
image="nginx:1.27",
ports=[client.V1ContainerPort(container_port=80)],
)
]
),
)
# Create the pod in the default namespace
v1.create_namespaced_pod(namespace="default", body=pod_manifest)
print("Pod created.")
Pod created.
Always set resource limits in production. A pod without limits can consume node resources and affect other workloads.
Read Pod Details
After creation, inspect the pod to confirm its status. Call read_namespaced_pod() with the pod name and namespace.
This method returns the full pod object. You can read the phase, container statuses, and conditions.
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
# Read a specific pod
pod = v1.read_namespaced_pod(name="demo-nginx", namespace="default")
print(f"Name: {pod.metadata.name}")
print(f"Phase: {pod.status.phase}")
print(f"Pod IP: {pod.status.pod_ip}")
Name: demo-nginx
Phase: Running
Pod IP: 10.244.0.15
Use this method in health checks and automation scripts. It gives you a single source of truth for pod state.
Patch a Pod
Some pod fields can be updated in place. Labels, annotations, and image tags are common examples.
Call patch_namespaced_pod() with a partial body. The API server merges the change into the existing object.
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
# Update a label on the pod
patch_body = {"metadata": {"labels": {"team": "platform"}}}
v1.patch_namespaced_pod(
name="demo-nginx",
namespace="default",
body=patch_body,
)
print("Pod patched.")
Pod patched.
Not every field is mutable. Changing a container image usually requires a new pod or a deployment rollout.
Delete a Pod
Clean up test pods to avoid clutter. Call delete_namespaced_pod() with the pod name and namespace.
You can pass a grace period to allow the container to shut down cleanly.
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
# Delete the pod with a 30 second grace period
v1.delete_namespaced_pod(
name="demo-nginx",
namespace="default",
grace_period_seconds=30,
)
print("Pod deleted.")
Pod deleted.
Check for a NotFound error in automation. A pod may already be gone, and that should not crash your script.
Handle Errors Gracefully
Kubernetes API calls can fail. Permissions, conflicts, and network issues are common.
Wrap operations in a try/except block. Catch specific exceptions from the Kubernetes client.
from kubernetes import client, config
from kubernetes.client.exceptions import ApiException
config.load_kube_config()
v1 = client.CoreV1Api()
try:
v1.read_namespaced_pod(name="missing-pod", namespace="default")
except ApiException as exc:
if exc.status == 404:
print("Pod does not exist.")
else:
print(f"API error: {exc.status} {exc.reason}")
Pod does not exist.
For production automation, install sentry-sdk in Python to capture exceptions and API failures automatically. This gives you visibility into broken jobs before users notice.
Best Practices for Clean Automation
Reuse a single API client across calls. Creating a new client for every operation wastes resources.
Always set explicit namespaces. Relying on the default namespace causes confusion in multi-tenant clusters.
Use labels to identify pods created by your automation. Labels make cleanup and filtering much easier.
If you schedule regular pod management jobs, schedule Python tasks with Airflow to run them on a reliable timetable. Pair this with alerting for failed runs.
Keep your Kubernetes client version aligned with your cluster minor version. Mismatches cause missing fields and API errors.
Test destructive operations in a staging cluster first. Deleting the wrong pod in production can cause an outage.
Conclusion
Managing Kubernetes pods with Python is straightforward. Load the configuration, create a client, and call the right API method.
Use list_namespaced_pod() to inspect pods. Use create, read, patch, and delete methods to control their lifecycle.
Handle errors explicitly and reuse your client. These small habits keep automation reliable and safe.
With these patterns, your Python scripts can manage pods confidently at any scale.