将Prometheus集成到K8s代理监控体系
·
安装Prometheus Operator
Prometheus Operator简化了Prometheus在Kubernetes上的部署和管理。通过Helm Chart安装:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack --namespace monitoring
此命令会创建monitoring命名空间,并自动部署Prometheus、Alertmanager、Grafana及相关CRD。
配置ServiceMonitor
Prometheus Operator通过ServiceMonitor自定义资源发现并监控服务。示例YAML:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: example-app
namespace: monitoring
spec:
selector:
matchLabels:
app: example-app
endpoints:
- port: web
interval: 30s
确保目标Service的标签与selector.matchLabels匹配,端口名称需一致。
暴露Prometheus服务
通过Ingress或NodePort访问Prometheus UI。NodePort示例:
apiVersion: v1
kind: Service
metadata:
name: prometheus-service
namespace: monitoring
spec:
type: NodePort
ports:
- name: web
port: 9090
targetPort: 9090
nodePort: 30090
selector:
app.kubernetes.io/name: prometheus
访问http://<NodeIP>:30090即可查看监控数据。
集成自定义指标
若需监控应用自定义指标,需在应用中暴露Prometheus格式的/metrics端点。确保Pod注解包含以下内容:
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
Prometheus会自动发现并抓取这些端点。
配置告警规则
通过PrometheusRule资源定义告警规则。示例:
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: example-alerts
namespace: monitoring
spec:
groups:
- name: example
rules:
- alert: HighRequestLatency
expr: job:request_latency_seconds:mean5m{job="myjob"} > 0.5
for: 10m
labels:
severity: critical
annotations:
summary: "High request latency detected"
告警会自动由Alertmanager处理并发送通知。
验证监控数据
登录Grafana(默认用户名/密码为admin/prom-operator),导入Prometheus数据源,查看预置的Kubernetes仪表盘或创建自定义面板。Grafana服务可通过端口转发访问:
kubectl port-forward svc/prometheus-grafana 3000:80 -n monitoring
访问http://localhost:3000即可。
更多推荐
所有评论(0)