温馨提示×

Ubuntu下Apache如何进行性能监控

小樊
38
2025-12-26 19:05:11
栏目: 智能运维

Ubuntu下Apache性能监控实操指南

一 系统层快速排查

  • 进程与资源:使用top/htop查看apache2/httpd进程的CPU、内存占用;按P/M排序快速定位异常进程。
  • 系统整体:vmstat 1(关注r运行队列、us/sy CPU、free内存)、iostat -x 1(关注**%util**、await)、sar -u 10/-d 10(历史与实时CPU/磁盘)。
  • 网络与连接:ss -lntp | grep ':80|:443’查看监听与连接;必要时配合netstat -ant
  • 一体化工具:dstat -ta 6glances(支持Web界面远程查看)。
  • 提示:安装htop/sysstat/dstat/glances可用sudo apt install htop sysstat dstat glances
    以上工具适合先定位是CPU瓶颈I/O瓶颈还是连接瓶颈

二 Apache自带模块 mod_status

  • 启用模块与配置:
    • 启用:sudo a2enmod status
    • 编辑:/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(人类可读)或http://服务器IP/server-status?auto(机器可读,便于采集)
    • 关键指标:Total Accesses/Total kBytes、Req/s、Bytes/s、Busy/Idle Workers、Scoreboard(直观看到工作进程负载与排队情况)。
      该模块是零成本、低开销的实时观测入口,建议优先启用。

三 日志分析与命令行工具

  • 实时日志:
    • 访问日志:sudo tail -f /var/log/apache2/access.log
    • 错误日志:sudo tail -f /var/log/apache2/error.log
  • 快速统计:
    • 统计访问量/状态码:awk ‘{print $1}’ access.log | sort | uniq -c
  • 可视化报告:
    • goaccess /var/log/apache2/access.log --log-format=COMBINED(生成实时Web可视化报告,含状态码热图)。
  • 终端实时请求:
    • apachetop -f /var/log/apache2/access.log(需安装apachetop),按URL/客户端聚合查看请求速率响应时间
      日志与命令行工具适合定位异常流量、错误激增、慢请求来源

四 长期监控与可视化方案

  • Prometheus + Grafana:
    • 组件:apache_exporter(默认端口9117,抓取**/server-status?auto**)、Prometheus(抓取exporter)、Grafana(展示)。
    • 配置要点:在prometheus.yml添加job指向apache_exporter:9117;Grafana添加Prometheus数据源并导入Apache仪表盘(如ID 1860)。
  • Zabbix:
    • 安装Zabbix Server/Agent;在zabbix_agentd.conf添加UserParameter(如apache.status[*]调用/server-status?auto);前端导入Template App Apache并关联主机。
  • 其他可选:Nagios(插件如check_apache)、Netdata(访问http://IP:19999,内置Apache模块,开箱即用)。
    上述方案适合长期存储、可视化与告警的生产级监控。

五 告警与自动化

  • 进程守护脚本(示例):
    #!/usr/bin/env bash
    if ! systemctl is-active --quiet apache2; then
        echo "$(date): Apache DOWN, restarting..." >> /var/log/apache_monitor.log
        systemctl start apache2
    fi
    
    • 加入crontab:*/5 * * * * /path/to/monitor.sh
  • 日志错误阈值告警(示例):
    #!/usr/bin/env bash
    LOG="/var/log/apache2/error.log"
    ERR=$(grep -c "error" "$LOG" 2>/dev/null || echo 0)
    if [ "$ERR" -gt 5 ]; then
        echo "Apache Error Alert: $ERR errors" | mail -s "Apache Alert" you@example.com
    fi
    
  • 外部可用性监控:UptimeRobot配置HTTP(S)监控(如5分钟间隔),异常时邮件/Slack/短信通知。
    告警建议覆盖:进程存活、端口连通、5xx比例、关键错误关键字

0