跳轉到內容

VPS 性能監控與告警系統搭建實戰 2026 | Prometheus Grafana 完全指南

VPS 性能監控與告警系統

沒有監控的系統就像盲人騎瞎馬。性能監控是運維的核心工作,通過監控可以及時發現系統異常、定位性能瓶頸、預防故障發生。本文將從零開始,使用 Prometheus + Grafana + Alertmanager 搭建一套完整的 VPS 監控告警系統。


一、監控系統架構

1.1 整體架構圖

┌─────────────────────────────────────────────────────────────┐
│                      監控系統架構                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  被監控服務器 1          被監控服務器 2       ...            │
│  ┌─────────────┐      ┌─────────────┐                      │
│  │Node Exporter│      │Node Exporter│                      │
│  └──────┬──────┘      └──────┬──────┘                      │
│         │                    │                              │
│         └─────────┬──────────┘                              │
│                   │ :9100                                    │
│                   ▼                                         │
│           ┌─────────────┐                                   │
│           │ Prometheus  │ ← 數據採集與存儲                  │
│           └──────┬──────┘                                   │
│                  │                                          │
│         ┌────────┴────────┐                                 │
│         ▼                 ▼                                 │
│  ┌───────────┐     ┌──────────────┐                        │
│  │  Grafana  │     │ Alertmanager │                        │
│  │ 可視化面板 │     │ 告警通知     │                        │
│  └───────────┘     └──────┬───────┘                        │
│                            │                                │
│                            ▼                                │
│                      郵件 / 釘釘 / 飛書                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

1.2 組件說明

組件作用默認端口
Prometheus時序數據庫,抓取並存儲指標數據9090
Node Exporter採集 Linux 系統指標9100
Grafana可視化監控面板3000
Alertmanager告警管理與通知9093

二、Node Exporter 安裝與配置

2.1 安裝 Node Exporter

bash
# 下載最新版本
NODE_EXPORTER_VERSION="1.8.2"
wget https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXPORTER_VERSION}/node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64.tar.gz

# 解壓
tar xzf node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64.tar.gz
cd node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64

# 安裝
cp node_exporter /usr/local/bin/

# 創建用戶
useradd -rs /bin/false node_exporter

2.2 配置 systemd 服務

ini
# /etc/systemd/system/node_exporter.service
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target

