G
GuideDevOps
Lesson 9 of 15

Docker & Kubernetes Python SDKs

Part of the Python for DevOps tutorial series.

Python's powerful SDKs allow you to automate infrastructure tasks that usually require CLI commands like docker run or kubectl apply.

1. Docker SDK for Python (docker)

The docker package allows you to communicate with the Docker daemon.

Basic Usage: List Running Containers

Action:

import docker
 
client = docker.from_env()
for container in client.containers.list():
    print(f"ID: {container.short_id}, Name: {container.name}, Status: {container.status}")

Result:

ID: a1b2c3d4, Name: redis_cache, Status: running
ID: f5e6d7c8, Name: nginx_proxy, Status: running

2. Kubernetes Python Client (kubernetes)

The official Kubernetes Python client is used for automating tasks like scaling deployments or auditing pods.

Listing All Pods in a Namespace

Action:

from kubernetes import client, config
 
# Load local kubeconfig
config.load_kube_config()
 
v1 = client.CoreV1Api()
print("Listing pods in 'default' namespace:")
pods = v1.list_namespaced_pod(namespace="default")
for pod in pods.items:
    print(f"Pod: {pod.metadata.name}, IP: {pod.status.pod_ip}")

Result:

Listing pods in 'default' namespace:
Pod: web-server-v1-6789fb8c-x2jkl, IP: 10.244.1.42
Pod: database-master-0, IP: 10.244.1.12

3. DevOps Automation: Health Checks

A common use case is writing a script that checks if a Kubernetes Deployment has the correct number of ready replicas and restarts it if necessary.

Snippet:

apps_v1 = client.AppsV1Api()
deploy = apps_v1.read_namespaced_deployment(name="my-app", namespace="prod")
 
if deploy.status.ready_replicas < deploy.spec.replicas:
    print("ALERT: Not all replicas are ready!")
    # Notification or auto-remediation logic...

4. Comparison: CLI vs. SDK

FeatureCLI (bash)SDK (python)
SpeedFast for single tasksBetter for complex logic
ParsingRequires jq / awkNative objects/JSON
Error HandlingExit codesTry/Except blocks
IntegrationDifficult to testEasy unit testing

Summary

  • Use docker-py for managing local or remote containers.
  • Use kubernetes-python-client for sophisticated orchestration.
  • Prefer SDKs when your logic involves multi-step decision-making.