Kubernetes Deployment & Liveness/Readiness Probes
1Concept
Kubernetes orchestrates containerized Python microservices. Deployments define replica sets, CPU/RAM resource requests and limits, and configure `livenessProbe` (restarts failed containers) and `readinessProbe` (routes traffic only when the service is ready).
2Architecture Diagram
K8s Ingress ---> K8s Service ---> [ Pod 1: Ready ] [ Pod 2: Ready ] [ Pod 3: Unhealthy -> K8s Restarts! ]
3Code Example
Python 3.12
k8s_manifest = '''
apiVersion: apps/v1
kind: Deployment
metadata:
name: fastapi-microservice
spec:
replicas: 3
selector:
matchLabels:
app: fastapi-api
template:
metadata:
labels:
app: fastapi-api
spec:
containers:
- name: api
image: enterprise-registry.corp/api:v2.1
ports:
- containerPort: 8000
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "512Mi"
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 15
periodSeconds: 20
'''
print("=== Production Kubernetes Deployment Manifest ===")
print(k8s_manifest.strip())4Expected Output
=== Production Kubernetes Deployment Manifest ===
apiVersion: apps/v1
kind: Deployment
metadata:
name: fastapi-microservice
spec:
replicas: 3
selector:
matchLabels:
app: fastapi-api
template:
metadata:
labels:
app: fastapi-api
spec:
containers:
- name: api
image: enterprise-registry.corp/api:v2.1
ports:
- containerPort: 8000
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "1000m"
memory: "512Mi"
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 15
periodSeconds: 205Key Takeaways
- ✓Always configure memory limits to prevent out-of-control memory leaks from affecting node neighbors.
- ✓Readiness probes remove pods from service endpoints during warm-up or high load.
- ✓Use Horizontal Pod Autoscaler (HPA) to scale pods based on CPU and request latency metrics.