如何为 prometheus-operator 创建一个 ServiceMonitor?

How to create a ServiceMonitor for prometheus-operator?

最近,prometheus-operator 已升级为稳定的 helm 图表 (https://github.com/helm/charts/tree/master/stable/prometheus-operator)。

我想了解如何在 k8s 集群中通过 prometheus-operator 添加自定义应用程序进行监控。对于默认情况下提供 9252 指标的 gitlab runner 的示例将不胜感激 (https://docs.gitlab.com/runner/monitoring/#configuration-of-the-metrics-http-server)。

我有一个基本的 yaml,它显然不起作用,但也没有提供任何关于 什么 不起作用的反馈:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: gitlab-monitor
  # Change this to the namespace the Prometheus instance is running in
  namespace: default
  labels:
    app: gitlab-runner-gitlab-runner
    release: prometheus
spec:
  selector:
    matchLabels:
      app: gitlab-runner-gitlab-runner
  namespaceSelector:
    # matchNames:
    # - default
    any: true
  endpoints:
  - port: http-metrics
    interval: 15s

这是普罗米修斯配置:

> kubectl get prometheus -o yaml

...
serviceMonitorNamespaceSelector: {}
serviceMonitorSelector:
  matchLabels:
    release: prometheus
...

所以选择器应该匹配。 "not working" 我的意思是端点没有出现在 prometheus UI.

感谢 Peter 向我展示了原则上的想法并非完全错误,我找到了缺失的部分 link。作为 servicemonitor 监控服务(哈哈),我错过了创建不属于 gitlab helm chart 的服务的部分。最后,这个 yaml 为我解决了问题,指标出现在 Prometheus 中:

# Service targeting gitlab instances
apiVersion: v1
kind: Service
metadata:
  name: gitlab-metrics
  labels:
    app: gitlab-runner-gitlab-runner
spec:
  ports:
  - name: metrics # expose metrics port
    port: 9252 # defined in gitlab chart
    targetPort: metrics
    protocol: TCP
  selector:
    app: gitlab-runner-gitlab-runner # target gitlab pods
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: gitlab-metrics-servicemonitor
  # Change this to the namespace the Prometheus instance is running in
  # namespace: default
  labels:
    app: gitlab-runner-gitlab-runner
    release: prometheus
spec:
  selector:
    matchLabels:
      app: gitlab-runner-gitlab-runner # target gitlab service
  endpoints:
  - port: metrics
    interval: 15s

很高兴知道:metrics targetPort 是在 gitlab runner 图表中定义的。

我知道这个问题已经回答了。但是当使用 Helm 的 stable/prometheus-operator 图表部署在 Kubernetes 中的 Prometheus 找不到我的 ServiceMonitor 的任何活动目标时,我遇到了类似的问题。 原来我的服务暴露了一个我没有明确命名的端口:

  - protocol: TCP
    port: 8080
    targetPort: uwsgi

我可以通过定位 uwsgi 端口在 Ingress 中使用它。但似乎 ServiceMonitor 需要在 Service 中明确命名的端口,即使它与它自己的 tagetPort:

同名
  - name: uwsgi
    protocol: TCP
    port: 8080
    targetPort: uwsgi

我写了一篇关于这个问题的博客posthere

以上解决方案目前运行良好。

发布标签很重要。没有这个,Prom 无法将应用指标添加到其目标列表。

通过检查 Prometheus 本身的 ServiceMonitor,确保添加正确的发布标签。还要确保在元数据和规范部分中也将发布标签添加到服务和部署文件中。

如果遇到 Prometheus 显示目标而不是端点的情况,请看一下:https://github.com/prometheus-operator/prometheus-operator/issues/3053

这张图完美展示了 Prometheus、ServiceMonitors 和 Services 之间的连接

如果任何匹配项不正确,目标将不会显示。

阅读更多:https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/troubleshooting.md#troubleshooting-servicemonitor-changes