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

时间:2020-08-26 22:02:04

标签: kubernetes microservices prometheus kubernetes-helm prometheus-operator

我正在按Helm图表将Prometheus-operator部署到群集中,但是我实现了自定义服务以监视我的应用程序,我需要将服务添加到Prometheus-operator中才能查看指标数据。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

首先,您需要通过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对象将选择满足以下条件的所有ServiceMonitor

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

ServiceMonitor具有标签选择器,用于选择服务及其底层Endpoint对象。示例应用程序的Service对象通过具有app值的example-app标签选择Pod。 Service对象还指定公开指标的端口。

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

此Service对象由ServiceMonitor发现,后者以相同的方式进行选择。 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用于选择创建服务的所有名称空间。您可以使用matchNames指定特定的任何名称空间。

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

  serviceMonitorNamespaceSelector:
    matchLabels:
      prometheus: prometheus

serviceMonitorNamespaceSelector运算符中使用以上Prometheus选择带有标签prometheus: prometheus的命名空间。假设您有一个命名空间demo,并且在这个demo命名空间中创建了一个Prometheus,那么您需要使用patch在prometheus: prometheus命名空间中添加标签demo:< / p>

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

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