ServiceMonitor 配置与调试
通过 exporter / pushgateway / 自定义 metric / ingress-nginx / node-exporter / kubelet,都已经形成 metrics 接口,并且有对应的 Service 提供服务。我们可以通过这个 Service 查看组件是否采集到数据。要把这些数据采集到 Prometheus 中,就需要编写 ServiceMonitor 文件。
ServiceMonitor 写法
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
labels:
k8s-app: app1 # 这里必须是 k8s-app,不然 prometheus 采集不了该资源
name: app1
namespace: monitoring
spec:
endpoints:
- interval: 30s
path: /metrics
port: http # 端口号只能是字符串,是 pod 中定义的端口 name
jobLabel: k8s-app
namespaceSelector:
matchNames:
- yournamespace
selector:
matchLabels:
app: app1 # 匹配 service
说明:ServiceMonitor 集中在
install/kubernetes/prometheus/servicemonitor/,约定metadata.labels.k8s-app必须存在,spec.selector.matchLabels匹配目标 Service。可参考cloud-pushgateway-sm.yml、kubelet-sm.yml、node-exporter-sm.yml、istio-sm.yml、kong-sm.yml等。为什么必须有
k8s-app:Prometheus CR(prometheus/prometheus-main.yml)通过serviceMonitorSelector: matchExpressions: [key: k8s-app, operator: Exists]挑选 ServiceMonitor,只有带此 label 的才会被 Operator 同步给 Prometheus,否则采集不到。
监控非 K8s 内应用
对于 K8s 内的应用,可以通过上面的 ServiceMonitor 采集 Service 暴露的 metrics 接口;对于非 K8s 内的应用,需要自己编写 Prometheus 的配置文件。
其实上面的监控也是通过 prometheus-operator 自动生成 Prometheus 的配置文件,类似可参考下面的 ConfigMap。需要自己熟悉 Prometheus 的记录规则(recording rules)与报警规则(alerting rules)。
apiVersion: v1
kind: ConfigMap
metadata:
labels:
app: prometheus-7.3.0
name: prometheus-config
namespace: monitoring
data:
prometheus.yml: |
global:
evaluation_interval: 15s
scrape_interval: 15s
scrape_timeout: 10s
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
rule_files: # prometheus-rules.yaml
# - "first_rules.yml"
# - "second_rules.yml"
scrape_configs:
- job_name: prometheus
static_configs:
- targets:
- localhost:9090
说明:在 Operator 体系下,集群外应用无需手改配置文件,可用 Prometheus CR 的
additionalScrapeConfigs字段挂载额外的原生scrape_configs(本仓库指向prometheus-configConfigMap 的prometheus-additional.yaml)。记录 / 报警规则则用PrometheusRuleCRD 定义,文件为install/kubernetes/prometheus/prometheus/prometheus-rules.yml和prometheus-rules-more.yaml,需带prometheus: k8s、role: alert-rules两个 label 才会被 Prometheus CR 的ruleSelector选中。
配置 ServiceMonitor 后调试
在配置 ServiceMonitor 之前,要先通过 curl service:port/metrics 查看是否正常采集了数据。如果正常采集了数据,后面的监控才能正常。
配置了 ServiceMonitor 以后,稍微等一两分钟,可以在 Prometheus 中查看是否配置成功。如果 Configuration 中包含了你的 ServiceMonitor 相关配置(解析成 Prometheus 配置以后的样子),才表示你的 SM 配置语法正确,并且配置同步到了 Prometheus 中。

进入 Service Discovery,可以看到你配置的 ServiceMonitor 匹配到了多少个 Pod。(注意:由于 ServiceMonitor 文件中匹配的是 Service,Prometheus 会自动获取 Service 下面绑定的 Pod,并将 Pod 作为 metrics 接口的访问地址,并且会随着 Service 下 Pod 的变更而变更。)

进入 Targets,查看每个 Pod 的 metrics 接口是否能正常拿到数据。如果能拿到数据,Pod 状态为绿色。

有了数据就可以在 Graph 中查看到指标数据,并配置 Grafana 了(见 告警与 Grafana)。