向 prometheus-operator 添加新的服务指标

Add new service metrics to prometheus-operator

我正在通过 Helm chart 将 Prometheus-operator 部署到我的集群,但我实现了一个自定义服务来监控我的应用程序,我需要将我的服务添加到 Prometheus-operator 以查看我的指标数据。

我该怎么做?

首先需要通过Helm或手动部署Prometheus-operator:

# By Helm:
$ helm install stable/prometheus-operator --generate-name
 
# By manual: for release `release-0.41`
kubectl apply -f  https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/release-0.41/bundle.yaml

如果您的集群启用了 RBAC,那么您需要为 Prometheus 对象安装 RBAC 内容:

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: prometheus
rules:
- apiGroups: [""]
  resources:
  - nodes
  - nodes/metrics
  - services
  - endpoints
  - pods
  verbs: ["get", "list", "watch"]
- apiGroups: [""]
  resources:
  - configmaps
  verbs: ["get"]
- nonResourceURLs: ["/metrics"]
  verbs: ["get"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus
  namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: prometheus
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: prometheus
subjects:
- kind: ServiceAccount
  name: prometheus
  namespace: default

然后需要部署Promethues对象:

apiVersion: monitoring.coreos.com/v1
kind: Prometheus
metadata:
  name: prometheus
  labels:
    prometheus: prometheus
spec:
  replicas: 1
  serviceAccountName: prometheus
  serviceMonitorSelector:
    matchLabels:
      k8s-app: prometheus
  serviceMonitorNamespaceSelector:
    matchLabels:
      prometheus: prometheus
  resources:
    requests:
      memory: 400Mi

这里,Prometheus对象将select所有满足以下条件的ServiceMonitor

  • ServiceMonitor 将具有 k8s-app: prometheus 标签。
  • ServiceMonitor 将在具有 prometheus: prometheus 标签的命名空间中创建。

ServiceMonitor 有一个标签 select 或者 select 服务及其底层端点对象。示例应用程序的服务对象 select 由具有 example-app 值的 app 标签提供 Pods。服务对象还指定公开指标的端口。

kind: Service
apiVersion: v1
metadata:
  name: example-app
  labels:
    app: example-app
spec:
  selector:
    app: example-app
  ports:
  - name: web
    port: 8080

此服务对象由 ServiceMonitor 发现,select以相同的方式发现。 app 标签必须具有值 example-app.

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: example-app
  labels:
    k8s-app: prometheus
spec:
  selector:
    matchLabels:
      app: example-app
  namespaceSelector:
    # matchNames:
    # - demo
    any: true
  endpoints:
  - port: web

这里,namespaceSelector用于selectall-namespaces创建服务的地方。您可以使用 matchNames.

指定特定的任何命名空间

您还可以根据需要在任何命名空间中创建 ServiceMonitor。但是需要在Prometheus cr的spec中指定,比如:

  serviceMonitorNamespaceSelector:
    matchLabels:
      prometheus: prometheus

上面的serviceMonitorNamespaceSelectorPrometheus运算符中用于select具有标签prometheus: prometheus的名称空间。假设你有一个命名空间 demo 并且在这个 demo 命名空间中你创建了一个 Prometheus 然后你需要使用补丁在 demo 命名空间中添加标签 prometheus: prometheus

$ kubectl patch namespace demo -p '{"metadata":{"labels": {"prometheus":"prometheus"}}}'

您可以在此处找到更多详细信息: