Ubuntu下配置Apache监控的完整步骤
mod_status是Apache内置的性能监控模块,可提供服务器运行状态、请求速率、连接数等关键指标。
sudo a2enmod status命令启用模块(若未安装会自动提示安装)。/etc/apache2/sites-available/000-default.conf或/etc/apache2/mods-enabled/status.conf),在<VirtualHost>或<Location>块中添加访问限制,仅允许可信IP访问(如本地或运维IP):<Location "/server-status">
SetHandler server-status
Require ip 127.0.0.1 # 替换为你的IP或域名
</Location>
sudo systemctl restart apache2使配置生效。http://服务器IP/server-status,可看到Apache的实时状态(如“Server uptime”“Requests per second”);添加?auto参数可实现自动刷新(如http://服务器IP/server-status?auto)。Apache的访问日志(/var/log/apache2/access.log)和错误日志(/var/log/apache2/error.log)是监控服务器运行状态的重要数据源。
tail命令实时监控日志更新:
sudo tail -f /var/log/apache2/access.logsudo tail -f -n 100 /var/log/apache2/error.log(-n 100显示最近100行)。awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -nr | head -10grep -c " 404 " /var/log/apache2/access.logawk '{print $7}' /var/log/apache2/access.log | cut -d '/' -f2- | sort | uniq -c | sort -nr | head -10。mailx):#!/bin/bash
ERROR_LOG="/var/log/apache2/error.log"
ERROR_COUNT=$(grep -c "[error]" "$ERROR_LOG") # 统计错误数量
if [ "$ERROR_COUNT" -gt 0 ]; then
echo "Apache错误警报:检测到$ERROR_COUNT个错误" | mailx -s "Apache错误报警" your_email@example.com
fi
赋予执行权限(sudo chmod +x /usr/local/bin/apache_error_monitor.sh),并通过crontab -e添加定时任务(如每分钟执行一次):* * * * * /usr/local/bin/apache_error_monitor.sh
```。
对于需要更全面监控(如系统资源、历史趋势、可视化)的场景,可使用第三方工具。
apache_exporter(Apache的Prometheus客户端)采集Apache指标。安装apache_exporter后,在Prometheus配置文件中添加scrape_configs指向apache_exporter的地址(如localhost:9117)。apache_accesses_total、apache_workers),并设置阈值告警(如当错误数超过10时发送短信)。。glances后,运行glances命令,选择“Apache”模块即可查看详细信息。。monit后,编辑配置文件(/etc/monit/monitrc)添加Apache监控规则:check process apache2 with pidfile /var/run/apache2/apache2.pid
start program = "/etc/init.d/apache2 start"
stop program = "/etc/init.d/apache2 stop"
if failed host 127.0.0.1 port 80 protocol http then restart
if 5 restarts within 5 cycles then timeout
重启Monit服务(sudo systemctl restart monit)使配置生效。。Ubuntu自带的系统工具可辅助监控Apache的资源使用情况。
top命令显示系统进程的资源占用(按M键按内存排序,按P键按CPU排序),htop是top的增强版(需安装:sudo apt install htop),界面更友好,可实时查看Apache进程的资源使用情况。sysstat:sudo apt install sysstat),运行iostat -x 1可查看磁盘的读写速率、利用率等指标,帮助排查Apache因磁盘IO瓶颈导致的性能问题。。