Node-Problem-Detector完全指南
一、NPD 简介
1.1 什么是 Node Problem Detector?
Node Problem Detector(NPD)是 Kubernetes 官方维护的节点问题检测工具,作为 DaemonSet 在每个节点上运行,持续检测节点层面的各种问题并报告给 API Server,使集群管理堆栈的上游层能够感知节点健康状况。
官方仓库:https://github.com/kubernetes/node-problem-detector
版本说明:NPD 从 v0.8.x 跳转到 v1.34.x,采用与 Kubernetes 对齐的版本号。当前最新版本为 v1.36.0(2025-07-11)。v0.8.x 仍接收安全补丁但已属于 legacy 分支。
1.2 为什么需要 NPD?
在 Kubernetes 集群中,大量节点问题会影响运行在其上的 Pod:
- 基础设施守护进程问题:NTP 服务关闭、SSH 服务异常
- 硬件问题:CPU、内存或磁盘损坏、网络故障
- 内核问题:内核死锁、文件系统损坏、内核崩溃
- 容器运行时问题:Docker/Containerd 守护进程无响应
- Kubernetes 组件问题:Kubelet 频繁重启、Kube-proxy 异常
在 NPD 出现之前,这些问题对集群管理层不可见,Kubernetes 会继续将 Pod 调度到有问题的节点。NPD 的引入使得:
- 实时检测节点层面的各种问题
- 将问题报告给 API Server(NodeCondition / Event)
- 触发自动化的故障处理流程(配合 Remedy Systems)
- 提高集群的稳定性和可靠性
1.3 应用场景
NPD 已在主流云平台默认启用:
- GKE(Google Kubernetes Engine):作为默认 Kubernetes Addon 运行
- AKS(Azure Kubernetes Service):作为 AKS Linux Extension 的一部分默认启用
- 企业自建集群:用于提升故障检测和自动恢复能力
1.4 部署方式
| 方式 | 说明 | 适用场景 |
|---|---|---|
| DaemonSet(推荐) | 作为 Kubernetes DaemonSet 在每个节点运行 | 标准 K8s 集群 |
| 独立部署 | 作为独立守护进程运行 | 非 Kubernetes 环境 |
二、核心概念和架构
2.1 Problem API
NPD 使用两种方式向 API Server 报告问题:
NodeCondition — 永久性问题
用于报告导致节点无法正常运行 Pod 的持续性问题,会直接影响节点的调度状态。
常见的 NodeCondition 类型:
| Condition | 说明 |
|---|---|
KernelDeadlock | 内核死锁 |
ReadonlyFilesystem | 文件系统只读 |
FrequentKubeletRestart | Kubelet 频繁重启 |
FrequentDockerRestart | Docker 频繁重启 |
FrequentContainerdRestart | Containerd 频繁重启 |
KubeletUnhealthy | Kubelet 不健康 |
ContainerRuntimeUnhealthy | 容器运行时不健康 |
Event — 临时性问题
用于报告对 Pod 影响有限但具有参考意义的临时问题。不影响调度状态,用于故障诊断和趋势分析。
2.2 架构设计
NPD 采用模块化架构,所有 Problem Daemon 作为 goroutine 运行在同一个 NPD 二进制中:
graph TD
subgraph NPD["Node Problem Detector"]
subgraph PD["Problem Daemons"]
A[SystemLogMonitor
系统日志监控]
B[SystemStatsMonitor
系统统计监控]
C[CustomPluginMonitor
自定义插件监控]
D[HealthChecker
健康检查]
end
subgraph EX["Exporters"]
E[Kubernetes Exporter
NodeCondition / Event]
F[Prometheus Exporter
Metrics]
G[Stackdriver Exporter
Google Cloud 监控]
end
end
A --> E
A --> F
B --> F
C --> E
C --> F
D --> E
D --> F
E --> H[Kubernetes API Server]
F --> I[Prometheus]
G --> J[Google Cloud Monitoring]2.3 工作流程
- 问题检测:Problem Daemons 持续监控节点的日志、统计信息和服务状态
- 问题分析:根据预定义规则匹配检测到的问题
- 问题报告:通过 Exporters 将问题报告到 API Server / Prometheus
- 问题处理:Kubernetes 或 Remedy Systems 根据报告采取措施
- 状态更新:持续跟踪问题的状态变化
三、Problem Daemons 详解
3.1 SystemLogMonitor(系统日志监控)
系统日志监控器监视系统日志,根据预定义规则报告问题和指标,能够检测内核级别错误和系统服务异常。
支持的日志源:
| 配置类型 | 说明 | 典型配置文件 |
|---|---|---|
| kmsg | 内核消息(/dev/kmsg) | kernel-monitor.json |
| filelog | 文件日志 | kernel-monitor-filelog.json |
| systemd | Systemd journal | systemd-monitor.json |
| abrt | Automatic Bug Reporting Tool | abrt-adaptor.json |
检测的问题类型:
KernelDeadlock:内核死锁(soft lockup)ReadonlyFilesystem:文件系统变为只读FrequentKubeletRestart:Kubelet 频繁重启FrequentDockerRestart:Docker 频繁重启FrequentContainerdRestart:Containerd 频繁重启
配置示例(kernel-monitor.json):
{
"plugin": "kmsg",
"logPath": "/dev/kmsg",
"lookback": "5m",
"bufferSize": 10,
"source": "kernel-monitor",
"conditions": [
{
"type": "KernelDeadlock",
"reason": "KernelDeadlock",
"message": "kernel: BUG: soft lockup - CPU#%d stuck for %us! [%s:%d]"
}
],
"metrics": [
{
"name": "kernel_deadlock_total",
"help": "Number of kernel deadlocks detected",
"labels": ["reason"]
}
]
}
NPD 内置的监控配置文件:
| 配置文件 | 用途 |
|---|---|
kernel-monitor.json / kernel-monitor-filelog.json | 内核日志监控 |
kernel-monitor-counter.json | 内核日志计数器 |
docker-monitor.json / docker-monitor-filelog.json | Docker 日志监控 |
docker-monitor-counter.json | Docker 日志计数器 |
systemd-monitor.json / systemd-monitor-counter.json | Systemd 服务监控 |
readonly-monitor.json | 只读文件系统检测 |
network-problem-monitor.json | 网络问题监控 |
disk-log-message-filelog.json | 磁盘日志消息监控 |
iptables-mode-monitor.json | iptables 模式监控 |
3.2 SystemStatsMonitor(系统统计监控)
收集节点健康相关的系统统计信息作为 Prometheus 指标,默认采集间隔 60 秒。
采集指标分类:
| 类别 | 指标 |
|---|---|
| CPU | cpu/load_1m、cpu/load_5m、cpu/load_15m、cpu/runnable_task_count、cpu/usage_time、system/cpu_stat、system/interrupts_total、system/procs_running、system/procs_blocked |
| 内存 | memory/bytes_used、memory/percent_used、memory/anonymous_used、memory/dirty_used、memory/page_cache_used、memory/unevictable_used、memory/zswap_bytes_used |
| 磁盘 | disk/bytes_used、disk/percent_used、disk/io_time、disk/operation_count、disk/operation_bytes_count、disk/avg_queue_len、disk/weighted_io |
| 主机 | host/uptime |
| OS 特性 | system/os_feature(读取 guestosconfig/known-modules.json) |
磁盘监控配置选项:
includeAllAttachedBlk:包含所有挂载的块设备includeRootBlk:包含根块设备lsblkTimeout:lsblk 命令超时时间
3.3 CustomPluginMonitor(自定义插件监控)
允许用户编写自定义检查脚本,提供极大的灵活性。
使用场景:
- 监控特定应用程序状态
- 检查自定义服务健康状态
- 集成第三方监控工具
- 实现业务特定的故障检测逻辑
插件脚本示例(NTP 检测):
#!/bin/bash
# NTP 问题检测脚本
if ! systemctl is-active --quiet ntpd; then
echo "NTP service is not running"
exit 1
fi
ntpq -p | grep "*"
if [ $? -ne 0 ]; then
echo "NTP is not synchronized"
exit 1
fi
echo "NTP is healthy"
exit 0
配置示例:
{
"plugin": "custom",
"pluginConfigFile": "/etc/kubernetes/node-problem-detector/custom-plugin-config.json",
"metrics": [
{
"name": "custom_plugin_check_total",
"help": "Number of custom plugin checks",
"labels": ["result"]
}
]
}
NPD 还内置了 DNS 查询插件(v1.35.1 新增),可直接用于检测节点 DNS 解析能力。
3.4 HealthChecker(健康检查)
检查 Kubelet 和容器运行时的健康状况,确保核心组件正常运行。
检测的问题:
KubeletUnhealthy:Kubelet 不健康ContainerRuntimeUnhealthy:容器运行时不健康
内置配置文件:
health-checker-kubelet.jsonhealth-checker-docker.jsonhealth-checker-containerd.json
配置选项:
| 配置项 | 说明 | 默认值 |
|---|---|---|
component | 组件名称 | - |
service | 服务名称 | - |
enableRepair | 是否启用自动修复 | false |
healthCheckTimeout | 健康检查超时 | 30s |
coolDownTime | 修复后冷却时间 | 5m |
四、Exporters 详解
4.1 Kubernetes Exporter
将节点问题报告给 API Server:临时问题作为 Event,永久问题作为 NodeCondition。
配置参数:
| 参数 | 说明 | 默认值 |
|---|---|---|
--enable-k8s-exporter | 启用 Kubernetes 导出器 | true |
--apiserver-override | 自定义 API Server 地址 | - |
--address | HTTP 服务绑定地址 | 127.0.0.1 |
--port | HTTP 服务端口 | 20256 |
v1.34.0 变更:默认绑定地址从之前的未绑定改为
localhost,如依赖旧行为需手动配置。
HTTP 端点:
/healthz:健康检查/conditions:当前节点条件/debug/pprof:性能分析
4.2 Prometheus Exporter
将节点问题和指标以 Prometheus 格式暴露。
配置参数:
| 参数 | 说明 | 默认值 |
|---|---|---|
--prometheus-address | 抓取端点地址 | 127.0.0.1 |
--prometheus-port | 抓取端点端口 | 20257 |
指标示例:
# HELP node_problem_detector_problem_total Number of times a specific type of problem have occurred.
# TYPE node_problem_detector_problem_total counter
node_problem_detector_problem_total{reason="KernelDeadlock"} 1
node_problem_detector_problem_total{reason="ReadonlyFilesystem"} 0
# HELP node_problem_detector_problem_gauge Whether a specific type of problem is affecting node or not.
# TYPE node_problem_detector_problem_gauge gauge
node_problem_detector_problem_gauge{type="KernelDeadlock",reason="KernelDeadlock"} 1
node_problem_detector_problem_gauge{type="ReadonlyFilesystem",reason="ReadonlyFilesystem"} 0
4.3 Stackdriver Exporter
向 Google Cloud Monitoring API 报告节点问题和指标,适用于 GKE 环境。可通过编译时 build tag disable_stackdriver_exporter 禁用。
五、代码结构分析
5.1 项目结构
node-problem-detector/
├── pkg/ # 核心代码包
│ ├── custompluginmonitor/ # 自定义插件监控
│ ├── exporters/ # 导出器实现
│ │ ├── k8sexporter/ # Kubernetes 导出器
│ │ ├── prometheusexporter/ # Prometheus 导出器
│ │ └── stackdriver/ # Stackdriver 导出器
│ ├── healthchecker/ # 健康检查
│ ├── logcounter/ # 日志计数器
│ ├── problemdaemon/ # 问题守护进程框架
│ ├── problemdetector/ # 问题检测器核心
│ ├── problemmetrics/ # 问题指标管理
│ ├── systemlogmonitor/ # 系统日志监控
│ ├── systemstatsmonitor/ # 系统统计监控
│ ├── types/ # 类型定义
│ ├── util/ # 工具函数
│ └── version/ # 版本信息
├── cmd/ # 命令行入口
├── config/ # 配置文件(26 个 JSON)
├── deployment/ # 部署文件
├── test/ # 测试文件
└── Makefile # 构建脚本
5.2 核心组件分析
ProblemDaemon(问题守护进程)
所有 Problem Daemon 通过 Register 模式注册到统一的工厂:
// 注册问题守护进程工厂方法
func Register(problemDaemonType types.ProblemDaemonType, handler types.ProblemDaemonHandler) {
handlers[problemDaemonType] = handler
}
// 根据配置创建所有问题守护进程
func NewProblemDaemons(monitorConfigPaths types.ProblemDaemonConfigPathMap) []types.Monitor {
problemDaemonMap := make(map[string]types.Monitor)
for problemDaemonType, configs := range monitorConfigPaths {
for _, config := range *configs {
if _, ok := problemDaemonMap[config]; ok {
klog.Warningf("Duplicated problem daemon configuration %q", config)
continue
}
problemDaemonMap[config] = handlers[problemDaemonType].CreateProblemDaemonOrDie(config)
}
}
problemDaemons := []types.Monitor{}
for _, problemDaemon := range problemDaemonMap {
problemDaemons = append(problemDaemons, problemDaemon)
}
return problemDaemons
}
ProblemDetector(问题检测器核心)
启动所有监控器,通过统一的 channel 接收状态,分发给所有 Exporter:
func (p *problemDetector) Run(ctx context.Context) error {
var chans []<-chan *types.Status
failureCount := 0
for _, m := range p.monitors {
ch, err := m.Start()
if err != nil {
klog.Errorf("Failed to start problem daemon %v: %v", m, err)
failureCount++
continue
}
if ch != nil {
chans = append(chans, ch)
}
}
if len(p.monitors) == failureCount {
return fmt.Errorf("no problem daemon is successfully setup")
}
defer func() {
for _, m := range p.monitors {
m.Stop()
}
}()
ch := groupChannel(chans)
klog.Info("Problem detector started")
for {
select {
case <-ctx.Done():
return nil
case status := <-ch:
for _, exporter := range p.exporters {
exporter.ExportProblems(status)
}
}
}
}
ProblemMetricsManager(问题指标管理器)
确保每个问题类型在任何时刻最多只有一个 reason 被设置为 1:
func (pmm *ProblemMetricsManager) SetProblemGauge(problemType string, reason string, value bool) error {
pmm.problemTypeToReasonMutex.Lock()
defer pmm.problemTypeToReasonMutex.Unlock()
// 清除之前的 reason
if lastReason, ok := pmm.problemTypeToReason[problemType]; ok {
pmm.problemGauge.Record(map[string]string{"type": problemType, "reason": lastReason}, 0)
}
pmm.problemTypeToReason[problemType] = reason
var valueInt int64
if value {
valueInt = 1
}
return pmm.problemGauge.Record(map[string]string{"type": problemType, "reason": reason}, valueInt)
}
HealthChecker 结构体:
type healthChecker struct {
component string // 组件名称
service string // 服务名称
enableRepair bool // 是否启用自动修复
healthCheckFunc func() (bool, error) // 健康检查函数
repairFunc func() // 修复函数
uptimeFunc func() (time.Duration, error) // 运行时间
healthCheckTimeout time.Duration // 检查超时
coolDownTime time.Duration // 修复后冷却时间
loopBackTime time.Duration // 日志回溯时间
logPatternsToCheck map[string]int // 需要检查的日志模式
}
六、部署和配置
6.1 搭建测试集群
参考 基于Kind搭建测试集群 快速创建一个测试集群。
配置:
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
apiServerAddress: "192.168.1.16"
nodes:
- role: control-plane
extraPortMappings:
- containerPort: 6443
hostPort: 6443
listenAddress: "192.168.1.16"
protocol: tcp
- role: control-plane
- role: control-plane
- role: worker
- role: worker
创建高可用集群:
sudo kind create cluster --config=huari.yaml --name huari-test --image kindest/node:v1.34.0 --retain
sudo kind export logs --name huari-test
切换 kubectl 上下文:
sudo kubectl cluster-info --context kind-huari-test
查看信息:
# 查看集群节点
sudo kubectl get nodes
# 查看集群全部的 pod
sudo kubectl get pods -A -owide
删除集群:
sudo kind delete cluster --name huari-test
6.2 Helm 部署
NPD 官方推荐使用 Delivery Hero 维护的 Helm Chart:
# 添加 Helm 仓库
helm repo add deliveryhero https://charts.deliveryhero.io/
# 安装 NPD
helm install node-problem-detector deliveryhero/node-problem-detector \
--namespace kube-system \
--create-namespace
# 国内集群使用镜像代理
helm upgrade node-problem-detector deliveryhero/node-problem-detector \
--namespace kube-system \
--reuse-values \
--set image.repository=m.daocloud.io/registry.k8s.io/node-problem-detector/node-problem-detector \
--set image.tag=v1.36.0
6.3 启动参数
| 参数 | 说明 | 默认值 |
|---|---|---|
--config.system-log-monitor | 系统日志监控配置文件路径 | - |
--config.system-stats-monitor | 系统统计监控配置文件路径 | - |
--config.custom-plugin-monitor | 自定义插件监控配置文件路径 | - |
--enable-k8s-exporter | 启用 Kubernetes 导出器 | true |
--prometheus-address | Prometheus 端点地址 | 127.0.0.1 |
--prometheus-port | Prometheus 端点端口 | 20257 |
--hostname-override | 自定义节点名称 | - |
已弃用参数:
--system-log-monitors和--custom-plugin-monitors已被--config.*系列替代。如果同时设置新旧参数,NPD 会 panic。旧参数将在未来版本移除。
七、使用和测试
7.1 基本使用
查看 NPD 日志:
kubectl logs -n kube-system -l app=node-problem-detector -f
查看节点状态:
# 查看节点条件
kubectl describe node <node-name>
# 查看节点事件
kubectl get events --field-selector involvedObject.name=<node-name>
查看 Prometheus 指标:
curl http://<node-ip>:20257/metrics
7.2 测试 NPD 功能
测试内核死锁检测:
# 在一个终端中监控事件
kubectl get events -w
# 在节点上注入测试消息
sudo sh -c "echo 'kernel: BUG: unable to handle kernel NULL pointer dereference at TESTING' >> /dev/kmsg"
测试 Docker 挂起检测:
sudo sh -c "echo 'kernel: INFO: task docker:20744 blocked for more than 120 seconds.' >> /dev/kmsg"
八、Remedy Systems(补救系统)
Remedy Systems 是旨在自动修复 NPD 检测到的问题的系统。它们观察 NPD 发出的 Event 和 NodeCondition,采取措施恢复集群健康。
8.1 常见的 Remedy Systems
| 系统 | 功能 | 工作原理 |
|---|---|---|
| Draino | 根据节点条件自动排空节点 | 监控 NodeCondition → 标记不可调度 → 排空 → 配合 Cluster Autoscaler 终止节点 |
| Descheduler | 驱逐违反 NoSchedule 污点的 Pod | 监控污点状态 → 驱逐 Pod → 重新调度到健康节点 |
| Cluster Autoscaler | 自动扩缩节点数量 | Pod 无法调度时加节点 → 节点空闲时缩节点 → 替换不健康节点 |
| mediK8S | 基于 NHC Operator 的自动修复 | 监控 NodeCondition → 修复 API 委托 → 支持有条件修复和手动暂停 |
| Poison-Pill | 重启节点并重新调度工作负载 | 检测严重问题 → 节点重启 → 工作负载重新调度 |
| Cluster API MachineHealthCheck | 修复不健康的 Machine | 监控 Machine 健康 → 自动替换不健康 Machine |
相关仓库:
- Draino: https://github.com/planetlabs/draino
- Descheduler: https://github.com/kubernetes-sigs/descheduler
- Cluster Autoscaler: https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler
- mediK8S: https://github.com/medik8s
- Poison-Pill: https://github.com/medik8s/poison-pill
- Cluster API MachineHealthCheck: https://cluster-api.sigs.k8s.io/developer/architecture/controllers/machine-health-check
8.2 典型集成方案
方案一:NPD + Draino + Cluster Autoscaler
graph LR
A[NPD 检测问题] --> B[标记节点不可调度]
B --> C[Draino 排空节点]
C --> D[Cluster Autoscaler 终止节点]
D --> E[自动创建新节点]方案二:NPD + Descheduler
graph LR
A[NPD 检测问题] --> B[设置节点污点]
B --> C[Descheduler 驱逐 Pod]
C --> D[Pod 重新调度到健康节点]方案三:NPD + mediK8S
graph LR
A[NPD 检测问题] --> B[NHC 监控状态]
B --> C[mediK8S 执行修复]
C --> D[Poison-Pill 重启节点]