介绍

上一篇基于Prometheus-Operator部署了Prometheus、AlertManager:原文地址

部署微服务

采用Prometheus官方提供的基于golang编写的微服务示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
apiVersion: apps/v1
kind: Deployment
metadata:
name: example-app
spec:
replicas: 3
selector:
matchLabels:
app: example-app
template:
metadata:
labels:
app: example-app
spec:
containers:
- name: example-app
image: quay.io/brancz/prometheus-example-app:v0.5.0
ports:
- name: web
containerPort: 8080

---
kind: Service
apiVersion: v1
metadata:
name: example-app
labels:
app: example-app
jobname: app # servicemonitor 使用
spec:
selector:
app: example-app
ports:
- name: web
port: 8080
nodePort: 30080 # 外部端口
type: NodePort # 演示用,实际微服务为ClusterIP

访问:http://nodeip:30080/metrics

可以看到已经将微服务本身的监控信息暴露出去

部署ServiceMonitor

告诉Prometheus基于service获取

官方api参考:https://prometheus-operator.dev/docs/api-reference/api/#monitoring.coreos.com/v1.ServiceMonitor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
labels:
app: example-app # ServiceMonitor 的标签,用于标识和选择
name: example-app # ServiceMonitor 的名称
spec:
endpoints:
- port: web # 抓取指标的端口名称(对应 Service 中定义的端口名称)
interval: 15s # 抓取指标的间隔时间
path: /metrics # 指定自定义路径
scheme: http # 使用 HTTP 协议抓取指标
tlsConfig:
insecureSkipVerify: true # 跳过 TLS 证书验证(用于自签名证书场景)
selector:
matchLabels:
app: example-app
jobLabel: jobname # 用于 Prometheus 中 job 标签的值,取自 Service 的该标签,不指定时,默认使用service名称
selector:
matchLabels:
app: example-app # 选择带有 app=example-app 标签的 Service

访问:http://nodeip:30900/targets

查看servicemonitor已经将指标获取到,并且job名称为service标签中设置的名称