梗概

kubernetes探针是用于检查容器健康状况的机制,确保只有健康的容器才能接收流量,并在容器异常时自动重启或隔离。

核心概念

  • Liveness Probe(存活探针):判断容器是否存活,失败时kubelet会重启容器
  • Readiness Probe(就绪探针):判断容器是否准备好接收流量,失败时从Service端点中移除
  • Startup Probe(启动探针):检查容器应用是否已启动,为慢启动容器提供额外时间

详细说明

探针类型详解

1. Liveness Probe(存活探针)

livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 5
  failureThreshold: 3

作用机制

  • 定期检查容器内应用是否正常运行
  • 检测到应用死锁、无响应等状态时触发重启
  • Pod的重启策略配合工作

典型场景

  • Java应用出现内存泄漏导致无响应
  • 应用进入死循环状态
  • 数据库连接池耗尽

2. Readiness Probe(就绪探针)

readinessProbe:
  httpGet:
    path: /ready
    port: 8080
  initialDelaySeconds: 5
  periodSeconds: 5

作用机制

  • 检查容器是否准备好处理请求
  • 失败时将PodService的负载均衡中移除
  • 不会重启容器,只是暂时隔离

典型场景

  • 应用启动过程中需要加载配置
  • 依赖的外部服务暂时不可用
  • 应用正在执行数据库迁移

3. Startup Probe(启动探针)

startupProbe:
  httpGet:
    path: /startup
    port: 8080
  failureThreshold: 30
  periodSeconds: 10

作用机制

  • 为慢启动应用提供足够的启动时间
  • 启动期间禁用其他探针
  • 适用于启动时间较长的遗留应用

探针检查方式

HTTP GET

httpGet:
  path: /health
  port: 8080
  httpHeaders:
  - name: Custom-Header
    value: Awesome

TCP Socket

tcpSocket:
  port: 8080

执行命令

exec:
  command:
  - cat
  - /tmp/healthy

配置参数

参数说明默认值
initialDelaySeconds容器启动后等待多久开始探测0
periodSeconds探测频率10
timeoutSeconds探测超时时间1
successThreshold连续成功次数阈值1
failureThreshold连续失败次数阈值3

最佳实践

1. 探针端点设计

  • 轻量级检查:避免复杂的业务逻辑检查
  • 快速响应:确保探针端点能快速返回结果
  • 区分检查类型:为不同探针设计不同的检查逻辑

2. 参数调优

# 生产环境推荐配置
livenessProbe:
  httpGet:
    path: /actuator/health/liveness
    port: 8080
  initialDelaySeconds: 60    # 给应用足够启动时间
  periodSeconds: 30          # 适中的检查频率
  timeoutSeconds: 10         # 合理的超时时间
  failureThreshold: 3        # 避免误杀
 
readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    port: 8080
  initialDelaySeconds: 10
  periodSeconds: 10
  timeoutSeconds: 5
  failureThreshold: 3

3. 与Spring Boot集成

# application.yml
management:
  health:
    probes:
      enabled: true
    livenessState:
      enabled: true
    readinessState:
      enabled: true
  endpoint:
    health:
      show-details: always
      probes:
        enabled: true

故障排查

常见问题

  1. 探针频繁失败:检查应用启动时间、网络延迟
  2. 误重启:调整failureThresholdtimeoutSeconds
  3. 流量中断:检查readiness探针逻辑是否过于严格

调试命令

# 查看Pod事件
kubectl describe pod <pod-name>
 
# 查看探针日志
kubectl logs <pod-name> -c <container-name>
 
# 手动测试探针端点
kubectl exec -it <pod-name> -- curl localhost:8080/health

探针机制是kubernetes实现应用高可用的关键组件,与控制器Service等组件协同工作,确保集群中只有健康的容器实例对外提供服务。