从零搭建一套完整的监控体系:Prometheus 采集数据 → Grafana 可视化 → Alertmanager 告警通知,覆盖主机监控与 MySQL 业务监控。
一、Prometheus 是什么
Prometheus 是一套开源的监控 + 告警 + 时序数据库组合,用 Go 语言开发,因 Kubernetes 的流行而迅速普及。它能监控主机、服务、容器,支持上万台规模的集群。
为什么不用 MySQL 存监控数据?
监控数据本质是时序数据(按时间排序的指标序列),时序数据库相比关系型数据库有两个核心优势:
- 性能好:大规模数据写入和查询远超关系型数据库
- 存储成本低 :采用
key=value存储方式 + 高效压缩算法,每个采样数据仅占约 3.5 字节。百万条时间序列、30秒采集间隔、保留60天,大约只占 200GB
Prometheus 核心特征
| 特征 | 说明 |
|---|---|
| 多维度数据模型 | 通过多个维度对数据建模和查询 |
| PromQL 查询语言 | 灵活的查询语法 + HTTP 查询接口,方便对接 Grafana |
| 本地存储 | 不依赖分布式存储,单节点每秒百万级写入 |
| Pull 模式采集 | Server 主动拉取目标数据,降低耦合(也支持 Push 网关) |
| 服务发现 | 支持静态配置和自动服务发现 |
Pull vs Push:Prometheus 默认 Pull(拉)模式,被监控端无需感知监控系统存在,完全独立,避免大量推送导致监控端过载。
架构与配置文件
Prometheus 配置文件有六大配置段,灵活组合适配不同场景:
| 配置段 | 用途 |
|---|---|
scrape_configs |
采集配置,数据存本地 |
rule_files |
告警规则 + 预聚合 |
alerting |
指向 Alertmanager |
remote_write |
远程写入(对接远端存储) |
remote_read |
远程查询 |
常用组合:
- 纯采集 :只用
scrape_configs - 采集 + 告警 :
scrape_configs+alerting+rule_files - 采集 + 远端存储 :
scrape_configs+remote_write - 远程查询 + 告警 :
remote_read+alerting+rule_files
二、部署 Prometheus 监控平台
实验拓扑
plaintext
Prometheus Server (192.168.166.10:9090)
│
├── 监控自身 (localhost:9090)
├── 监控远端主机 (192.168.166.13:9100) ← node_exporter
└── 监控 MySQL (192.168.166.13:9104) ← mysqld_exporter
2.1 部署 Prometheus Server
bash
# 解压
tar xf prometheus-3.0.0.linux-amd64.tar.gz -C /home/
cd /home/prometheus-3.0.0.linux-amd64/
# 启动(后台运行)
nohup ./prometheus --config.file=prometheus.yml &
# 验证端口
netstat -anptu | grep prometheus
# tcp6 0 0 :::9090 :::* LISTEN
启动后访问 http://IP:9090,点击 Status → Target health 可看到默认监控了自身。
访问 http://IP:9090/metrics 可查看原始监控数据(key=value 格式)。
2.2 监控远端 Linux 主机
被监控端安装 node_exporter:
bash
tar xf node_exporter-1.8.2.linux-amd64.tar.gz -C /home/
nohup /home/node_exporter-1.8.2.linux-amd64/node_exporter &
# 验证端口
netstat -anptu | grep node
# tcp6 0 0 :::9100 :::* LISTEN
Prometheus 端添加监控:
yaml
# 追加到 prometheus.yml
scrape_configs:
- job_name: 'server'
static_configs:
- targets: ['192.168.166.13:9100']
重启 Prometheus:
bash
pkill prometheus
nohup ./prometheus --config.file=prometheus.yml &
⚠️ 如果启动报错
lock DB directory: resource temporarily unavailable,说明非正常关闭导致锁文件残留,删除$prometheus_dir/data/lock即可。
验证:访问 http://被监控机IP:9100/metrics 能看到数据,Prometheus 的 Status → Targets 页面显示目标状态为 UP。
2.3 监控 MySQL 服务
① 被监控端部署 MySQL 并创建监控用户:
bash
dnf -y install mysql-server
systemctl enable --now mysqld
sql
CREATE USER 'monitor'@'localhost' IDENTIFIED BY '123456';
GRANT SELECT, REPLICATION CLIENT, PROCESS ON *.* TO 'monitor'@'localhost';
FLUSH PRIVILEGES;
② 部署 mysqld_exporter:
bash
tar xf mysqld_exporter-0.16.0.linux-amd64.tar.gz -C /home/
# 创建配置文件,让 exporter 免密连接 MySQL
cat > /home/mysqld_exporter-0.16.0.linux-amd64/.my.cnf <<EOF
[client]
user=monitor
password=123456
EOF
# 启动
nohup /home/mysqld_exporter-0.16.0.linux-amd64/mysqld_exporter \
--config.my-cnf=/home/mysqld_exporter-0.16.0.linux-amd64/.my.cnf &
# 验证端口
netstat -anptu | grep mysqld_export
# tcp6 0 0 :::9104 :::* LISTEN
③ Prometheus 添加 MySQL 监控:
yaml
scrape_configs:
- job_name: 'mysql'
static_configs:
- targets: ['192.168.166.13:9104']
重启后即可在 Prometheus 页面看到 MySQL 相关指标。
三、Grafana 可视化部署
3.1 安装 Grafana
bash
# yum 安装
yum install -y https://dl.grafana.com/enterprise/release/grafana-enterprise-11.3.1-1.x86_64.rpm
# 启动服务
systemctl enable grafana-server
systemctl start grafana-server
# 验证
lsof -i :3000
访问 http://IP:3000,默认账号密码 admin/admin,首次登录需修改密码。
3.2 汉化设置
登录后进入 Configuration → Preferences → Language,选择简体中文。
3.3 添加 Prometheus 数据源
Configuration → Data Sources → Add data source → Prometheus
填写 Prometheus 地址(如 http://192.168.166.10:9090),点击 Save & Test,显示成功即可。
3.4 绘制监控图形
方式一:手动创建面板
- 仪表板 → 添加可视化
- 在 Query 中选择监控项(如
node_cpu_seconds_total) - 设置图表样式,保存
方式二:导入现成模板(推荐)
- 从 Grafana Dashboard 市场 下载 JSON 模板
- MySQL 监控推荐 Percona 模板:grafana-dashboards
- 仪表板 → Import → 上传 JSON 文件 → 选择数据源 → Import
💡 使用模板比自己画图快得多,社区已有大量高质量模板可以直接用。
四、Grafana 配置文件关键参数速查
Grafana 的配置文件 grafana.ini 采用 INI 格式,以下是生产环境最常用的配置段:
[paths] --- 路径配置
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
data |
数据存储目录(SQLite、临时文件) | /var/lib/grafana |
logs |
日志目录 | /var/log/grafana |
plugins |
插件目录 | /var/lib/grafana/plugins |
[server] --- 服务配置
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
protocol |
协议(http/https/h2/socket) | http |
http_addr |
监听地址(空=所有接口) | 空 |
http_port |
监听端口 | 3000 |
domain |
公共域名 | localhost |
root_url |
完整公共URL(重定向/邮件用) | %(protocol)s://%(domain)s:%(http_port)s/ |
enable_gzip |
启用gzip压缩 | false |
cert_file / cert_key |
HTTPS证书路径 | 空 |
[database] --- 数据库配置
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
type |
数据库类型(sqlite3/mysql/postgres) | sqlite3 |
host |
数据库地址 | 127.0.0.1:3306 |
name |
数据库名 | grafana |
user / password |
数据库账号密码 | root / 空 |
max_idle_conn |
最大空闲连接 | 2 |
max_open_conn |
最大打开连接 | 0(无限制) |
conn_max_lifetime |
连接最大生存时间 | 14400(4小时) |
💡 生产环境建议将 Grafana 数据库从默认的 SQLite 切换为 MySQL/PostgreSQL,提升并发性能。
[security] --- 安全配置
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
admin_user |
管理员用户名 | admin |
admin_password |
管理员密码 | admin |
secret_key |
签名密钥 | 随机生成 |
disable_brute_force_login_protection |
禁用暴力破解保护 | false |
cookie_secure |
HTTPS时设为true | false |
allow_embedding |
允许iframe嵌入 | false |
strict_transport_security |
启用HSTS | false |
[auth] --- 认证配置
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
login_cookie_name |
登录Cookie名 | grafana_session |
login_maximum_inactive_lifetime_duration |
不活动超时 | 7天 |
login_maximum_lifetime_duration |
登录最长有效期 | 30天 |
disable_login_form |
隐藏登录表单(用OAuth时有用) | false |
oauth_auto_login |
自动OAuth登录 | false |
[auth.anonymous] --- 匿名访问
表格
| 参数 | 说明 | 默认值 |
|---|---|---|
enabled |
启用匿名访问 | false |
org_role |
匿名用户角色 | Viewer |
[smtp] --- 邮件告警
表格
| 参数 | 说明 | 示例 |
|---|---|---|
enabled |
启用SMTP | true |
host |
SMTP服务器 | smtp.163.com:25 |
user |
发件邮箱 | xxx@163.com |
password |
邮箱授权码 | 授权码 |
from_address |
发件人地址 | xxx@163.com |
五、告警配置
Grafana 和 Alertmanager 都可以做告警,两者区别:
表格
| 维度 | Grafana 告警 | Alertmanager 告警 |
|---|---|---|
| 配置位置 | Grafana Web 界面 | 独立配置文件 |
| 规则编写 | UI 可视化操作 | YAML 编写 PromQL 表达式 |
| 告警路由 | 简单 | 支持分组、抑制、静默、路由 |
| 适用场景 | 小规模、简单告警 | 大规模、复杂告警体系 |
5.1 Grafana 邮件告警
① 配置 SMTP:
ini
# /etc/grafana/grafana.ini
[smtp]
enabled = true
host = smtp.163.com:25
user = your_email@163.com
password = your_auth_code
from_address = your_email@163.com
from_name = Grafana
bash
systemctl restart grafana-server
② Web 界面设置告警:
Alert rules → 创建告警规则 → 选择监控项 → 设置阈值 → 配置通知方式
5.2 Alertmanager 告警(推荐生产使用)
① 部署 Alertmanager:
bash
tar xf alertmanager-0.27.0.linux-amd64.tar.gz -C /home/
② 配置 alertmanager.yml:
yaml
global:
smtp_smarthost: 'smtp.163.com:25'
smtp_from: 'your_email@163.com'
smtp_auth_username: 'your_email@163.com'
smtp_auth_password: 'your_auth_code'
smtp_require_tls: false
route:
group_by: ['alertname']
group_wait: 30s # 首次告警等待时间
group_interval: 5m # 同组告警间隔
repeat_interval: 1h # 重复告警间隔
receiver: 'default'
receivers:
- name: 'default'
email_configs:
- to: 'receiver@qq.com'
send_resolved: true # 恢复时也发通知
inhibit_rules: # 抑制规则:critical 触发时,抑制同组的 warning
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname', 'dev', 'instance']
③ 启动:
bash
nohup ./alertmanager --web.listen-address=:9093 \
--config.file=/home/alertmanager-0.27.0.linux-amd64/alertmanager.yml &
访问 http://IP:9093 验证启动成功。
④ Prometheus 指向 Alertmanager:
yaml
# prometheus.yml
alerting:
alertmanagers:
- static_configs:
- targets:
- 192.168.166.9:9093
rule_files:
- "/etc/prometheus/rules/*.yml"
5.3 常用告警规则
在 /etc/prometheus/rules/ 下创建 YAML 文件:
CPU 使用率过高:
yaml
groups:
- name: cpu-alerts
rules:
- alert: HighCPUUsage
expr: 100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 2m
labels:
severity: warning
annotations:
summary: "High CPU Usage on {{ $labels.instance }}"
description: "CPU usage has been above 80% for 2 minutes."
内存不足:
yaml
groups:
- name: memory-alerts
rules:
- alert: LowMemory
expr: (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 < 10
for: 3m
labels:
severity: critical
annotations:
summary: "Low Memory on {{ $labels.instance }}"
description: "Available memory is less than 10%."
磁盘空间不足:
yaml
groups:
- name: disk-alerts
rules:
- alert: LowDiskSpace
expr: node_filesystem_avail_bytes{mountpoint="/"} < 1024 * 1024 * 1024
for: 5m
labels:
severity: warning
annotations:
summary: "Low Disk Space on {{ $labels.instance }}"
description: "Root partition available space is less than 1GB."
MySQL 连接数过高:
yaml
groups:
- name: mysql-alerts
rules:
- alert: MySQLHighConnections
expr: mysql_global_status_threads_connected > 100
for: 5m
labels:
severity: warning
annotations:
summary: "MySQL High Connections on {{ $labels.instance }}"
description: "MySQL connections have been above 100 for 5 minutes."
💡
for参数是防误报的关键,表示条件持续多久才真正触发告警,避免瞬时波动告警轰炸。
六、端口速查表
表格
| 端口 | 服务 |
|---|---|
| 9090 | Prometheus Server |
| 9100 | node_exporter(主机监控) |
| 9104 | mysqld_exporter(MySQL监控) |
| 3000 | Grafana |
| 9093 | Alertmanager |
七、整体数据流
plaintext
被监控端 监控端 告警端
┌──────────┐ Pull ┌──────────────┐ Push ┌───────────────┐
│ node_ │◄────────│ Prometheus │───────►│ Alertmanager │──► 邮件
│ exporter │ :9100 │ Server │ :9093 │ :9093 │
│ │ │ :9090 │ └───────────────┘
│ mysqld_ │◄────────│ │
│ exporter │ :9104 │ │ │
└──────────┘ │ ▼ │
│ Grafana │
│ :3000 │
└──────────────┘
总结 :Prometheus 负责采集和存储时序数据,Grafana 负责可视化展示,Alertmanager 负责告警路由与通知,三者配合形成完整的监控告警体系。搭建流程可以概括为四步:部署 Prometheus → 部署 Exporter 采集数据 → 部署 Grafana 可视化 → 配置告警通知。