K8S系列之5.3:应用健康与可观测性(探针、监控与日志)
2026/5/8 18:28:34 网站建设 项目流程

在分布式系统中,没有可观测性的应用就像在黑暗中飞行。本章将为你构建完整的"眼睛"和"耳朵",让你不仅能及时发现故障,更能预知问题,实现真正的自动驾驶式运维。

引言:可观测性的三重维度

云原生时代,可观测性已经从"可有可无"变成"必不可少"。它包含三个核心支柱:

维度作用经典工具回答的问题
指标(Metrics)数值化测量Prometheus系统表现如何?CPU使用率多少?
日志(Logs)离散事件记录EFK/Loki发生了什么?为什么出错?
追踪(Traces)请求链路追踪Jaeger/Zipkin请求经过哪些服务?哪里最慢?

一、应用健康检查:Kubernetes探针机制

1.1 探针类型与作用机制

Kubernetes提供三种探针来保障应用的健康运行:

Pod生命周期
成功
失败
成功
持续监控
失败
失败
启动探针
Pod创建
就绪探针
重启容器
接收流量
健康运行
存活探针
重启容器
从Service移除

1.2 探针配置详解

存活探针(Liveness Probe)
apiVersion:apps/v1kind:Deploymentmetadata:name:web-appspec:replicas:3selector:matchLabels:app:web-apptemplate:metadata:labels:app:web-appspec:containers:-name:appimage:nginx:1.21ports:-containerPort:80livenessProbe:httpGet:path:/healthzport:80httpHeaders:-name:X-Custom-Headervalue:AwesomeinitialDelaySeconds:10# 容器启动后等待10秒periodSeconds:5# 每5秒检查一次timeoutSeconds:2# 超时时间2秒successThreshold:1# 成功1次即认为成功failureThreshold:3# 失败3次才认为失败

就绪探针(Readiness Probe)
readinessProbe:exec:command:-cat-/tmp/healthyinitialDelaySeconds:5periodSeconds:5# 或使用TCP检查# tcpSocket:# port: 3306# 或使用HTTP检查(推荐)# httpGet:# path: /ready# port: 8080

启动探针(Startup Probe) - Kubernetes 1.16+
startupProbe:httpGet:path:/startupport:8080failureThreshold:30# 最多尝试30次periodSeconds:10# 每10秒尝试一次# 总共允许 30 * 10 = 300秒 = 5分钟的启动时间

1.3 探针最佳实践

场景1:Java应用的健康检查
# Spring Boot应用配置livenessProbe:httpGet:path:/actuator/health/livenessport:8080initialDelaySeconds:120# Java应用启动较慢periodSeconds:10readinessProbe:httpGet:path:/actuator/health/readinessport:8080initialDelaySeconds:30periodSeconds:5startupProbe:httpGet:path:/actuator/health/startupport:8080failureThreshold:30periodSeconds:10
场景2:数据库连接的就绪检查
# 数据库连接检查脚本readinessProbe:exec:command:-/bin/sh--c-|# 检查数据库连接 if mysqladmin ping -h"${DB_HOST}" -u"${DB_USER}" -p"${DB_PASSWORD}" 2>/dev/null; then exit 0 else exit 1 fiinitialDelaySeconds:30periodSeconds:10
场景3:gRPC服务的健康检查
# 需要gRPC健康检查协议livenessProbe:grpc:port:50051service:grpc.health.v1.Health# 可选,指定服务名称initialDelaySeconds:10periodSeconds:5

1.4 常见陷阱与解决方案

问题1:探针配置不当导致频繁重启

# 错误配置:初始延迟太短livenessProbe:httpGet:path:/healthport:8080initialDelaySeconds:2# ❌ 应用还没启动就开始检查periodSeconds:3failureThreshold:2# 正确配置:考虑应用启动时间livenessProbe:httpGet:path:/healthport:8080initialDelaySeconds:30# ✅ 给足启动时间periodSeconds:10failureThreshold:3

问题2:探针端点负载过高

# 解决方案:轻量级健康检查端点readinessProbe:httpGet:path:/health/light# 轻量检查,不检查所有依赖port:8080periodSeconds:5timeoutSeconds:1livenessProbe:httpGet:path:/health/deep# 深度检查,包含所有关键依赖port:8080periodSeconds:30# 检查间隔较长timeoutSeconds:

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询