最稳妥的方式是在 Django 里写一个轻量级的 HTTP 接口,然后在 Kubernetes 部署文件里配置 httpGet 探针,区分存活和就绪场景。
先说结论:不要直接用根路径做检查,建议单独开发健康检查视图,并根据启动阶段和运行阶段配置不同类型的探针。
- 适合:Django 容器化部署、需要自动重启或流量隔离的场景
- 先准备:确认 Django 能独立于数据库返回状态,或明确数据库依赖关系
- 验收:通过 kubectl describe 查看事件,确认探针状态为 Success
Django 健康检查视图代码实现
在 Django 项目中创建专门的视图,避免依赖数据库连接,确保轻量级。
views.py 示例:
from django.http import HttpResponse
def healthz(request):
# 存活检查:仅判断进程是否存活
return HttpResponse("OK", status=200)
def ready(request):
# 就绪检查:可在此处检查数据库连接等依赖
try:
from django.db import connection
connection.ensure_connection()
except Exception:
return HttpResponse("Service Unavailable", status=503)
return HttpResponse("OK", status=200)urls.py 配置:
from django.urls import path
from . import views
urlpatterns = [
path('healthz', views.healthz),
path('ready', views.ready),
]完整 Deployment 配置示例
以下是包含探针配置的完整 Kubernetes Deployment YAML 结构,注意缩进层级:
apiVersion: apps/v1
kind: Deployment
metadata:
name: django-app
spec:
replicas: 2
selector:
matchLabels:
app: django
template:
metadata:
labels:
app: django
spec:
containers:
- name: django
image: my-django-image:latest
ports:
- containerPort: 8000
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 15
periodSeconds: 20
timeoutSeconds: 5
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 3应用配置命令:
kubectl apply -f deployment.yaml怎么验证是否生效
1. 查看 Pod 事件:使用以下命令查看探针执行情况。
kubectl describe pod <pod-name>在输出结果的 Events 部分,应看到类似以下内容:
Normal Killing ... kubelet Container django failed liveness probe, will be restarted
Normal Pulled ... kubelet Successfully pulled image
Normal Created ... kubelet Created container django
Normal Started ... kubelet Started container django
Normal Success ... kubelet Readiness probe succeeded2. 内部 curl 测试:进入容器内部直接测试接口。
kubectl exec -it <pod-name> -- curl -v http://localhost:8000/healthz预期返回 HTTP 200 状态码及 body 内容 "OK"。
常见坑
- 就绪探针强依赖数据库:如果数据库抖动,Pod 会被剔除流量,可能引发级联故障。建议就绪探针仅检查核心依赖,或设置合理的失败阈值。
- 检查逻辑过重:健康检查接口不应执行耗时操作,否则会导致探针超时,容器被反复重启。
- 超时时间设置过短:Django 启动需要加载模型和中间件,initialDelaySeconds 设置过小会导致启动失败。建议根据实际启动耗时调整,必要时增加 startupProbe。
参考来源
1. Kubernetes 官方文档:Configure Liveness, Readiness and Startup Probes (kubernetes.io)
2. Django 官方文档:Writing views (djangoproject.com)