Prometheus 是一个强大的开源监控和报警工具,广泛应用于系统监控、网络监控和应用程序性能监控等领域,以下是使用 Prometheus 的基本方法和步骤:
安装 Prometheus
Prometheus 可以通过多种方式安装,包括手动安装和使用容器化工具(如 Docker)安装。
方法 1:使用 Docker 安装 Prometheus
Prometheus 提供了 Docker 镜像,安装非常简单。
# 启动 Prometheus docker run -d --name prometheus -p 909:909 -p 9093:9093 prom/prometheus
启动后,可以通过 http://localhost:909 访问 Prometheus 界面。
方法 2:手动安装
如果不使用 Docker,可以手动安装。
-
下载 Prometheus
- 从 Prometheus 官方网站 下载二进制文件。
-
配置 Prometheus
-
将 Prometheus 二进制文件放在适当的目录中(
/usr/local/prometheus)。 -
创建配置文件
prometheus.yml:global: listen_address: '...' port: 909 # 收集器配置 alerting: enabled: true # 目标配置(示例) targets: - { url: 'http://localhost:808', labels: { app: 'http-server' } }
-
-
运行 Prometheus
./prometheus -config.file prometheus.yml
配置 Prometheus
Prometheus 的配置文件包含目标、收集器和告警规则等内容。
配置文件结构
global:
# 全局配置,如 listen_address 和 port
listen_address: '...'
port: 909
scraping:
# 数据收集配置
interval_seconds: 15 # 抽取数据的时间间隔
targets:
- { url: 'http://localhost:808', labels: { app: 'http-server' } }
# 收集器配置(可选)
collectors:
- name: 'prometheus'
interval_seconds: 30
http_client_config:
http_timeout: 5s
retry_count: 3
alerting:
enabled: true
alertmanager_interval: 5m
添加目标
Prometheus 的目标是指需要监控的资产(如服务器、数据库、应用程序等),常见目标类型包括:
- HTTP/HTTPS 服务
targets: - { url: 'http://localhost:808', labels: { app: 'http-server' } } - TCP/UDP 服务
targets: - { url: 'tcp://localhost:80', labels: { app: 'http-server' } } - 本地文件监控
targets: - { path: '/var/log/prometheus.log', labels: { app: 'prometheus' } }
配置告警规则
Prometheus 使用告警规则来触发报警,当目标的数据不符合预期时,Prometheus 会生成告警。
rules:
- alert: '服务器负载过高'
expr: 'job:prometheus scraped:2m >= 3'
for: '5m'
labels:
severity: 'critical'
annotations:
summary: '服务器负载过高'
使用 Prometheus
-
通过 Web 界面
- 启动 Prometheus 后,访问
http://localhost:909,即可看到 Prometheus 的 Web 界面。
- 启动 Prometheus 后,访问
-
使用 CLI
- Prometheus 提供一个命令行工具
prom,可以用于查询数据。# 查询目标状态 prom target
查询某个指标
prom query 'http_requests_total{path="/"}'
- Prometheus 提供一个命令行工具
-
集成 Grafana
Prometheus 与 Grafana 结合使用,用于可视化监控数据,Grafana 是 Prometheus 的标准可视化工具,可以通过配置 Prometheus 来集成。
高级使用方法
-
集成 Alertmanager
- Prometheus 提供了 Alertmanager 用于处理告警,例如发送通知和触发自动化操作。
alerting: alertmanager_interval: 5m alertmanager_configs: - target: 'http://localhost:9093' from: 'default' resolve_timeout: 5m
- Prometheus 提供了 Alertmanager 用于处理告警,例如发送通知和触发自动化操作。
-
扩展数据收集
- 使用 Prometheus 的黑盒(Blackbox)收集外部服务的数据。
collecteurs: - name: 'blackbox' interval_seconds: 60 http_client_config: http_timeout: 5s retry_count: 3 targets: - { url: 'http://localhost:80', labels: { app: 'web-app' } }
- 使用 Prometheus 的黑盒(Blackbox)收集外部服务的数据。
-
配置多个 Prometheus 实例
如果需要高可用性,可以部署多个 Prometheus 实例,并使用 Prometheus 网关(如 Prometheus HAProxy)进行负载均衡和故障转移。
故障排除
- 配置错误:检查配置文件是否正确,确保目标 URL 和端口正确。
- 端口问题:确保 Prometheus 和 Alertmanager 的端口(909 和 9093)没有被防火墙阻止。
- 权限问题:确保 Prometheus 有足够的权限访问目标资源(如日志文件、网络端口等)。
通过以上方法,你可以开始使用 Prometheus 进行系统监控和告警,Prometheus 的灵活性和可扩展性使其成为现代监控工具的首选。









