Apache2如何提升Ubuntu服务器性能
小樊
46
2025-12-28 19:06:14
Ubuntu上Apache2性能优化实战指南
一 基础优化
- 更新系统与软件包:执行sudo apt update && sudo apt upgrade,获取性能修复与安全补丁。
- 精简模块:仅启用必需模块,禁用无用模块(如a2dismod status),降低内存占用与攻击面。
- 启用持久连接:在**/etc/apache2/apache2.conf中开启KeepAlive On**,建议MaxKeepAliveRequests 100、KeepAliveTimeout 5,减少TCP握手与排队。
- 启用压缩:启用mod_deflate并压缩文本类资源(如text/html、text/css、application/javascript),显著降低传输体积。
- 配置缓存:启用mod_cache/mod_disk_cache,示例:
CacheEnable disk /
CacheRoot “/var/cache/apache2”
CacheDirLevels 2
CacheDirLength 1
- 减少.htaccess开销:在生产站点将AllowOverride None,避免每个请求递归检查目录.htaccess。
- 启用HTTP/2:启用mod_http2,在**/etc/apache2/ports.conf使用Listen 443 ssl http2**,提升并发与首包速度。
- 优化SSL/TLS:仅启用安全协议与强套件,开启会话缓存,示例:
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
SSLSessionCache shmcb:/var/run/ssl_scache(512000)
SSLSessionCacheTimeout 300
二 选择并调整MPM并发模型
- 选择原则:
- prefork:进程模型,兼容性好(如传统mod_php),但内存占用较高。
- worker/event:多线程/事件驱动,适合高并发动态内容(如PHP-FPM、Node.js、Python)。
- 配置示例(数值需结合内存与压测微调):
- prefork(适合兼容场景):
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 4000
- worker/event(适合高并发):
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0(建议充分压测后再设为0)
- 修改后重启:sudo systemctl restart apache2。
三 系统与网络层优化
- 硬件与存储:优先SSD、多核CPU与充足内存,减少I/O与CPU瓶颈。
- 内核网络参数(编辑**/etc/sysctl.conf**):
net.core.somaxconn = 4096(增大监听队列)
net.ipv4.tcp_tw_reuse = 1(复用TIME_WAIT连接)
vm.swappiness = 10(降低换页倾向)
应用:sudo sysctl -p。
- 文件描述符限制:提升进程可打开文件数(如LimitNOFILE=65536于服务单元或**/etc/security/limits.conf**),避免“Too many open files”。
- 静态资源减负:将图片、CSS、JS托管至CDN,显著降低源站压力与跨地域时延。
四 监控与维护
- 启用状态页:启用mod_status,仅内网访问:
<Location “/server-status”>
SetHandler server-status
Require ip 127.0.0.1 [::1]
访问http://localhost/server-status查看请求数、CPU、Worker等关键指标。
- 日志轮转:配置**/etc/logrotate.d/apache2**,示例:
/var/log/apache2/*.log { daily; rotate 30; compress; delaycompress; missingok; notifempty; create 640 root adm; sharedscripts; postrotate; systemctl reload apache2; endscript }
- 压测与验证:使用ab(ApacheBench)或wrk进行基线测试与回归测试,每次仅调整1–2项参数并观察RPS、P95/P99、错误率与资源占用。
- 错误排查:定期分析**/var/log/apache2/error.log**,结合top/htop、ss -s定位瓶颈。
五 场景化配置建议
- 动态PHP站点(如mod_php):优先prefork,按“单进程内存×MaxRequestWorkers ≤ 物理内存×0.7”估算上限,避免OOM;启用OPcache减少脚本编译开销。
- 高并发API/反向代理:使用event MPM + PHP-FPM,开启HTTP/2,必要时用mod_proxy_balancer做负载均衡:
Proxy balancer://mycluster
BalancerMember http://backend1.example.com
BalancerMember http://backend2.example.com
ProxyPass / balancer://mycluster
- 静态资源为主:启用mod_cache/mod_disk_cache,设置较长Cache-Control/Expires;结合CDN与mod_deflate进一步减负。
- 安全与性能并重:保持Apache/模块及时更新,精简模块与**.htaccess**使用,限制敏感路径访问,减少攻击面与文件系统开销。