"没有监控的系统就像蒙眼开飞机"。监控是SRE和DevOps的核心能力,它让你知道系统当前状态、发现问题趋势、验证修复效果。好的监控系统=指标+日志+链路追踪。
┌───────────────────────────────────────────────┐ │ 告警与可视化 │ │ Grafana Dashboard PagerDuty/钉钉 │ ├───────────────────────────────────────────────┤ │ 数据存储与查询 │ │ Prometheus + TSDB ELK + Elasticsearch │ ├───────────────────────────────────────────────┤ │ 数据采集 │ │ Node Exporter 应用Metrics Fluentd Jaeger │ │ (系统指标) (业务指标) (日志) (链路) │ ├───────────────────────────────────────────────┤ │ 被监控目标 │ │ 服务器 容器 数据库 消息队列 网络设备 │ └───────────────────────────────────────────────┘
# CPU监控
top -b -n 1 | head -20
mpstat 1 5 # 每秒采样5次
lscpu | grep "CPU(s)" # CPU核心数
# 内存监控
free -h
vmstat 1 5 # 虚拟内存统计
cat /proc/meminfo | head -10
# 磁盘I/O监控
iostat -xz 1 5 # 每秒磁盘I/O统计
iotop # 进程级I/O监控(需root)
# 网络监控
sar -n DEV 1 5 # 网络流量统计
ss -tlnp # TCP连接统计
netstat -tlnp # 端口监听(旧命令)
# 综合监控工具
apt install sysstat -y # iostat, mpstat, sar
apt install htop iotop nethogs -y # 交互式工具
# 下载安装
cd /opt
wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz
tar xzf node_exporter-*.tar.gz
ln -s node_exporter-*/node_exporter /usr/local/bin/
# 创建systemd服务
cat > /etc/systemd/system/node-exporter.service << 'EOF'
[Unit]
Description=Node Exporter
After=network.target
[Service]
Type=simple
User=nobody
ExecStart=/usr/local/bin/node_exporter \
--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|run) \
--collector.textfile.directory=/var/lib/node_exporter/textfile
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
# 启动
sudo systemctl daemon-reload
sudo systemctl enable --now node-exporter
# 验证
curl -s http://localhost:9100/metrics | head -20
# node_cpu_seconds_total{cpu="0",mode="idle"} 12345.67
# node_memory_MemAvailable_bytes 4.2e+09
#!/usr/bin/env bash
# health-check.sh - 系统健康检查
set -euo pipefail
THRESHOLD_CPU=80
THRESHOLD_MEM=85
THRESHOLD_DISK=90
check_cpu() {{
local usage
usage=$(top -bn1 | grep "Cpu(s)" | awk '{{print $2}}' | cut -d. -f1)
if [[ $usage -gt $THRESHOLD_CPU ]]; then
echo "⚠️ CPU使用率: ${{usage}}% (阈值: $THRESHOLD_CPU%)"
return 1
fi
echo "✅ CPU使用率: ${{usage}}%"
}}
check_memory() {{
local usage
usage=$(free | awk '/Mem:/ {{printf "%.0f", $3/$2*100}}')
if [[ $usage -gt $THRESHOLD_MEM ]]; then
echo "⚠️ 内存使用率: ${{usage}}% (阈值: $THRESHOLD_MEM%)"
return 1
fi
echo "✅ 内存使用率: ${{usage}}%"
}}
check_disk() {{
local issues=0
while read -r line; do
local usage
usage=$(echo "$line" | awk '{{print $5}}' | tr -d '%')
local mount
mount=$(echo "$line" | awk '{{print $6}}')
if [[ $usage -gt $THRESHOLD_DISK ]]; then
echo "⚠️ 磁盘 $mount 使用率: ${{usage}}%"
issues=$((issues+1))
fi
done < <(df -h | grep '^/dev')
[[ $issues -eq 0 ]] && echo "✅ 磁盘使用率正常"
return $issues
}}
echo "========== 系统健康检查 =========="
check_cpu
check_memory
check_disk
echo "=================================="
数据采集层 存储层 展示层 ┌─────────┐ ┌─────────┐ ┌─────────┐ │ Node │──metrics──▶│ │ │ │ │ Exporter│ │ │──query──▶│Grafana │ └─────────┘ │ Prometh-│ │Dashboard│ ┌─────────┐ │ eus │ └─────────┘ │ App │──metrics──▶│ + TSDB │ │ │ Metrics │ │ │ ┌────▼────┐ └─────────┘ │ │ │ Alert │ ┌─────────┐ │ │ │ Manager │ │ Blackbox│──probe───▶│ │ │ →钉钉 │ │ Exporter│ └─────────┘ │ →邮件 │ └─────────┘ │ →PagerDuty│ ┌─────────┐ └─────────┘ │ Fluentd │────logs────▶ Elasticsearch ──▶ Kibana └─────────┘
# 检查exporter是否正常
curl -s http://localhost:9100/metrics | head -5
systemctl status node-exporter
# 检查Prometheus target状态
curl -s http://prometheus:9090/api/v1/targets | python3 -m json.tool
# 常见原因:
# 1. 网络不通 → 检查防火墙
# 2. scrape_interval太长 → 调整
# 3. 目标过载 → 降低采集频率
# 4. TSDB存储满 → 清理旧数据
# 确认iowait
iostat -x 1 3
# %util 超过80%表示磁盘饱和
# 找到I/O密集进程
iotop -oP
# 常见原因:大量日志写入、数据库全表扫描、swap频繁
# 解决:优化查询、增加缓存、使用SSD、调整vm.dirty_ratio
| 信号 | 含义 | 关键指标 | 异常表现 |
|---|---|---|---|
| 延迟 | 请求处理时间 | P50/P95/P99 | P99飙升但P50正常→尾部延迟 |
| 流量 | 系统负载量 | QPS/RPS/并发连接 | 突增→可能是攻击或热点 |
| 错误 | 失败请求比例 | 5xx率、超时率 | 持续>1%→需要告警 |
| 饱和度 | 资源使用极限 | CPU/内存/连接池 | 接近100%→即将雪崩 |
# Docker部署Prometheus
docker run -d --name prometheus \
-p 9090:9090 \
-v /opt/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
-v /opt/prometheus/data:/prometheus \
prom/prometheus:v2.48.0
# Prometheus配置文件
cat > /opt/prometheus/prometheus.yml << 'EOF'
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
labels:
env: 'production'
- job_name: 'app'
metrics_path: /metrics
static_configs:
- targets: ['app:8080']
EOF
# 常用PromQL查询
# CPU使用率
100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# 内存使用率
100 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes * 100)
# 磁盘使用率
100 - (node_filesystem_avail_bytes{fstype=~"ext4|xfs"} / node_filesystem_size_bytes * 100)
# HTTP请求P99延迟
histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))
# 5xx错误率
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100
#!/usr/bin/env bash
# 自定义指标收集脚本(Node Exporter Textfile Collector)
set -euo pipefail
METRICS_DIR="/var/lib/node_exporter/textfile"
METRICS_FILE="$METRICS_DIR/custom.prom"
mkdir -p "$METRICS_DIR"
# 业务指标:活跃用户数
ACTIVE_USERS=$(redis-cli SCARD active_users 2>/dev/null || echo 0)
echo "# HELP app_active_users Number of active users" > "$METRICS_FILE"
echo "# TYPE app_active_users gauge" >> "$METRICS_FILE"
echo "app_active_users $ACTIVE_USERS" >> "$METRICS_FILE"
# 业务指标:订单处理速率
ORDER_RATE=$(redis-cli GET order_rate_per_min 2>/dev/null || echo 0)
echo "# HELP app_order_rate Orders per minute" >> "$METRICS_FILE"
echo "# TYPE app_order_rate gauge" >> "$METRICS_FILE"
echo "app_order_rate $ORDER_RATE" >> "$METRICS_FILE"
# 确保文件时间戳更新
touch "$METRICS_FILE"
# 确认内存泄漏
while true; do
echo "$(date): RSS=$(ps -o rss= -p $(pgrep myapp)) KB"
sleep 60
done
# 使用pmap查看内存映射
pmap -x $(pgrep myapp) | tail -5
# Go pprof分析
curl http://localhost:6060/debug/pprof/heap > heap.prof
go tool pprof heap.prof
掌握USE/RED方法论、系统资源监控、Prometheus生态——监控是发现问题的第一道防线。