Best Practices for Microservices: Health Checks
37%
Fine-Tuning Probes with Configuration Options
Let's put these concepts into practice by creating a Deployment that uses both liveness and readiness probes. We will use a simple application that exposes an HTTP endpoint for health checks.
kubectl apply -f - <
---
# create a temporary namespace to perform our test
apiVersion: v1
kind: Namespace
metadata:
name: healthcheck
---
# create a Deployment with liveness and readiness probes
apiVersion: apps/v1
kind: Deployment
metadata:
name: stateless-flask
namespace: healthcheck
spec:
replicas: 1
selector:
matchLabels:
app: stateless-flask
template:
metadata:
labels:
app: stateless-flask
spec:
containers:
- name: stateless-flask
image: eon01/stateless-flask
ports:
- containerPort: 5000
livenessProbe:
exec:
command:
- python3
- -c
- |
import urllib.request, sys
from datetime import datetime
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
urllib.request.urlopen('http://example.com', timeout=2)
# Write to container's main process stdout
with open('/proc/1/fd/1', 'w') as f:
f.write(f"{timestamp} - Liveness probe: example.com is reachable\n")
sys.exit(0)
except Exception as e:
# Write to container's main process stderr
with open('/proc/1/fd/2', 'w') as f:
f.write(f"{timestamp} - Liveness probe: Cannot reach example.com - {str(e)}\n")
sys.exit(1)
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
successThreshold: 1
failureThreshold: 3
readinessProbe:
httpGet:
path: /tasks
port: 5000
initialDelaySeconds: 10
periodSeconds: 15
timeoutSeconds: 10
successThreshold: 1
failureThreshold: 15
# terminationGracePeriodSeconds: 10
EOF
Our liveness probe uses an exec mechanism that runs a Python script to check if example.com is reachable. If it is, the probe succeeds; otherwise, it fails.
The script is as follows:
import urllib.request, sys
from datetime import datetime
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
urllib.request.urlopen('http://example.com', timeout=2)
# Write to container's main process stdout
with open('/proc/1/fd/1', 'w') as f:
f.write(f"{timestamp} - Liveness probe: example.com is reachable\n")
sys.exit(0)
except Exception as e:
# Write to container's main process stderr
with open('/proc/1/fd/2', 'w') as f:
f.write(Cloud-Native Microservices With Kubernetes - 2nd Edition
A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in KubernetesEnroll now to unlock all content and receive all future updates for free.
