Apache在Ubuntu上的性能监控方法
top是实时显示系统进程资源占用的命令行工具,可查看Apache进程(如httpd或apache2)的CPU、内存使用率;htop是其增强版,提供更友好的界面(支持颜色、排序、鼠标操作)。安装htop需运行sudo apt install htop,运行后通过F6键选择按“%CPU”或“%MEM”排序,快速定位高负载进程。
vmstat:监控系统虚拟内存、CPU、磁盘I/O等整体性能,安装sysstat包(sudo apt install sysstat)后,运行vmstat 1(每秒更新一次),重点关注r(运行队列长度)、us(用户态CPU使用率)、sy(内核态CPU使用率)、free(空闲内存)等指标。iostat:监控CPU和磁盘I/O负载,运行iostat -x 1(-x显示扩展统计信息),关注%util(磁盘利用率,超过70%需警惕)、await(平均I/O等待时间)。sar:收集、报告系统活动数据,运行sar -u 10(每10秒采集一次CPU使用率)、sar -d 10(每10秒采集一次磁盘I/O),可通过-f参数查看历史数据。dstat:多功能系统监控工具,整合了vmstat、iostat、netstat等功能,运行dstat -ta 6(每6秒更新一次),可实时查看CPU、内存、磁盘、网络等综合指标。glances:跨平台系统监控工具,提供Web界面(glances -w),支持远程监控,运行后显示CPU、内存、磁盘、网络、进程等全面信息,适合快速排查性能瓶颈。mod_status是Apache内置的性能监控模块,可提供详细的服务器状态信息(如请求数、连接数、工作模式、CPU使用率)。配置步骤:
sudo a2enmod status(Ubuntu下简化命令);/etc/apache2/mods-enabled/status.conf,添加以下内容(允许本地访问):<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1 ::1 # 仅允许本地访问,生产环境可添加信任IP
</Location>
ExtendedStatus On # 开启详细状态信息
sudo systemctl restart apache2;http://服务器IP/server-status,可看到实时性能数据(如“Requests per second”“Busy workers”)。node_exporter(收集系统指标):wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz,解压后运行./node_exporter;prometheus.yml,添加Apache监控任务(需配合apache_exporter,如wget https://github.com/Lusitaniae/apache_exporter/releases/download/v0.13.0/apache_exporter-0.13.0.linux-amd64.tar.gz,配置scrape_configs指向apache_exporter的9117端口);sudo apt install grafana,启动后登录(默认admin/admin),添加Prometheus为数据源,导入Apache监控仪表盘(如ID:1860)。Zabbix是开源企业级监控解决方案,支持监控Apache的性能指标(如请求数、响应时间、CPU/内存使用率)。配置步骤:
sudo apt install zabbix-server-mysql zabbix-frontend-php zabbix-apache-conf zabbix-agent;/etc/zabbix/zabbix_agentd.conf,设置Server和ServerActive为Zabbix服务器IP,添加UserParameter(如UserParameter=apache.status[*], curl -s http://localhost/server-status?auto | grep "$1");check_apache)监控Apache状态,需安装Nagios Core和插件,配置commands.cfg和services.cfg,设置告警阈值(如CPU使用率超过80%时发送邮件)。apache_exporter,可监控Apache请求延迟、错误率等指标,适合微服务架构。使用tail -f命令实时查看Apache的访问日志(/var/log/apache2/access.log)和错误日志(/var/log/apache2/error.log),了解请求流量和错误情况(如4xx/5xx错误)。
编写Shell脚本定期检查错误日志中的错误数量,超过阈值时发送报警(如邮件)。示例脚本:
#!/bin/bash
LOG_FILE="/var/log/apache2/error.log"
ERROR_COUNT=$(grep -c "error" "$LOG_FILE")
if [ "$ERROR_COUNT" -gt 5 ]; then
echo "Apache Error detected: $ERROR_COUNT errors in $LOG_FILE" | mail -s "Apache Error Alert" your_email@example.com
fi
将脚本添加到cron作业(crontab -e),每分钟执行一次:* * * * * /path/to/script.sh。
UptimeRobot是免费在线监控服务,支持HTTP(S)监控,配置步骤: