為確保 Apache HTTP 服務高可用,需在服務異常停止時能自動偵測並重啟。傳統做法是撰寫輪詢腳本放入背景執行,現代 Linux 則建議搭配 systemd 的 Restart=on-failure 機制,或使用 systemd timer 替代 cron。本文提供兩種方案:經典 Shell 輪詢腳本(相容舊系統)與 systemd 原生高可用設定(推薦生產環境)。
curl 對 https://127.0.0.1/ 發送 HEAD 請求,連線逾時 15 秒、總逾時 20 秒。/etc/init.d/httpd restart。while true; do ... sleep 10; done 持續監控。# 1. 建立腳本
cat > /opt/autorshttpd <<'EOF'
#!/bin/bash
URL="https://127.0.0.1/"
curlit() {
curl --connect-timeout 15 --max-time 20 --head --silent "$URL" | grep -q '^HTTP/.* 200'
}
doit() {
if ! curlit; then
/etc/init.d/httpd restart > /dev/null 2>&1
fi
}
while true; do
doit
sleep 10
done
EOF
# 2. 賦予執行權限
chmod 755 /opt/autorshttpd
# 3. 測試執行(背景執行)
nohup /opt/autorshttpd > /var/log/autorshttpd.log 2>&1 &
# 4. 設定開機自啟(rc.local 或 systemd service)
echo "/opt/autorshttpd > /var/log/autorshttpd.log 2>&1 &" >> /etc/rc.local
chmod +x /etc/rc.local
注意:nohup ... & 確保 SSH 斷線後腳本仍在背景運行;生產環境建議導向日誌檔便於稽核。
現代發行版(RHEL 7+/CentOS 7+/Ubuntu 16.04+/Debian 9+)皆使用 systemd 管理服務,無需額外腳本即可實現自動重啟。
# 建立 override 目錄
mkdir -p /etc/systemd/system/httpd.service.d
# 撰寫覆蓋檔
cat > /etc/systemd/system/httpd.service.d/restart.conf <<'EOF'
[Service]
Restart=on-failure
RestartSec=10
StartLimitIntervalSec=60
StartLimitBurst=3
# 可選:健康檢查(需 Apache 2.4+ mod_proxy_hcheck 或外部監控)
# ExecStartPre=/usr/bin/curl -f https://127.0.0.1/ || exit 1
EOF
# 重載並重啟服務
systemctl daemon-reload
systemctl restart httpd
Restart=on-failure:非正常退出(非 0、信號、逾時)自動重啟RestartSec=10:重啟前等待 10 秒,避免快速失敗風暴StartLimitIntervalSec/Burst:限制單位時間重啟次數,防止無限循環# /etc/systemd/system/httpd-healthcheck.service
[Unit]
Description=Apache HTTPD Health Check
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/bin/bash -c 'curl -f -s -o /dev/null --max-time 10 https://127.0.0.1/ || systemctl restart httpd'
# /etc/systemd/system/httpd-healthcheck.timer
[Unit]
Description=Run Apache health check every 30 seconds
[Timer]
OnBootSec=1min
OnUnitActiveSec=30s
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now httpd-healthcheck.timer
| 維度 | Shell 輪詢腳本 | systemd 原生 |
|---|---|---|
| 相容性 | 極高(任何 init 系統) | 需 systemd 發行版 |
| 資源佔用 | 常駐進程 + 定期 fork curl | 事件驅動 + timer 觸發,較輕量 |
| 日誌整合 | 自行導向檔案 | 自動納入 journald,journalctl -u httpd 即可查 |
| 狀態感知 | 僅 HTTP 回應碼 | 可結合 WatchdogSec、HealthCheck 擴充 |
| 維護性 | 需手動管理 PID、logrotate | 標準化單元檔,版本控制友善 |
結論:新部署優先採用 systemd 方案;舊系統或容器環境無 systemd 時,Shell 腳本仍是可靠備案。
/healthz(檢查資料庫連線、快取、磁碟空間等)logrotate 管理 /var/log/autorshttpd.log 或 journald 保留策略keepalived / haproxy 實現多節點負載均衡與故障轉移,單機自動重啟只是基礎防線透過上述方法,可大幅降低 Apache 服務中斷風險,構建更穩健的 Web 服務基礎設施。