Apache HTTP Server (httpd) 的啟動、停止、重啟看似簡單,但優雅重啟、信號語義、多 MPM 模型差異直接影響線上服務可用性。本文覆蓋 systemd、SysVinit、apachectl、直接信號四種控制方式,深度解析優雅重啟原理與生產環境最佳實踐。
# 啟動
sudo systemctl start apache2 # Ubuntu/Debian 服務名
sudo systemctl start httpd # RHEL/CentOS/Fedora 服務名
# 停止
sudo systemctl stop apache2
# 重啟 (硬重啟:SIGTERM → SIGKILL → 再啟動)
sudo systemctl restart apache2
# 重新載入配置 (優雅重啟:SIGHUP / USR1)
sudo systemctl reload apache2
# 狀態檢查
systemctl status apache2
# 開機自啟
sudo systemctl enable apache2
/etc/init.d/apache2 start|stop|restart|reload|status
# 或
service apache2 start|stop|restart|reload|status
所有上層命令最終都轉為向父進程 (PID 寫在 PidFile) 發送信號:
| 動作 | 信號 | apachectl 參數 | httpd -k 參數 | 行為描述 |
|---|---|---|---|---|
| 立即停止 | SIGTERM (15) | stop | stop | 父進程殺死所有子進程並退出,進行中請求被強行中斷 |
| 優雅停止 | SIGWINCH | graceful-stop | graceful-stop | 子進程完成當前請求後退出,父進程停止監聽,等待所有子進程結束 |
| 優雅重啟 | SIGUSR1 | graceful | graceful | 子進程完成請求後退出,父進程重讀配置、重開日誌、按新配置產生新子進程,**零停機** |
| 硬重啟 | SIGHUP (1) | restart | restart | 類似 stop+start,父進程不退出,但子進程被強制殺死,有極短暫不可用窗口 |
# 讀取 PID 文件發送信號
kill -USR1 $(cat /var/run/apache2/apache2.pid) # 優雅重啟
kill -HUP $(cat /var/run/apache2/apache2.pid) # 硬重啟
kill -TERM $(cat /var/run/apache2/apache2.pid) # 停止
kill -WINCH $(cat /var/run/apache2/apache2.pid) # 優雅停止
httpd.conf、*.conf、.htaccess (若啟用)ErrorLog、CustomLog (支援日誌輪轉)StartServers、MinSpareServers/Threads 參數啟動新子進程/線程apachectl graceful 完美協作apachectl configtest 或 httpd -tmod_status 會標記優雅重啟前的子進程為 G (Gracefully finishing)| MPM | 子進程/線程模型 | 優雅重啟特點 |
|---|---|---|
| prefork | 多進程,每進程單線程 | 進程級隔離,記憶體佔用大,重啟較慢 |
| worker | 多進程,每進程多線程 | 線程級優雅退出,需注意線程安全 |
| event (預設 2.4+) | 多進程,專用監聽線程 + 工作線程 | 最佳 KeepAlive 處理,優雅重啟效率最高 |