Kubernetes preStop 钩子
在 Kubernetes 中,preStop
钩子 是 Pod 生命周期中的一个关键机制,用于在容器被终止前执行特定操作(如优雅关闭应用、清理资源等)。
1. preStop
的作用
- 优雅终止(Graceful Shutdown):
在容器收到
SIGTERM
信号前,先执行preStop
钩子中的命令或 HTTP 请求,确保应用正确处理未完成的请求或保存状态。 - 顺序控制:
与
terminationGracePeriodSeconds
配合,避免强制终止(SIGKILL
)导致数据丢失。
2. 典型应用场景
场景 1:通知服务下线
containers:
- name: web-server
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "curl -X POST http://localhost:8080/graceful-shutdown"]
用途:通知应用主动从注册中心(如 Consul)注销,避免流量继续路由到正在终止的 Pod。
场景 2:等待请求完成
containers:
- name: nginx
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 30 && nginx -s quit"]
用途:等待 30 秒让现有请求完成,再发送 nginx -s quit
优雅退出。
场景 3:清理临时文件
containers:
- name: log-processor
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "rm -rf /tmp/*.log"]
3. 配置参数说明
参数名 | 说明 |
---|---|
terminationGracePeriodSeconds |
从 SIGTERM 到 SIGKILL 的等待时间(默认 30 秒),需覆盖 preStop 耗时。 |
restartPolicy |
若设为 Never 或 OnFailure ,preStop 仅在删除 Pod 时触发。 |
4. 示例
apiVersion: v1
kind: Pod
metadata:
name: graceful-app
spec:
terminationGracePeriodSeconds: 60 # 预留足够时间给preStop
containers:
- name: app
image: nginx:latest
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "echo 'Stopping...'; sleep 20; nginx -s quit"]
ports:
- containerPort: 80
5. 调试技巧
-
查看事件:
kubectl describe pod <pod-name> | grep -A 10 "Events"
-
日志验证: 确保
preStop
命令的日志被记录(如写入文件或标准输出)。
评论需开启科学上网!