简介:本文详细解析Prometheus监控K8s集群的核心机制,涵盖部署架构、核心组件配置、监控指标采集与告警策略设计,帮助运维人员快速构建高可用监控体系。
K8s动态资源调度特性(如Pod自动扩缩容、节点迁移)导致传统监控工具(如Zabbix)难以精准追踪资源状态。Prometheus通过以下特性实现高效监控:
--kubelet-service和--config-file参数),自动识别Node、Pod、Service等资源变化典型案例:某金融企业K8s集群(3000+Pod)通过Prometheus联邦架构实现跨区域监控,数据采集延迟<5s,存储成本较ELK方案降低60%
# prometheus-deployment.yaml示例apiVersion: apps/v1kind: Deploymentmetadata:name: prometheus-serverspec:replicas: 2template:spec:containers:- name: prometheusimage: prom/prometheus:v2.47.2args:- --config.file=/etc/prometheus/prometheus.yml- --storage.tsdb.retention.time=30dports:- containerPort: 9090
关键配置项说明:
storage.tsdb.retention.time:建议生产环境设置≥30天--web.enable-admin-api:需谨慎开启,用于TSDB维护操作--web.external-url:配置Ingress时必须设置,解决Alertmanager跳转问题通过Thanos Query实现多Prometheus实例聚合查询,组件配置要点:
--query.auto-downsampling参数控制)--collector.disable-defaults排除无用指标)
container_cpu_usage_seconds_total{container="",pod="",namespace=""}container_memory_working_set_bytes{container="",pod="",namespace=""}
/metrics端点(需开启--authentication-token-webhook)--endpoints参数指定集群地址通过Prometheus Client库(Go/Python/Java)暴露业务指标,示例Go代码:
import ("github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/promhttp")var (requestCount = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",Help: "Total HTTP requests",},[]string{"method", "path"},))func init() {prometheus.MustRegister(requestCount)}func handler(w http.ResponseWriter, r *http.Request) {requestCount.WithLabelValues(r.Method, r.URL.Path).Inc()// ...业务逻辑}
# prometheus-rules.yaml示例groups:- name: k8s.resource.rulesrules:- alert: HighCPUUsageexpr: sum(rate(container_cpu_usage_seconds_total{container!="POD"}[5m])) by (pod) > 0.8for: 10mlabels:severity: warningannotations:summary: "Pod {{ $labels.pod }} CPU usage high"
kube_pod_container_status_restarts_total > 3
probe_success{job="blackbox-exporter"} == 0
for字段设置持续触发时间(建议5-10min)by (namespace,pod)减少告警数量
route:group_by: ['alertname', 'cluster']repeat_interval: 1h
scrape_interval)--storage.tsdb.wal-compression--storage.tsdb.path=/data/prometheus(单独挂载SSD)&step=60s| 现象 | 排查步骤 |
|---|---|
| 目标不可达 | 检查ServiceAccount权限、NetworkPolicy |
| 指标缺失 | 验证Pod annotations:prometheus.io/scrape: "true" |
| 内存溢出 | 调整--storage.tsdb.retention.size限制 |
level=info msg="Loading configuration file" file=/etc/prometheus/prometheus.ymllevel=error msg="Error reloading config" err="1 error in configuration"
curl -v http://<prometheus-ip>:9090/api/v1/targets
Label: namespaceQuery: label_values(kube_pod_info, namespace)
| 方案 | 成本 | 查询性能 | 适用场景 |
|---|---|---|---|
| Thanos | 中等 | 高 | 跨集群聚合 |
| VictoriaMetrics | 低 | 极高 | 超大规模集群 |
| InfluxDB | 高 | 中等 | 时序+日志混合存储 |
Prometheus监控K8s集群已形成完整生态链,从基础资源监控到业务指标采集均可通过标准化方案实现。未来发展方向包括:
建议运维团队定期进行监控系统健康检查(每月一次),重点关注存储增长趋势、告警规则有效性以及采集延迟指标,确保监控体系持续稳定运行。