HPA无法获取自定义指标的根本原因是指标采集链路断裂,需依次验证Custom Metrics API注册、prometheus-adapter连通性、Prometheus指标采集、ServiceMonitor/RBAC配置及HPA标签匹配。

当HPA配置了自定义指标(如http_requests_total)却始终显示failed to get metric或unable to fetch metrics from custom metrics API,说明Kubernetes无法从Prometheus Adapter获取目标指标值,必须逐层验证链路是否打通。
确认Custom Metrics API是否可用
运行kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1/。如果返回404或连接拒绝,说明APIService未注册成功;若返回JSON但resources为空,说明Adapter服务未就绪或API注册失败。
检查APIService状态:kubectl get apiservice v1beta1.custom.metrics.k8s.io,观察CONDITIONS列是否为True。若为False,执行kubectl describe apiservice v1beta1.custom.metrics.k8s.io查看Reason字段——常见原因是Service端点不可达或TLS证书不匹配。
验证Prometheus Adapter能否连通Prometheus
进入prometheus-adapter Pod:kubectl exec -it -n monitoring deploy/prometheus-adapter -- sh。
在容器内执行curl -k https://prometheus-operated:9090/api/v1/query?query=count%7Bjob%3D%22prometheus-operator%22%7D。若返回connection refused或超时,说明Adapter与Prometheus网络不通,需检查Service名称、端口、命名空间是否匹配,以及NetworkPolicy是否拦截。
【关键前提】Adapter ConfigMap中rules必须明确包含目标指标的转换规则,且Prometheus中该指标必须真实存在并可查。例如要暴露http_requests_total为QPS,rules里至少要有:- seriesQuery: 'http_requests_total{namespace!="",pod!=""}',否则Adapter根本不会生成对应metric endpoint。
检查Prometheus是否真正采集到你的Pod指标
第一步:确认你的应用Pod已暴露/metrics端点,且Service有prometheus.io/scrape: "true"注解或已通过ServiceMonitor被识别。
第二步:访问Prometheus UI → Status → Targets,查找对应Pod的target状态。若显示Down且报错context deadline exceeded,大概率是Pod未就绪、防火墙阻断、或metrics路径/端口配置错误。
第三步:在Prometheus中直接执行查询:count(http_requests_total{job="your-app-job"})。若结果为0,说明指标从未被抓取;若报No data,检查指标label是否与ServiceMonitor中matchLabels完全一致——一个label键值对不匹配,整个target就会被忽略。
排查RBAC权限缺失
方法一:检查prometheus-adapter ServiceAccount绑定的ClusterRole是否授予了list/watch权限给pods和services资源。常见错误是只给了namespaced权限,但Adapter需跨命名空间发现target。
方法二:临时提权验证——将Adapter SA绑定到cluster-admin角色:kubectl create clusterrolebinding debug-adapter --clusterrole=cluster-admin --serviceaccount=monitoring:prometheus-adapter。若此时HPA恢复正常,则100%是RBAC问题,需回退并修复最小权限策略。
注意:Prometheus自身抓取Pod指标也依赖RBAC。若kubectl logs -n monitoring prometheus-operated-0 | grep "pods is forbidden"出现类似日志,说明Prometheus Operator的ServiceAccount缺少pods列表权限,需更新其ClusterRole。
定位HPA具体卡在哪一环
步骤一:查看HPA事件:kubectl describe hpa your-hpa-name,聚焦Events末尾几条。若出现FailedGetPodsMetric,说明Adapter返回空数据;若为FailedGetMetrics且提示no metrics returned,说明指标名拼写错误或Prometheus无此时间序列。
步骤二:直接调用Custom Metrics API模拟HPA行为:kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/default/pods/*/http_requests_total" | jq .。若返回NotFound,证明Adapter未生成该指标;若返回empty list,说明Adapter查到了指标但值为空——此时要回到Prometheus查原始数据是否存在。
步骤三:检查HPA中scaleTargetRef指向的Deployment是否设置了matchLabels,且与Pod模板中metadata.labels严格一致。标签不匹配会导致Adapter无法关联Pod实例,自然查不到任何pod-level指标。











