服务器CPU内存实时监控搭建教程
引言
服务器CPU与内存的实时监控是运维工作的核心环节,能帮助团队快速发现性能瓶颈、预测资源耗尽风险。本文采用开源Prometheus生态,通过Node Exporter采集指标、Prometheus存储聚合、Grafana可视化展示,三步搭建一套轻量级、可扩展的监控系统。本教程适用于Linux服务器,无需额外付费工具或云服务。
前置条件
- 一台运行Linux(CentOS 7+ / Ubuntu 18.04+)的服务器,拥有sudo权限。
- 服务器已开放以下端口:Prometheus默认9090,Node Exporter默认9100,Grafana默认3000。请确保防火墙规则允许内部或管理网段访问。
- 已安装wget或curl用于下载二进制文件。
第一步:安装Node Exporter
Node Exporter负责采集服务器的CPU、内存、磁盘、网络等系统指标。
- 下载最新版本:前往Prometheus官方下载页面获取Node Exporter的Linux amd64版本,例如:
wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz(版本号请以官网为准)。 - 解压并安装:
tar -xvf node_exporter-*.tar.gz,将二进制文件移至/usr/local/bin。 - 创建系统服务:编写
/etc/systemd/system/node_exporter.service,内容如下:[Unit] Description=Node Exporter [Service] ExecStart=/usr/local/bin/node_exporter Restart=always [Install] WantedBy=multi-user.target - 启动并启用:
systemctl daemon-reload; systemctl start node_exporter; systemctl enable node_exporter。验证服务状态:systemctl status node_exporter,并通过curl http://localhost:9100/metrics查看指标输出。
第二步:配置Prometheus
Prometheus作为时序数据库,负责拉取Node Exporter的指标并存储。
- 下载Prometheus:从官方下载页面获取Linux版本,解压至
/opt/prometheus。 - 修改配置文件:编辑
/opt/prometheus/prometheus.yml,将scrape_configs中的localhost:9090替换为Node Exporter的地址(本例为localhost:9100):
如需监控多台服务器,追加多个targets。scrape_configs: - job_name: 'node' static_configs: - targets: ['localhost:9100'] - 创建系统服务:参照Node Exporter方式,编写
/etc/systemd/system/prometheus.service,ExecStart指向/opt/prometheus/prometheus --config.file=/opt/prometheus/prometheus.yml。 - 启动并验证:服务启动后,访问
http://服务器IP:9090,在Prometheus UI中执行up{job="node"},应返回值为1的指标。
第三步:部署Grafana
Grafana提供丰富的仪表盘和告警功能。
- 安装Grafana:使用官方仓库(推荐)或直接下载二进制。例如在Ubuntu上:
sudo apt-get install -y software-properties-common; sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main"; sudo apt-get update; sudo apt-get install grafana。或直接下载rpm/deb包。 - 启动Grafana:
systemctl start grafana-server; systemctl enable grafana-server。访问http://服务器IP:3000,默认账号密码为admin/admin,首次登录后请修改。 - 添加Prometheus数据源:在Grafana左侧菜单选择“Configuration” → “Data Sources” → “Add data source”,类型选Prometheus,URL填写
http://localhost:9090(如Prometheus在同一服务器),点击“Save & Test”。
第四步:配置监控面板
Grafana官方社区提供了成熟的Node Exporter仪表盘,可直接导入。
- 获取仪表盘ID:访问Grafana官网仪表盘市场,搜索“Node Exporter Full”或使用ID
1860(此为常用ID,适用于新版)。 - 导入仪表盘:在Grafana左侧菜单选择“+” → “Import”,输入ID并加载,选择Prometheus数据源。仪表盘将自动显示CPU使用率、内存占用、磁盘I/O等图表。
- 自定义面板:如需更精细的CPU/内存监控,可新建Dashboard,添加Panel,查询PromQL语句,例如:
- CPU使用率:
100 - (avg by (instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) - 内存使用率:
100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))
- CPU使用率:
验证与优化
部署完成后,通过Grafana仪表盘观察指标变化,例如执行高负载测试(如stress工具),确认CPU曲线上升、内存占用变化。建议设置告警规则:在Grafana “Alerting”模块中配置CPU使用率>90%持续5分钟发送邮件或Webhook通知。此外,定期升级各组件版本,确保安全补丁。对于大规模集群,可考虑引入Prometheus Federation或Thanos进行水平扩展。
通过本教程,您已建立一套完整的CPU/内存实时监控系统。该方案完全基于开源软件,无License费用,适用于各类IDC机房和私有云环境。