我正在通过Helm chart将Prometheus操作符部署到我的集群中,但我实现了一个自定义服务来监控我的应用程序,我需要将我的服务添加到Prometheus操作符中以查看我的度量数据。
我该怎么做?
首先,您需要通过Helm或手动部署Prometheus操作员:
# 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
标签- 将在具有
prometheus: prometheus
标签的名称空间中创建ServiceMonitor
ServiceMonitor有一个标签选择器,用于选择服务及其底层Endpoint对象。示例应用程序的Service对象通过具有example-app
值的app
标签来选择Pods。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
在Prometheus
运算符中使用上述serviceMonitorNamespaceSelector
来选择具有标签prometheus: prometheus
的名称空间。假设您有一个名称空间demo
,并且在这个demo
名称空间中您创建了一个Prometheus
,那么您需要使用补丁在demo
名称空间中添加标签prometheus: prometheus
:
$ kubectl patch namespace demo -p '{"metadata":{"labels": {"prometheus":"prometheus"}}}'
您可以在这里找到更多详细信息:
头盔:https://github.com/helm/charts/tree/master/stable/prometheus-operator
手动:https://github.com/prometheus-operator/prometheus-operator/blob/release-0.41/Documentation/user-guides/getting-started.md
名称空间选择器:https://github.com/prometheus-operator/prometheus-operator/blob/master/Documentation/design.md