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必须存在(Prometheus 按此 label 查找,否则采集不到),spec.selector.matchLabels匹配目标 Service。可参考cloud-pushgateway-sm.yml、kubelet-sm.yml、node-exporter-sm.yml、istio-sm.yml、kong-sm.yml等。
监控非 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
与代码一致:本仓库的记录 / 报警规则文件为
install/kubernetes/prometheus/prometheus/prometheus-rules.yml和prometheus-rules-more.yaml。
配置 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)。