监控系统的价值取决于告警质量——告警太多产生”告警疲劳”,重要告警被忽视;告警太少故障时无人知晓。本文帮你建立分级合理、通知准确的生产级Prometheus告警体系。
一、告警质量原则
- 告警必须可操作:每条告警都应该有对应的处理手册(Runbook),收到告警知道该做什么
- 告警反映用户影响:优先告警用户可感知的问题(网站慢/不可用),而非系统指标(CPU高)
- 避免抖动型告警:使用
for持续时间确认,避免瞬时波动触发误报 - 告警分级:P1(立即处理)→ P2(1小时内)→ P3(工作日内)
二、完整告警规则文件
<code"># /etc/prometheus/rules/server-alerts.yml
groups:
# ========== P1:严重告警(立即处理,电话+钉钉)==========
- name: critical
interval: 30s
rules:
# 服务器完全无响应
- alert: InstanceDown
expr: up == 0
for: 2m
labels:
severity: critical
team: ops
annotations:
summary: "🔴 服务器无响应 {{ $labels.instance }}"
description: "{{ $labels.instance }} 已无响应超过2分钟,请立即检查"
runbook: "https://wiki.yourdomain.com/runbooks/instance-down"
# 网站HTTP接口不可用
- alert: WebsiteDown
expr: probe_success{job="blackbox"} == 0
for: 2m
labels:
severity: critical
annotations:
summary: "🔴 网站不可访问 {{ $labels.instance }}"
description: "网站 {{ $labels.instance }} 连续2分钟探测失败"
# SSL证书即将过期(不可用)
- alert: SSLCertExpiredCritical
expr: probe_ssl_earliest_cert_expiry{job="blackbox"} - time() < 7 * 24 * 3600 for: 1h labels: severity: critical annotations: summary: "🔴 SSL证书7天内过期 {{ $labels.instance }}" description: "{{ $labels.instance }} 的SSL证书将在 {{ $value | humanizeDuration }} 后过期" # 磁盘即将写满(95%以上) - alert: DiskCritical expr: | (1 - node_filesystem_avail_bytes{mountpoint="/", fstype!="tmpfs"} / node_filesystem_size_bytes{mountpoint="/", fstype!="tmpfs"}) * 100 > 95
for: 5m
labels:
severity: critical
annotations:
summary: "🔴 磁盘极度紧张 {{ $labels.instance }}"
description: "磁盘使用率 {{ $value | printf \"%.1f\" }}%,可能导致服务中断"
# OOM killer触发(进程被杀死)
- alert: OOMKillerActive
expr: increase(node_vmstat_oom_kill[5m]) > 0
for: 0m
labels:
severity: critical
annotations:
summary: "🔴 OOM Killer触发 {{ $labels.instance }}"
description: "服务器内存耗尽,进程被强制终止,请立即处理"
# ========== P2:高优告警(1小时内处理,钉钉+邮件)==========
- name: warning
interval: 60s
rules:
# CPU持续高负载
- alert: HighCPULoad
expr: |
100 - (avg by(instance) (
irate(node_cpu_seconds_total{mode="idle"}[5m])
) * 100) > 85
for: 10m
labels:
severity: warning
annotations:
summary: "⚠️ CPU使用率过高 {{ $labels.instance }}"
description: "CPU使用率 {{ $value | printf \"%.1f\" }}% 持续10分钟,请检查高CPU进程"
# 内存使用率高
- alert: HighMemoryUsage
expr: |
(1 - node_memory_MemAvailable_bytes /
node_memory_MemTotal_bytes) * 100 > 90
for: 5m
labels:
severity: warning
annotations:
summary: "⚠️ 内存使用率过高 {{ $labels.instance }}"
description: "内存使用率 {{ $value | printf \"%.1f\" }}%,已触发Swap或接近OOM"
# 磁盘使用率高
- alert: DiskWarning
expr: |
(1 - node_filesystem_avail_bytes{mountpoint="/"} /
node_filesystem_size_bytes{mountpoint="/"}) * 100 > 85
for: 10m
labels:
severity: warning
annotations:
summary: "⚠️ 磁盘使用率过高 {{ $labels.instance }}"
description: "磁盘使用率 {{ $value | printf \"%.1f\" }}%,请清理或扩容"
# MySQL连接数接近上限
- alert: MySQLConnectionsHigh
expr: |
mysql_global_status_threads_connected /
mysql_global_variables_max_connections * 100 > 80
for: 5m
labels:
severity: warning
annotations:
summary: "⚠️ MySQL连接数过高 {{ $labels.instance }}"
description: "MySQL连接使用率 {{ $value | printf \"%.1f\" }}%,可能影响新连接"
# HTTP 5xx错误率高
- alert: HighHTTPErrorRate
expr: |
sum(rate(nginx_http_requests_total{status=~"5.."}[5m])) by (instance) /
sum(rate(nginx_http_requests_total[5m])) by (instance) * 100 > 5
for: 5m
labels:
severity: warning
annotations:
summary: "⚠️ HTTP 5xx错误率过高 {{ $labels.instance }}"
description: "5xx错误率 {{ $value | printf \"%.1f\" }}%,请检查应用错误日志"
# ========== P3:低优告警(工作日内处理,邮件)==========
- name: info
interval: 5m
rules:
# SSL证书30天内过期
- alert: SSLCertExpiringSoon
expr: probe_ssl_earliest_cert_expiry{job="blackbox"} - time() < 30 * 24 * 3600
for: 1h
labels:
severity: info
annotations:
summary: "ℹ️ SSL证书30天内过期 {{ $labels.instance }}"
description: "证书将在 {{ $value | humanizeDuration }} 后过期,请检查自动续签"
# 域名即将过期(通过自定义Exporter)
- alert: DomainExpiringSoon
expr: domain_expiry_days < 30
for: 24h
labels:
severity: info
annotations:
summary: "ℹ️ 域名30天内过期 {{ $labels.domain }}"
description: "域名 {{ $labels.domain }} 将在 {{ $value }} 天后过期"三、Alertmanager路由配置
<code"># /srv/monitoring/alertmanager/alertmanager.yml
global:
resolve_timeout: 5m
smtp_from: monitor@yourdomain.com
smtp_smarthost: mail.yourdomain.com:587
smtp_auth_username: monitor@yourdomain.com
smtp_auth_password: 邮件密码
# 告警去重和分组
route:
group_by: ['alertname', 'instance', 'severity']
group_wait: 30s # 同组告警等待30秒后发送(收集更多)
group_interval: 5m # 同组新告警最少间隔5分钟发送
repeat_interval: 4h # 持续告警4小时重发一次
receiver: default
routes:
# P1告警:立即发送,重复间隔1小时
- match:
severity: critical
receiver: critical-channel
group_wait: 10s
repeat_interval: 1h
continue: false
# P2告警:发送到钉钉和邮件
- match:
severity: warning
receiver: warning-channel
repeat_interval: 4h
continue: false
# P3告警:只发邮件
- match:
severity: info
receiver: info-channel
repeat_interval: 24h
# 告警抑制(避免级联告警)
inhibit_rules:
# 如果服务器宕机(critical),抑制该服务器的所有warning告警
- source_match:
severity: critical
alertname: InstanceDown
target_match:
severity: warning
equal: [instance]
# 如果磁盘critical,抑制磁盘warning
- source_match:
severity: critical
alertname: DiskCritical
target_match:
severity: warning
alertname: DiskWarning
equal: [instance]
receivers:
- name: default
email_configs:
- to: ops-team@yourdomain.com
- name: critical-channel
webhook_configs:
- url: http://dingtalk-proxy:8080/critical
send_resolved: true
email_configs:
- to: oncall@yourdomain.com
headers:
Subject: '[P1-CRITICAL] {{ .GroupLabels.alertname }}'
- name: warning-channel
webhook_configs:
- url: http://dingtalk-proxy:8080/warning
send_resolved: true
email_configs:
- to: ops-team@yourdomain.com
- name: info-channel
email_configs:
- to: ops-team@yourdomain.com
headers:
Subject: '[P3-INFO] {{ .GroupLabels.alertname }}'四、钉钉Webhook代理服务
<code">// dingtalk-proxy/server.js
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
const WEBHOOKS = {
critical: process.env.DINGTALK_CRITICAL_WEBHOOK,
warning: process.env.DINGTALK_WARNING_WEBHOOK,
};
app.post('/:severity', async (req, res) => {
const { severity } = req.params;
const alerts = req.body.alerts || [];
const webhook = WEBHOOKS[severity];
if (!webhook) return res.status(400).json({ error: 'Unknown severity' });
for (const alert of alerts) {
const status = alert.status === 'resolved' ? '✅ 已恢复' : getEmoji(severity);
const msg = `${status} **${alert.labels.alertname}**
实例:${alert.labels.instance || 'N/A'}
级别:${alert.labels.severity}
摘要:${alert.annotations.summary}
详情:${alert.annotations.description}
时间:${new Date(alert.startsAt).toLocaleString('zh-CN')}`;
await axios.post(webhook, {
msgtype: 'markdown',
markdown: { title: alert.labels.alertname, text: msg },
}).catch(console.error);
}
res.json({ ok: true });
});
function getEmoji(severity) {
return { critical: '🔴', warning: '⚠️', info: 'ℹ️' }[severity] || '📢';
}
app.listen(8080, () => console.log('钉钉代理运行在 :8080'));五、告警验证与测试
<code"># 验证告警规则语法
promtool check rules /etc/prometheus/rules/*.yml
# 立即触发测试告警(验证通知链路)
curl -X POST http://localhost:9093/api/v1/alerts \
-H "Content-Type: application/json" \
-d '[{
"labels": {
"alertname": "TestAlert",
"severity": "warning",
"instance": "test-server"
},
"annotations": {
"summary": "这是一条测试告警",
"description": "验证钉钉通知是否正常工作"
}
}]'
# 查看Alertmanager当前活跃告警
curl http://localhost:9093/api/v1/alerts | python3 -m json.tool六、总结
好的告警体系让运维团队对系统状态保持清晰认知,而不是被告警洪水淹没。核心原则:P1告警立刻处理、P2告警今日处理、P3告警本周处理,每条告警附带Runbook让处理者知道该做什么。IDC.Net的香港VPS稳定的网络环境确保Prometheus数据采集不受网络波动影响,是构建可靠监控体系的优质基础设施。
遇到问题解决不了?
把服务器 IP、报错截图和操作步骤发给我们,工程师 7×24 在线,工单平均 10 分钟内响应。
