Ubuntu 上优化 Apache2 的 CPU 使用
一 基线检查与模块精简
apache2 -v、systemctl status apache2,确保为稳定版本并运行正常。apache2ctl -M;禁用不需要的模块:sudo a2dismod module_name;启用必要模块:sudo a2enmod module_name。sudo a2enmod deflate。sudo a2enmod cache、sudo a2enmod cache_disk。ExtendedStatus On 并在 <Location /server-status> 中设置访问控制。二 选择并调优 MPM(多处理模块)
sudo a2dismod mpm_prefork → sudo a2enmod mpm_event(或 mpm_worker)→ sudo systemctl restart apache2。pmap/smem),再设置 MaxRequestWorkers,使“单进程内存 × MaxRequestWorkers ≤ 可用内存 × 0.7”。<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
三 连接与会话层优化
KeepAlive On 减少 TCP/SSL 握手与进程/线程创建销毁次数。MaxKeepAliveRequests 100 限制单连接请求数,避免长连接被少数客户端长期占用。KeepAliveTimeout 2(繁忙站点建议 1–5 秒)降低空闲占用;过小会影响页面内多资源加载。ports.conf 的 443 监听上添加 http2),多路复用可显著减少连接开销;确保 TLS 配置合理,避免过高加密套件导致 CPU 飙升。四 缓存与内容层面优化
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
五 监控与迭代流程
top/htop、apache2ctl status、curl -w 观察 CPU%、负载、请求耗时、并发连接;必要时开启 mod_status 的 ExtendedStatus 做细粒度排查。ab、wrk、jmeter 在测试环境进行基线压测,逐步调整 MPM 参数、KeepAlive、缓存策略,观察 吞吐、P95/P99 延迟与 CPU 变化。sudo systemctl reload apache2(或重启)生效,异常及时回滚。