[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter \
    --web.listen-address=:9100 \
    --collector.systemd \
    --collector.processes \
    --collector.filesystem.mount-points-exclude=^/(sys|proc|dev|run)($|/)

[Install]
WantedBy=multi-user.target
bash
# 啟動服務
systemctl daemon-reload
systemctl start node_exporter
systemctl enable node_exporter

# 驗證
curl http://localhost:9100/metrics

2.3 常用採集器說明

採集器說明默認啟用
cpuCPU 使用情況
diskstats磁盤 I/O 統計
filesystem文件系統使用
loadavg系統負載
meminfo內存使用
netstat網絡統計
systemdsystemd 服務狀態
processes進程信息

三、Prometheus 安裝與配置

3.1 安裝 Prometheus

bash
PROMETHEUS_VERSION="2.53.0"
wget https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz

tar xzf prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz
cd prometheus-${PROMETHEUS_VERSION}.linux-amd64

# 安裝二進制
cp prometheus promtool /usr/local/bin/

# 創建目錄
mkdir -p /etc/prometheus /var/lib/prometheus
cp prometheus.yml /etc/prometheus/
cp -r consoles console_libraries /etc/prometheus/

# 創建用戶
useradd -rs /bin/false prometheus
chown -R prometheus:prometheus /etc/prometheus /var/lib/prometheus

3.2 配置 prometheus.yml

yaml
# /etc/prometheus/prometheus.yml
global:
  scrape_interval: 15s
  evaluation_interval: 15s
  external_labels:
    monitor: 'vps-monitor'

# Alertmanager 配置
alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - localhost:9093

# 告警規則文件
rule_files:
  - "rules/*.yml"

# 抓取配置
scrape_configs:
  # Prometheus 自身監控
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  # Node Exporter - 服務器1
  - job_name: 'server1'
    static_configs:
      - targets: ['192.168.1.101:9100']
        labels:
          instance: 'web-server'
          region: 'us-east'

  # Node Exporter - 服務器2
  - job_name: 'server2'
    static_configs:
      - targets: ['192.168.1.102:9100']
        labels:
          instance: 'db-server'
          region: 'us-west'

  # 多臺服務器配置
  - job_name: 'node_exporter'
    static_configs:
      - targets: ['192.168.1.101:9100', '192.168.1.102:9100']
    relabel_configs:
      - source_labels: [__address__]
        target_label: instance
        regex: '([^:]+):\d+'
        replacement: '${1}'

3.3 配置 systemd 服務

ini
# /etc/systemd/system/prometheus.service
[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target

[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/usr/local/bin/prometheus \
    --config.file=/etc/prometheus/prometheus.yml \
    --storage.tsdb.path=/var/lib/prometheus \
    --storage.tsdb.retention.time=30d \
    --web.console.templates=/etc/prometheus/consoles \
    --web.console.libraries=/etc/prometheus/console_libraries \
    --web.listen-address=:9090

ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
bash
# 啟動 Prometheus
systemctl daemon-reload
systemctl start prometheus
systemctl enable prometheus

# 驗證
curl http://localhost:9090/-/healthy

3.4 防火牆配置

bash
# iptables 配置
iptables -A INPUT -p tcp --dport 9090 -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -p tcp --dport 9090 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 9100 -s 192.168.1.100 -j ACCEPT

四、Grafana 安裝與配置

4.1 安裝 Grafana

bash
# 安裝 Grafana OSS 版
apt install -y apt-transport-https software-properties-common wget
wget -q -O /usr/share/keyrings/grafana.key https://apt.grafana.com/gpg.key
echo "deb [signed-by=/usr/share/keyrings/grafana.key] https://apt.grafana.com stable main" > /etc/apt/sources.list.d/grafana.list

apt update
apt install -y grafana

# 啟動
systemctl start grafana-server
systemctl enable grafana-server

# 驗證
systemctl status grafana-server

4.2 配置 Grafana

ini
# /etc/grafana/grafana.ini
[server]
http_port = 3000
domain = grafana.example.com
root_url = https://grafana.example.com

[security]
admin_user = admin
admin_password = your_secure_password
disable_gravatar = true

[auth.anonymous]
enabled = false

[users]
allow_sign_up = false
auto_assign_org = true
auto_assign_org_role = Viewer

[analytics]
reporting_enabled = false
check_for_updates = false
bash
# 重啟生效
systemctl restart grafana-server

4.3 添加 Prometheus 數據源

  1. 訪問 http://your-server:3000
  2. 使用 admin / admin 登錄(首次登錄需修改密碼)
  3. 進入 Connections → Data sources → Add data source
  4. 選擇 Prometheus
  5. 配置 URL: http://localhost:9090
  6. 點擊 Save & test

4.4 導入監控面板

推薦的 Node Exporter 面板:

  • ID: 1860 — Node Exporter Full(最全的系統監控面板)
  • ID: 13978 — Node Exporter Dashboard
  • ID: 11074 — 1 Node Exporter for Prometheus Dashboard CN 中文版
bash
# 導入面板方法
# 1. Grafana → Dashboards → Import
# 2. 輸入面板 ID(如 1860)
# 3. 選擇 Prometheus 數據源
# 4. 點擊 Import

4.5 監控面板關鍵指標

指標類別關鍵指標PromQL
CPUCPU 使用率100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
內存內存使用率100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))
磁盤磁盤使用率100 * (1 - (node_filesystem_avail_bytes / node_filesystem_size_bytes))
網絡網絡入流量rate(node_network_receive_bytes_total[5m]) * 8
系統負載1 分鐘負載node_load1
磁盤 I/O讀延遲rate(node_disk_read_time_seconds_total[5m]) / rate(node_disk_reads_completed_total[5m])

五、告警規則配置

5.1 主機告警規則

yaml
# /etc/prometheus/rules/host.yml
groups:
  - name: host_alert
    rules:
      # 主機宕機告警
      - alert: HostDown
        expr: up == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "主機 {{ $labels.instance }} 宕機"
          description: "主機 {{ $labels.instance }} 已經 2 分鐘無法訪問"

      # CPU 使用率告警
      - alert: HighCPUUsage
        expr: 100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 85
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "主機 {{ $labels.instance }} CPU 使用率過高"
          description: "CPU 使用率超過 85%,當前值: {{ $value | printf \"%.2f\" }}%"

      # 內存使用率告警
      - alert: HighMemoryUsage
        expr: 100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) > 90
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "主機 {{ $labels.instance }} 內存使用率過高"
          description: "內存使用率超過 90%,當前值: {{ $value | printf \"%.2f\" }}%"

      # 磁盤使用率告警
      - alert: HighDiskUsage
        expr: 100 * (1 - (node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay"})) > 85
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "主機 {{ $labels.instance }} 磁盤使用率過高"
          description: "磁盤 {{ $labels.mountpoint }} 使用率超過 85%,當前值: {{ $value | printf \"%.2f\" }}%"

      # 系統負載告警
      - alert: HighLoadAverage
        expr: node_load15 / count by(instance) (node_cpu_seconds_total{mode="idle"}) > 2
        for: 15m
        labels:
          severity: warning
        annotations:
          summary: "主機 {{ $labels.instance }} 系統負載過高"
          description: "15 分鐘負載/CPU 核數 > 2,當前值: {{ $value | printf \"%.2f\" }}"

      # 磁盤 I/O 告警
      - alert: HighDiskIO
        expr: rate(node_disk_io_time_seconds_total[5m]) > 0.8
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "主機 {{ $labels.instance }} 磁盤 I/O 過高"
          description: "磁盤 I/O 利用率超過 80%,當前值: {{ $value | printf \"%.2f\" }}"

5.2 服務告警規則

yaml
# /etc/prometheus/rules/service.yml
groups:
  - name: service_alert
    rules:
      # Nginx 進程告警
      - alert: NginxDown
        expr: node_systemd_unit_state{name="nginx.service", state="active"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Nginx 服務異常"
          description: "Nginx 服務已停止運行"

      # MySQL 進程告警
      - alert: MySQLDown
        expr: node_systemd_unit_state{name="mysql.service", state="active"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "MySQL 服務異常"
          description: "MySQL 服務已停止運行"

      # Docker 進程告警
      - alert: DockerDown
        expr: node_systemd_unit_state{name="docker.service", state="active"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Docker 服務異常"
          description: "Docker 服務已停止運行"

5.3 加載告警規則

bash
# 驗證規則文件
promtool check rules /etc/prometheus/rules/*.yml

# 熱加載配置
curl -X POST http://localhost:9090/-/reload

# 或重啟服務
systemctl restart prometheus

六、Alertmanager 配置

6.1 安裝 Alertmanager

bash
ALERTMANAGER_VERSION="0.27.0"
wget https://github.com/prometheus/alertmanager/releases/download/v${ALERTMANAGER_VERSION}/alertmanager-${ALERTMANAGER_VERSION}.linux-amd64.tar.gz

tar xzf alertmanager-${ALERTMANAGER_VERSION}.linux-amd64.tar.gz
cd alertmanager-${ALERTMANAGER_VERSION}.linux-amd64

cp alertmanager amtool /usr/local/bin/
mkdir -p /etc/alertmanager /var/lib/alertmanager
cp alertmanager.yml /etc/alertmanager/

useradd -rs /bin/false alertmanager
chown -R alertmanager:alertmanager /etc/alertmanager /var/lib/alertmanager

6.2 郵件告警配置

yaml
# /etc/alertmanager/alertmanager.yml
global:
  resolve_timeout: 5m
  smtp_smarthost: 'smtp.example.com:587'
  smtp_from: 'alert@example.com'
  smtp_auth_username: 'alert@example.com'
  smtp_auth_password: 'your_smtp_password'
  smtp_require_tls: true

templates:
  - '/etc/alertmanager/template/*.tmpl'

route:
  group_by: ['alertname', 'instance']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h
  receiver: 'admin-email'
  routes:
    - match:
        severity: critical
      receiver: 'critical-email'
      repeat_interval: 1h
    - match:
        severity: warning
      receiver: 'warning-email'

receivers:
  - name: 'admin-email'
    email_configs:
      - to: 'admin@example.com'
        send_resolved: true

  - name: 'critical-email'
    email_configs:
      - to: 'oncall@example.com'
        send_resolved: true
        headers:
          Subject: '[CRITICAL] {{ .GroupLabels.alertname }} - {{ .GroupLabels.instance }}'

  - name: 'warning-email'
    email_configs:
      - to: 'dev@example.com'
        send_resolved: true

6.3 釘釘/Webhook 告警

yaml
# 釘釘 Webhook 告警
receivers:
  - name: 'dingtalk'
    webhook_configs:
      - url: 'https://oapi.dingtalk.com/robot/send?access_token=your_token'
        send_resolved: true
        http_config:
          headers:
            Content-Type: application/json

6.4 配置 systemd 服務

ini
# /etc/systemd/system/alertmanager.service
[Unit]
Description=Alertmanager
Wants=network-online.target
After=network-online.target

[Service]
User=alertmanager
Group=alertmanager
Type=simple
ExecStart=/usr/local/bin/alertmanager \
    --config.file=/etc/alertmanager/alertmanager.yml \
    --storage.path=/var/lib/alertmanager \
    --web.listen-address=:9093

[Install]
WantedBy=multi-user.target
bash
# 啟動
systemctl daemon-reload
systemctl start alertmanager
systemctl enable alertmanager

七、常用監控命令

7.1 系統性能查看

bash
# CPU 查看
top
htop
mpstat -P ALL 1 5

# 內存查看
free -h
vmstat 1 5

# 磁盤查看
df -h
du -sh /*
iostat -x 1 5

# 網絡查看
netstat -tlnp
ss -tlnp
iftop
nload

# 進程查看
ps aux
pstree
lsof -i :port

7.2 日誌查看

bash
# 系統日誌
journalctl -f
journalctl -u nginx.service -f

# 內核日誌
dmesg
dmesg -T | tail -20

# 登錄日誌
last
lastb
who
w

八、PromQL 基礎

8.1 常用查詢示例

promql
// CPU 使用率
100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

// 內存使用率
100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))

// 磁盤使用率
100 * (1 - (node_filesystem_avail_bytes{fstype!~"tmpfs"} / node_filesystem_size_bytes{fstype!~"tmpfs"}))

// 網絡流量(bps)
rate(node_network_receive_bytes_total{device!="lo"}[5m]) * 8

// CPU 負載
node_load1 / count by(instance) (node_cpu_seconds_total{mode="idle"})

// 進程數
node_processes_total

// TCP 連接數
node_netstat_Tcp_CurrEstab

8.2 PromQL 函數

函數說明
rate()每秒增長率(適合計數器)
irate()瞬時增長率(更靈敏)
increase()區間增長量
sum()求和
avg()平均值
max()最大值
min()最小值
count()計數
topk()前 N 個
rate(node_cpu[5m])5 分鐘平均速率

九、Docker 容器監控

9.1 cAdvisor 安裝

yaml
# docker-compose.yml
version: '3.8'

services:
  cadvisor:
    image: gcr.io/cadvisor/cadvisor:latest
    container_name: cadvisor
    restart: unless-stopped
    ports:
      - "8080:8080"
    volumes:
      - /:/rootfs:ro
      - /var/run:/var/run:rw
      - /sys:/sys:ro
      - /var/lib/docker:/var/lib/docker:ro

9.2 Prometheus 配置

yaml
scrape_configs:
  - job_name: 'cadvisor'
    static_configs:
      - targets: ['192.168.1.100:8080']

十、最佳實踐

10.1 監控原則

  1. 全面覆蓋:CPU、內存、磁盤、網絡、進程、服務狀態
  2. 分級告警:信息 → 警告 → 嚴重 → 緊急
  3. 合理閾值:根據業務場景設置,避免告警疲勞
  4. 趨勢分析:不僅看當前值,更要看趨勢變化
  5. 自動化:告警自動通知、自動修復

10.2 安全建議

  1. 不要暴露監控端口到公網:使用防火牆限制訪問
  2. 使用 HTTPS:Grafana 和 Prometheus 配置 SSL
  3. 設置認證:所有 Web 界面都需要登錄
  4. 最小權限:監控賬戶只分配必要權限

10.3 性能優化

  1. 合理設置採集間隔:默認 15s,可按需調整
  2. 數據保留策略:根據需要設置保留時間
  3. 降採樣:長期存儲使用降採樣數據
  4. 分片存儲:大規模場景使用遠程存儲

十一、總結

  • ✅ 監控系統架構與組件選型
  • ✅ Node Exporter 安裝與配置
  • ✅ Prometheus 安裝與配置
  • ✅ Grafana 可視化面板搭建
  • ✅ 告警規則配置(主機 + 服務)
  • ✅ Alertmanager 告警通知(郵件 + Webhook)
  • ✅ 常用監控命令與日誌查看
  • ✅ PromQL 基礎查詢
  • ✅ Docker 容器監控
  • ✅ 監控最佳實踐

監控是運維工作的眼睛,建立一套完善的監控告警系統,才能真正做到防患於未然,快速響應和解決問題。


相關閱讀:

最後更新於: