在 LAMP (Linux + Apache + MySQL/MariaDB + PHP) 环境中监控系统资源使用情况是维护服务器健康和性能优化的重要工作。以下是几种有效的监控方法:
top/htop - 实时监控进程和资源使用情况
top
htop # 需要安装,提供更友好的界面
vmstat - 查看内存、交换分区、CPU等使用情况
vmstat 1 # 每秒刷新一次
free - 查看内存使用情况
free -h
iostat - 监控磁盘I/O
iostat -x 1
iftop - 实时网络流量监控
iftop -i eth0
nethogs - 按进程显示网络流量
nethogs eth0
查看当前连接数:
apachectl status # 需要启用mod_status
netstat -anp | grep httpd | wc -l
启用 mod_status 模块(在 httpd.conf 中):
<Location /server-status>
SetHandler server-status
Require host example.com
</Location>
使用内置命令:
SHOW STATUS;
SHOW PROCESSLIST;
SHOW ENGINE INNODB STATUS;
使用 mysqladmin:
mysqladmin -u root -p extended-status
查看 PHP-FPM 状态(如果使用):
systemctl status php-fpm
查看 PHP 进程:
ps aux | grep php
Glances - 综合监控工具
pip install glances
glances
Netdata - 实时性能监控仪表板
bash <(curl -Ss https://my-netdata.io/kickstart.sh)
Prometheus + Grafana - 专业监控方案
/var/log/apache2/
或 /var/log/httpd/
/var/log/mysql/
/var/log/syslog
, /var/log/messages
使用工具分析:
tail -f /var/log/apache2/access.log # 实时查看
grep "ERROR" /var/log/apache2/error.log # 查找错误
简单的 bash 脚本监控资源并发送警报:
#!/bin/bash
# 设置阈值
CPU_THRESHOLD=80
MEM_THRESHOLD=90
DISK_THRESHOLD=85
# 获取当前值
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
MEM_USAGE=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
# 检查并发送警报
if (( $(echo "$CPU_USAGE > $CPU_THRESHOLD" | bc -l) )); then
echo "CPU 使用率过高: $CPU_USAGE%" | mail -s "服务器警报" admin@example.com
fi
if (( $(echo "$MEM_USAGE > $MEM_THRESHOLD" | bc -l) )); then
echo "内存使用率过高: $MEM_USAGE%" | mail -s "服务器警报" admin@example.com
fi
if [ "$DISK_USAGE" -gt "$DISK_THRESHOLD" ]; then
echo "磁盘使用率过高: $DISK_USAGE%" | mail -s "服务器警报" admin@example.com
fi
对于生产环境,建议使用更专业的监控方案: - Zabbix - 企业级监控 - Nagios - 成熟的监控系统 - Datadog - SaaS 监控平台 - New Relic - 应用性能监控
选择哪种监控方法取决于您的具体需求、服务器规模和预算。对于小型项目,命令行工具和简单脚本可能就足够了;对于大型生产环境,建议部署专业的监控系统。