Pod 生命周期与探针
约 587 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › K8s › Pod 与容器(在新窗口打开) › Pod 生命周期与探针
Pod 生命周期阶段
| 阶段 | 说明 |
|---|---|
| Pending | 已被集群接受,但容器未全部启动(正在拉取镜像或等待调度) |
| Running | Pod 已绑定到节点,所有容器已启动 |
| Succeeded | 所有容器正常退出(Job 场景) |
| Failed | 至少一个容器非正常退出 |
| Unknown | 与 Pod 所在节点通信失败 |
# 实时观察 Pod 状态变化
kubectl get pods -w
# 查看 Pod 状态详情
kubectl describe pod my-pod容器探针(Probe)
K8s 提供三种探针来检测容器状态:
| 探针 | 用途 | 检测到失败后的行为 |
|---|---|---|
| livenessProbe | 容器是否存活 | 重启容器 |
| readinessProbe | 容器是否就绪可接收流量 | 从 Service 端点中移除 |
| startupProbe | 容器是否已启动完成 | 重启容器(成功前禁用其他探针) |
livenessProbe
apiVersion: v1
kind: Pod
metadata:
name: liveness-demo
spec:
containers:
- name: app
image: nginx:alpine
livenessProbe:
httpGet:
path: /healthz
port: 80
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3readinessProbe
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
successThreshold: 1
failureThreshold: 2startupProbe
startupProbe:
httpGet:
path: /started
port: 8080
initialDelaySeconds: 0
periodSeconds: 2
failureThreshold: 30 # 给 60 秒启动时间探针类型
# HTTP GET 探针(最常用)
livenessProbe:
httpGet:
path: /healthz
port: 8080
httpHeaders:
- name: X-Custom-Header
value: health
# TCP Socket 探针
livenessProbe:
tcpSocket:
port: 3306
# Exec 命令探针
livenessProbe:
exec:
command:
- cat
- /tmp/healthy探针参数
| 参数 | 默认 | 说明 |
|---|---|---|
initialDelaySeconds | 0 | 容器启动后多久开始探测 |
periodSeconds | 10 | 探测间隔(秒) |
timeoutSeconds | 1 | 单次探测超时 |
successThreshold | 1 | 连续成功次数才视为健康 |
failureThreshold | 3 | 连续失败次数才视为不健康 |
生命周期钩子
spec:
containers:
- name: app
image: nginx:alpine
lifecycle:
postStart: # 容器启动后执行
exec:
command: ["/bin/sh", "-c", "echo Started > /tmp/status"]
preStop: # 容器停止前执行
exec:
command: ["/bin/sh", "-c", "nginx -s quit; sleep 5"]小结
- Pod 状态:Pending → Running → Succeeded/Failed。
- livenessProbe 决定是否重启,readinessProbe 决定是否接收流量。
- startupProbe 在启动阶段禁用其他探针,适合慢启动应用。
- 探针支持 HTTP GET、TCP Socket 和 Exec 三种方式。
preStop钩子实现优雅关闭,postStart做初始化工作。
上一节:Pod 定义与基本操作 下一节:Init 容器与 Sidecar
