您好,登录后才能下订单哦!
# 监控利器Prometheus怎么用
## 一、Prometheus概述
### 1.1 什么是Prometheus
Prometheus是由SoundCloud开发的开源监控系统和时间序列数据库,于2012年创建并于2015年正式发布。作为Cloud Native Computing Foundation(CNCF)的毕业项目,它已成为云原生时代最流行的监控解决方案之一。
核心特性:
- 多维数据模型(时间序列由metric名称和键值对标识)
- 灵活的查询语言PromQL
- 不依赖分布式存储,单个服务器节点自治
- 通过HTTP拉取(pull)方式采集时间序列数据
- 支持通过中间网关推送(push)时间序列数据
- 支持服务发现或静态配置发现目标
- 多种图形和仪表板支持
### 1.2 核心组件架构

典型部署包含以下组件:
1. **Prometheus Server**:主服务器,负责抓取和存储时间序列数据
2. **Client Libraries**:客户端库,用于检测应用程序代码
3. **Push Gateway**:支持短生命周期任务的网关
4. **Exporters**:专用数据导出器(如Node Exporter)
5. **Alertmanager**:处理警报的独立组件
6. **Web UI/Grafana**:数据可视化工具
## 二、安装与部署
### 2.1 二进制安装(Linux)
```bash
# 下载最新版本
wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-*
# 启动服务
./prometheus --config.file=prometheus.yml
docker run -d -p 9090:9090 \
-v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
使用Helm chart快速部署:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/prometheus
global:
scrape_interval: 15s # 默认抓取间隔
evaluation_interval: 15s # 规则评估间隔
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node'
static_configs:
- targets: ['node-exporter:9100']
配置项 | 说明 | 示例值 |
---|---|---|
scrape_interval | 抓取间隔 | 15s |
scrape_timeout | 抓取超时 | 10s |
metrics_path | 指标路径 | /metrics |
honor_labels | 标签处理策略 | true/false |
支持多种服务发现方式:
# Kubernetes服务发现示例
- job_name: 'kubernetes-nodes'
kubernetes_sd_configs:
- role: node
relabel_configs:
- source_labels: [__address__]
regex: '(.*):10250'
replacement: '${1}:9100'
target_label: __address__
每个时间序列由以下部分组成: - 指标名称(metric name) - 标签集合(key-value pairs) - 时间戳 - 样本值
示例格式:
http_requests_total{method="POST",handler="/api"} 1027 1395066363000
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requests = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
})
)
func init() {
prometheus.MustRegister(requests)
}
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
# 选择所有时间序列
http_requests_total
# 按标签过滤
http_requests_total{job="api-server",status!="200"}
# 范围查询
http_requests_total[5m]
# 算术运算
memory_usage_bytes / 1024 / 1024
# 比较运算
http_requests_total > 1000
# 逻辑运算
up{job="prometheus"} or up{job="node-exporter"}
# 求和
sum(http_requests_total)
# 按维度聚合
sum by(instance)(http_requests_total)
# 分位数计算
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
创建alert.rules文件:
groups:
- name: example
rules:
- alert: HighErrorRate
expr: job:request_error_rate:avg5m{job="myjob"} > 0.5
for: 10m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.instance }}"
description: "Error rate is {{ $value }}"
alertmanager.yml示例:
route:
group_by: ['alertname']
receiver: 'email-notifications'
receivers:
- name: 'email-notifications'
email_configs:
- to: 'admin@example.com'
from: 'alertmanager@example.com'
smarthost: 'smtp.example.com:587'
auth_username: 'user'
auth_password: 'password'
# 抑制规则示例
inhibit_rules:
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname']
Prometheus内置的Console Template示例:
<h1>Node Overview</h1>
<table>
<tr>
<th>Instance</th>
<th>CPU Usage</th>
<th>Memory</th>
</tr>
{{ range query "up" }}
<tr>
<td>{{ .Labels.instance }}</td>
<td>{{ printf "%.2f" (query "rate(node_cpu_seconds_total[1m])" }}</td>
<td>{{ template "memoryUsage" . }}</td>
</tr>
{{ end }}
</table>
部署方案: 1. Node Exporter:节点指标 2. kube-state-metrics:K8S资源状态 3. cAdvisor:容器指标
使用blackbox_exporter进行: - HTTP/HTTPS检查 - TCP端口检测 - ICMP ping测试
配置示例:
modules:
http_2xx:
prober: http
timeout: 5s
http:
valid_status_codes: [200]
命名规范:
_total
后缀表示计数器_seconds
表示时间单位标签设计原则:
资源规划:
安全建议:
up == 1
count(metric_name)
scrape_duration_seconds
count by(__name__)({__name__=~".+"})
检测作为云原生监控的事实标准,Prometheus凭借其强大的数据模型、灵活的查询语言和活跃的生态系统,已成为现代监控体系的核心组件。通过本文的全面介绍,希望您已经掌握从基础部署到高级配置的全套技能。随着v2.40版本引入的Native Histograms等新特性,Prometheus仍在持续进化,值得每个运维和开发人员深入学习和应用。
延伸阅读: - 官方文档:https://prometheus.io/docs - Prometheus书籍:《Prometheus: Up & Running》 - 社区论坛:https://prometheus.io/community “`
注:本文实际字数为约4800字,包含代码示例、配置片段和表格等结构化内容。可根据需要调整各部分详细程度或添加更多实战案例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。