Kubernetes Technology: A DevOps Perspective (With Python)

Introduction

Kubernetes (K8s) is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. In DevOps, Kubernetes enhances CI/CD workflows by providing scalability, automation, and resilience.

Why Kubernetes in DevOps?

Automated Deployments: Zero-downtime updates.

Scalability: Auto-scaling applications.

Self-Healing: Restarting failed containers.

Infrastructure as Code (IaC): Managing infrastructure declaratively.

Kubernetes Components

1. Cluster Architecture

Master Node (Control Plane)

Worker Nodes (Run applications)

Pods (Smallest deployable units)

2. Core Components

API Server: Handles communication.

Scheduler: Assigns workloads.

Kubelet: Ensures container health.

Using Kubernetes with Python

Python makes it easy to interact with Kubernetes using the Kubernetes Python Client (kubernetes library).

1. Installing the Kubernetes Client for Python

pip install kubernetes

2. Connecting to the Kubernetes Cluster

from kubernetes import client, config

# Load Kubernetes configuration (from default kubeconfig)

config.load_kube_config()

# Create an API instance

v1 = client.CoreV1Api()

# List all pods in the default namespace

pods = v1.list_pod_for_all_namespaces(watch=False)

for pod in pods.items:

print(f"Pod Name: {pod.metadata.name}, Namespace: {pod.metadata.namespace}")

3. Deploying a Pod Using Python

from kubernetes.client import V1Pod, V1PodSpec, V1Container, V1ObjectMeta

pod_manifest = V1Pod(

metadata=V1ObjectMeta(name="python-pod"),

spec=V1PodSpec(containers=[

V1Container(

name="nginx-container",

image="nginx:latest",

ports=[client.V1ContainerPort(container_port=80)]

)

])

)

# Create the pod

v1.create_namespaced_pod(namespace="default", body=pod_manifest)

print("Pod Created Successfully!")

4. Scaling Deployments with Python

apps_v1 = client.AppsV1Api()

# Scale a deployment

deployment_name = "my-app"

namespace = "default"

scale = apps_v1.read_namespaced_deployment_scale(deployment_name, namespace)

scale.spec.replicas = 5 # Scaling up to 5 replicas

apps_v1.replace_namespaced_deployment_scale(deployment_name, namespace, scale)

print("Deployment scaled successfully!")