概述
本文章主要记录如何把自定义的pod 服务接入prometheus
前置条件
在启用指标和仪表板之前,请确保集群中已安装kube-prometheus-stack
部署服务
部署pod
apiVersion: v1
kind: Pod
metadata:
name: example-app
labels:
app: example-app # 此标签用于 PodMonitor 的 selector
namespace: monitoring
spec:
containers:
- name: example-container
image: golang:1.24
command:
- /bin/sh
- -c
- sleep 10d
ports:
- name: web # 这里的名称与 PodMonitor 中的 port 字段匹配
containerPort: 2112 # 这个端口是暴露给外部的
nodeSelector:
kubernetes.io/hostname: i32e16214.sqa.eu95
启动服务
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}
kubectl exec -it example-app -n monitoring
# 进入pod 容器, 将代码写入 main.go
vi main.go
# 写入GOPROXY 环境变量(为了下包)
export GOPROXY='https://goproxy.cn,direct'
go mod init
go mod tidy
go run main.go
# 切回host,测试是否有输出
curl http://{POD_IP}:2112/metrics
定义监控规则
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: example-app
namespace: monitoring
labels:
team: frontend
spec:
selector:
matchLabels:
app: example-app
podMetricsEndpoints:
- port: web # 指定 Pod 中的端口名称
path: /metrics # 指定抓取指标的路径
interval: 30s # 抓取频率Ï
最终结果
可以在 status>target 中看下下面的图, 代表接入成公
总结
1、定义监控规则时, 需要matchLabels 和 pod labels 匹配 2、定义规则的port 应该和 服务port 一直 (如:上的web与服务的port name一致)