Apache 效能調校核心在於MPM 參數與記憶體使用平衡。以 Red Hat 系 httpd 2.4 (event MPM) 為例,完整測試流程:
ps -ylC httpd --sort:rss
# 輸出關鍵欄位:RSS (常駐記憶體 KB)、VSZ (虛擬記憶體 KB)
# 經驗值:event MPM 單進程 RSS 約 20~40 MB (含共享庫)
# 保守估算:可用記憶體 × 0.6 / 單進程 RSS = MaxRequestWorkers 上限
# 1000 請求、100 併發、啟用 Keep-Alive
ab -n 1000 -c 100 -k https://example.com/
# 關鍵指標:
# Requests per second (RPS)
# Time per request (mean, across all concurrent)
# Transfer rate (KB/sec)
# Percentage of requests served within XX ms (P50/P90/P99)
| 參數 (httpd.conf / conf.d/mpm.conf) | 預設值 | 建議調整方向 | 影響 |
|---|---|---|---|
| ServerLimit | 256 | 依記憶體上限設定 (≤ MaxRequestWorkers / ThreadsPerChild) | 進程數上限 |
| MaxRequestWorkers | 256 (event: ServerLimit × ThreadsPerChild) | ≈ (可用 RAM × 0.6) / 單進程 RSS | 最大併發連線數 |
| ThreadsPerChild | 25 | 25~64 (依 CPU 核心、鎖競爭調整) | 每進程執行緒數 |
| KeepAlive | On | On | 連線重用 |
| KeepAliveTimeout | 5 (秒) | 2~3 秒 (高併發環境) | 釋放閒置連線速度 |
| MaxKeepAliveRequests | 100 | 100~500 | 單連線最大請求數 |
| AsyncRequestWorkerFactor | 2 | 1.5~3 (event MPM 專用) | 非同步工作者額外容量係數 |
# 方案 A:保守 (預設)
ServerLimit 16
MaxRequestWorkers 400
ThreadsPerChild 25
KeepAliveTimeout 5
→ ab -n 1000 -c 100 -k : RPS 1,200, P99 850ms, 平均負載 0.30
# 方案 B:激進
ServerLimit 32
MaxRequestWorkers 800
ThreadsPerChild 25
KeepAliveTimeout 2
→ ab -n 1000 -c 100 -k : RPS 2,100, P99 420ms, 平均負載 0.85 (接近飽和)
# 方案 C:平衡 (推薦)
ServerLimit 24
MaxRequestWorkers 600
ThreadsPerChild 25
KeepAliveTimeout 2
MaxKeepAliveRequests 200
→ ab -n 1000 -c 100 -k : RPS 1,850, P99 510ms, 平均負載 0.55
EnableMMAP Off、EnableSendfile On (核心 2.4+ 預設開啟,NFS 掛載需關閉)。HostnameLookups Off (避免反向 DNS 查詢延遲)。ExtendedStatus Off (關閉 mod_status 詳細統計,省 CPU)。LoadModule 僅保留必要 (mod_ssl, mod_proxy, mod_headers, mod_rewrite, mod_deflate, mod_expires, mod_security)。mod_deflate + mod_brotli (httpd 2.4.26+)。mod_cache_disk / mod_cache_socache + Redis/ Memcached 後端。ab / wrk / h2load 至少 3 次取中位數。top -bn1 | grep httpd、free -h、iostat -x 1、sar -n DEV 1。Prometheus + node_exporter + apache_exporter 持續觀測 RPS、延遲分位、錯誤率、連線池使用率。以資料驅動調校,而非經驗猜測,才能榨乾 Apache 效能。