Kubernetes生产实战(三十一):K8S 集群日常巡检_kubernetes生产实战故障指南
Kubernetes 集群的日常巡检是保障业务稳定运行的关键环节。通过系统化的检查流程,可以及时发现潜在风险,预防故障发生。以下是一套完整的 Kubernetes 日常巡检实战指南:
一、巡检前准备
1. 环境准备
# 配置kubectl上下文kubectl config use-context production# 安装必要工具sudo apt-get install -y jq tree # Linuxbrew install jq tree # macOS
2. 巡检清单模板
kubectl get componentstatuses
kubectl top nodes
kubectl get pods --all-namespaces
kubectl get pvc --all-namespaces
kubectl get events --all-namespaces
二、集群核心组件检查
1. API Server 健康状态
kubectl get componentstatuses# 或直接访问API健康检查端点curl -k https://$APISERVER/healthz
预期结果:所有组件状态为Healthy
风险点:若etcd
或scheduler
异常,可能导致无法创建 / 删除资源
2. Controller Manager 状态
kubectl get pods -n kube-system -l component=kube-controller-manager
预期结果:所有 Pod 处于Running
状态,且READY
为1/1
3. Scheduler 状态
kubectl get pods -n kube-system -l component=kube-scheduler
预期结果:所有 Pod 处于Running
状态,且READY
为1/1
4. etcd 状态
# 获取etcd pod名称ETCD_POD=$(kubectl get pods -n kube-system -l component=etcd -o name)# 检查etcd成员健康状态kubectl exec -n kube-system $ETCD_POD -- sh -c \'ETCDCTL_API=3 etcdctl --endpoints=https://127.0.0.1:2379 \\ --cacert=/etc/kubernetes/pki/etcd/ca.crt \\ --cert=/etc/kubernetes/pki/etcd/server.crt \\ --key=/etc/kubernetes/pki/etcd/server.key \\ endpoint health\'
预期结果:所有成员返回health=true
三、Node 节点检查
1. 节点状态与数量
kubectl get nodes
预期结果:所有节点状态为Ready
风险点:若节点 NotReady,可能导致 Pod 调度失败
2. 节点资源使用情况
# 查看CPU和内存使用kubectl top nodes# 深入查看节点详情kubectl describe node | egrep \'Name:|Taints:|Conditions:\'
预期阈值:CPU < 80%,Memory < 80%
风险点:资源接近满负荷可能导致 OOM 或调度失败
3. 节点磁盘压力检查
# 检查节点磁盘压力状态kubectl get nodes -o json | jq \'.items[] | {name: .metadata.name, diskPressure: .status.conditions[] | select(.type==\"DiskPressure\") | .status}\'
预期结果:所有节点DiskPressure
为False
四、Pod 与工作负载检查
1. Pod 状态检查
# 查看所有命名空间的Pod状态kubectl get pods --all-namespaces | grep -v Running | grep -v Completed# 统计异常Pod数量kubectl get pods --all-namespaces | grep -v Running | grep -v Completed | wc -l
预期结果:输出为空(无异常 Pod)
常见异常状态:Pending
、CrashLoopBackOff
、Error
2. 容器重启次数检查
# 查看重启次数超过5次的Podkubectl get pods --all-namespaces -o json | jq \'.items[] | select(.status.containerStatuses[]?.restartCount > 5) | {name: .metadata.name, namespace: .metadata.namespace, restarts: .status.containerStatuses[].restartCount}\'
预期结果:无输出或重启次数合理(如初始化时的短暂重启)
3. 工作负载控制器检查
# 检查Deployment副本数kubectl get deployments --all-namespaces | awk \'$2 != $3 {print}\'# 检查StatefulSet副本数kubectl get statefulsets --all-namespaces | awk \'$2 != $3 {print}\'
预期结果:无输出(所有工作负载副本数与期望值一致)
五、网络与服务检查
1. Service 状态检查
# 查看所有Servicekubectl get services --all-namespaces# 检查无头服务(Headless Service)kubectl get services --all-namespaces | grep \"None\"
风险点:ClusterIP 类型的 Service 若无法访问,可能是 kube-proxy 异常
2. Ingress 控制器状态
# 查看Ingress控制器Podkubectl get pods -n ingress-nginx # 根据实际命名空间调整# 检查Ingress规则kubectl get ingress --all-namespaces
预期结果:Ingress 控制器 Pod 正常运行,规则配置正确
3. DNS 解析测试
# 在集群内创建测试Podkubectl run dns-test --image=busybox:1.35 --restart=Never -- sleep 3600# 测试集群内部域名解析kubectl exec dns-test -- nslookup kubernetes.default# 测试外部域名解析kubectl exec dns-test -- nslookup google.com# 清理测试Podkubectl delete pod dns-test
预期结果:所有域名解析正常
六、存储检查
1. PVC 状态检查
# 查看所有PVC状态kubectl get pvc --all-namespaces | grep -v Bound# 检查PVC容量使用kubectl describe pvc | grep \"Used Capacity\"
预期结果:所有 PVC 状态为Bound
,容量使用合理
2. PV 状态检查
# 查看所有PV状态kubectl get pv | grep -v Available | grep -v Bound
预期结果:所有 PV 状态为Bound
或Available
风险点:若出现Failed
状态,可能需要手动清理
3. 存储 Class 检查
# 查看存储类配置kubectl get sc
预期结果:默认存储类标记为(default)
七、事件与日志检查
1. 集群事件检查
# 查看最近1小时内的警告和错误事件kubectl get events --all-namespaces --sort-by=.metadata.creationTimestamp | grep -E \'Warning|Error\' | grep \"$(date -d \'1 hour ago\' +\'%Y-%m-%dT%H\')\"# 统计各命名空间的事件数量kubectl get events --all-namespaces -o json | jq \'.items[] | .metadata.namespace\' | sort | uniq -c | sort -nr
风险点:频繁出现的相同类型事件(如 OOMKilled)需重点关注
2. 关键组件日志检查
# 查看API Server日志kubectl logs -n kube-system # 查看kubelet日志journalctl -u kubelet -n 100 # 查看最近100行
关注点:频繁出现的错误日志、连接超时等
八、配置与安全检查
1. 证书有效期检查
# 检查APIServer证书有效期openssl x509 -noout -dates -in /etc/kubernetes/pki/apiserver.crt# 检查etcd证书有效期openssl x509 -noout -dates -in /etc/kubernetes/pki/etcd/server.crt
建议:证书剩余有效期应大于 3 个月
2. 节点 Taints 与 Tolerations 检查
# 查看所有节点的Taintskubectl get nodes -o json | jq \'.items[] | {name: .metadata.name, taints: .spec.taints}\'# 检查Pod的Tolerationskubectl get pods -o yaml | grep tolerations -A 5
风险点:过多 Taints 可能导致调度失败
3. 网络策略检查
# 查看所有网络策略kubectl get networkpolicies --all-namespaces# 验证网络策略生效情况# 创建测试Pod,验证是否符合网络策略限制
九、性能与资源使用分析
1. 资源请求与限制分析
# 查看各命名空间资源请求与限制kubectl describe namespace | grep -A 10 \"Resource Limits\"# 统计各命名空间Pod资源使用kubectl top pods --all-namespaces --containers
2. 长时间运行的 Job/CronJob 检查
# 查看运行时间超过24小时的Jobkubectl get jobs --all-namespaces -o json | jq \'.items[] | select(.status.startTime != null and (.status.completionTime == null or (.status.completionTime | fromdate) - (.status.startTime | fromdate) > 86400)) | {name: .metadata.name, namespace: .metadata.namespace, duration: ((.status.completionTime // now | fromdate) - (.status.startTime | fromdate)) / 3600 + \"h\"}\'
风险点:长时间运行的 Job 可能占用过多资源
十、巡检报告生成
1. 自动化巡检脚本
#!/bin/bash# k8s-daily-check.sh# 输出报告头部echo \"===== Kubernetes 日常巡检报告 =====\"echo \"日期: $(date)\"echo \"集群: $(kubectl config current-context)\"echo \"\"# 1. 核心组件状态echo \"--- 核心组件状态 ---\"kubectl get componentstatusesecho \"\"# 2. 节点状态echo \"--- 节点状态 ---\"kubectl get nodesecho \"\"# 3. Pod异常状态echo \"--- 异常Pod ---\"kubectl get pods --all-namespaces | grep -v Running | grep -v Completedecho \"\"# 4. PVC状态echo \"--- PVC状态 ---\"kubectl get pvc --all-namespaces | grep -v Boundecho \"\"# 5. 事件检查echo \"--- 最近1小时警告/错误事件 ---\"kubectl get events --all-namespaces --sort-by=.metadata.creationTimestamp | grep -E \'Warning|Error\' | grep \"$(date -d \'1 hour ago\' +\'%Y-%m-%dT%H\')\"echo \"\"# 6. 资源使用echo \"--- 节点资源使用 ---\"kubectl top nodesecho \"\"echo \"--- Pod资源使用 ---\"kubectl top pods --all-namespacesecho \"\"# 7. 证书有效期echo \"--- API Server证书有效期 ---\"openssl x509 -noout -dates -in /etc/kubernetes/pki/apiserver.crtecho \"\"echo \"===== 巡检完成 =====\"
2. 定期执行与报告归档
# 添加到crontab每日执行0 8 * * * /root/k8s-daily-check.sh > /var/log/k8s-check/$(date +\\%Y\\%m\\%d)-check.log 2>&1
十一、异常处理流程
- 发现异常:通过巡检发现问题
- 紧急处理:
- 若影响业务,优先恢复服务(如重启 Pod、扩容)
- 收集关键日志和事件信息
- 根因分析:
- 查看相关组件日志
- 分析事件时间线
- 检查配置变更历史
- 修复与预防:
- 修复问题(如调整资源配额、更新配置)
- 完善监控告警规则
- 更新巡检清单
十二、推荐工具
-
Krew:Kubectl 插件管理器
# 安装krew( set -x; cd \"$(mktemp -d)\" && OS=\"$(uname | tr \'[:upper:]\' \'[:lower:]\')\" && ARCH=\"$(uname -m | sed -e \'s/x86_64/amd64/\' -e \'s/\\(arm\\)\\(64\\)\\?.*/\\1\\2/\' -e \'s/aarch64/arm64/\')\" && KREW=\"krew-${OS}_${ARCH}\" && curl -fsSLO \"https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz\" && tar zxvf \"${KREW}.tar.gz\" && ./\"${KREW}\" install krew)# 常用krew插件kubectl krew install treekubectl krew install view-allocationskubectl krew install resource-capacity
-
kube-bench:CIS Kubernetes 安全基准检查
docker run --rm -v /etc/kubernetes:/etc/kubernetes -v /var/run:/var/run -v `pwd`:/output aquasec/kube-bench:latest run --targets master,node --version 1.23 --json > kube-bench-results.json
-
Prometheus + Grafana:集群监控与可视化
# 使用kube-prometheus-stack快速部署helm repo add prometheus-community https://prometheus-community.github.io/helm-chartshelm install prometheus prometheus-community/kube-prometheus-stack
通过系统化的日常巡检,可以提前发现 Kubernetes 集群中的潜在问题,降低生产环境故障概率,保障业务稳定运行。建议根据业务特点定制巡检清单,并结合自动化工具提升效率。