1. 使用systemctl命令管理服务状态
CentOS 7及以上版本通过systemd管理Apache(httpd)服务,可通过以下命令快速检查服务状态:
sudo systemctl status httpd
输出内容包括服务是否运行(active/running)、最近日志片段、启动时间等。若需启动/停止/重启服务,可使用:
sudo systemctl start httpd    # 启动
sudo systemctl stop httpd     # 停止
sudo systemctl restart httpd  # 重启
还可通过sudo systemctl enable httpd设置开机自启。
2. 启用Apache mod_status模块查看详细状态
mod_status是Apache内置模块,可提供服务器运行时的详细指标(如请求数、CPU使用、连接数等)。
/etc/httpd/conf/httpd.conf或/etc/httpd/conf.d/status.conf),添加以下内容:<IfModule mod_status.c>
    ExtendedStatus On
    <Location "/server-status">
        SetHandler server-status
        Require ip 192.168.1.100  # 仅允许受信任IP访问(替换为你的IP)
    </Location>
</IfModule>
保存后重启Apache:sudo systemctl restart httpd。http://服务器IP/server-status,即可查看实时状态(如“Server uptime”“Total accesses”“CPU usage”等)。3. 监控日志文件实时变化
Apache的日志文件记录了访问和错误信息,是排查问题的关键:
/var/log/httpd/access_log,错误日志位于/var/log/httpd/error_log(部分配置可能为/var/log/apache2/)。tail -f命令跟踪日志更新:sudo tail -f /var/log/httpd/error_log  # 实时查看错误日志
sudo tail -f /var/log/httpd/access_log # 实时查看访问日志
awk '{print $1}' /var/log/httpd/access_log | sort | uniq -c | sort -nrgrep " 404 " /var/log/httpd/access_logawk '{print $9}' /var/log/httpd/access_log | sort | uniq -c。4. 使用第三方监控工具实现全面监控
第三方工具提供可视化、告警及历史数据存储功能,适合生产环境:
http://服务器IP:19999访问仪表盘。安装命令:sudo curl -s https://packagecloud.io/install/repositories/netdata/netdata/script.rpm.sh | sudo bash
sudo yum install netdata -y
sudo systemctl start netdata
/server-status页面允许Prometheus抓取(如Require all granted),并通过Prometheus的http exporter获取数据。5. 通过Shell脚本+定时任务实现自动检查
编写简单的Shell脚本检查Apache进程状态,若未运行则自动重启,并通过Cron定时执行:
/usr/local/bin/check_apache.sh):#!/bin/bash
if ! pgrep -x httpd > /dev/null; then
    echo "$(date): Apache is not running. Restarting..." >> /var/log/apache_monitor.log
    systemctl start httpd
fi
chmod +x /usr/local/bin/check_apache.shcrontab -e
添加以下内容:*/5 * * * * /usr/local/bin/check_apache.sh
日志将记录在/var/log/apache_monitor.log中。