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 -nr
grep " 404 " /var/log/httpd/access_log
awk '{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抓?。ㄈ?code>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.sh
crontab -e
添加以下內容:*/5 * * * * /usr/local/bin/check_apache.sh
日志將記錄在/var/log/apache_monitor.log
中。