Apache2優化Ubuntu服務器性能的完整指南
sudo apt update && sudo apt upgrade,確保Ubuntu內核、Apache2及依賴模塊為最新版本,獲取性能改進與安全補丁。apachectl -M查看已加載模塊,通過sudo a2dismod [模塊名](如mod_status、mod_autoindex)禁用未使用的模塊,減少內存與CPU占用。sudo a2enmod deflate(壓縮)、expires(緩存過期)、rewrite(URL重寫)、cache(緩存),并通過sudo systemctl restart apache2生效。Apache2的MPM(多路復用模塊)決定了進程/線程的管理方式,需根據服務器用途選擇:
/etc/apache2/mods-enabled/mpm_prefork.conf,調整參數:<IfModule mpm_prefork_module>
StartServers 5 # 啟動時的進程數
MinSpareServers 5 # 最小空閑進程數
MaxSpareServers 10 # 最大空閑進程數
MaxRequestWorkers 150 # 最大并發請求數(根據內存計算:總內存/單個進程內存)
MaxConnectionsPerChild 1000 # 每個進程處理1000個請求后重啟(防止內存泄漏)
</IfModule>
/etc/apache2/mods-enabled/mpm_worker.conf,調整參數:<IfModule mpm_worker_module>
StartServers 2 # 啟動時的進程數
MinSpareThreads 25 # 最小空閑線程數
MaxSpareThreads 75 # 最大空閑線程數
ThreadLimit 64 # 線程數上限
ThreadsPerChild 25 # 每個子進程的線程數
MaxRequestWorkers 150 # 最大并發請求數
MaxConnectionsPerChild 0 # 0表示不限制(或設為較大值)
</IfModule>
注:
MaxRequestWorkers需根據服務器內存計算(如1GB內存的服務器,每個Apache進程約占用100MB,則MaxRequestWorkers可設為10-15)。
/etc/apache2/mods-enabled/deflate.conf,添加壓縮類型:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
壓縮可減少傳輸數據量(通常減少50%-70%),提升頁面加載速度。/etc/apache2/mods-enabled/expires.conf,設置靜態資源過期時間:<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
緩存可減少重復請求,降低服務器負載。/etc/apache2/apache2.conf,開啟持久連接:KeepAlive On
MaxKeepAliveRequests 100 # 每個連接最大請求數(避免單個連接占用過久)
KeepAliveTimeout 5 # 空閑連接超時時間(秒)
KeepAlive可減少TCP握手開銷(約60%的延遲降低),但需平衡MaxKeepAliveRequests與KeepAliveTimeout,避免過多空閑連接占用內存。/etc/apache2/apache2.conf,縮短請求超時時間:Timeout 30 # 默認120秒,縮短至30秒(減少長時間占用連接)
top/htop查看Apache進程的內存/CPU占用;apachetop(sudo apt install apachetop)實時監控請求速率與響應時間;vmstat 1查看系統級資源使用(如CPU、內存、I/O)。/etc/apache2/sites-available/[站點配置],將CustomLog/ErrorLog設為/dev/null(僅用于生產環境,調試時開啟);logrotate自動清理舊日志:sudo logrotate -f /etc/logrotate.conf(避免日志文件過大占用磁盤空間)。sudo systemctl restart apache2),釋放內存碎片與緩存,保持服務穩定。MaxRequestWorkers;/etc/sysctl.conf,優化網絡與內存設置:fs.file-max = 65536 # 最大文件描述符數
net.ipv4.tcp_tw_reuse = 1 # 重用TIME_WAIT連接
vm.swappiness = 10 # 減少交換空間使用(優先使用內存)
運行sudo sysctl -p使配置生效。通過以上步驟,可顯著提升Ubuntu服務器上Apache2的性能,適用于大多數中小型網站與Web應用。優化過程中需根據實際負載(如并發數、內存占用)調整參數,避免過度配置導致資源浪費。