以下是提升Ubuntu上Apache性能的关键方法:
选择高效MPM模块
event或worker模块(需禁用prefork):sudo a2dismod mpm_prefork && sudo a2enmod mpm_event # 禁用prefork,启用event
sudo systemctl restart apache2
配置示例(/etc/apache2/mods-enabled/mpm_event.conf):<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
</IfModule>
优化连接与超时设置
KeepAlive并合理设置参数:KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2 # 低延迟场景可设为1-3秒
启用缓存与压缩
mod_cache+mod_cache_disk):sudo a2enmod cache cache_disk
配置缓存目录:CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
mod_deflate压缩动态内容:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
限制资源占用
MaxRequestWorkers(根据服务器内存计算,如每进程约20-50MB):MaxRequestWorkers 100 # 示例值,需结合服务器资源调整
MaxConnectionsPerChild 1000 # 防止内存泄漏
mod_status等):sudo a2dismod status
系统级优化
sudo sysctl -w fs.file-max=100000
echo "fs.file-max = 100000" >> /etc/sysctl.conf
vm.swappiness=10):sudo sysctl -w vm.swappiness=10
监控与调优
htop、apachetop监控资源使用,动态调整参数。/var/log/apache2/access.log/error.log),排查异常请求。注意:修改配置前需备份文件,生产环境建议先在测试环境验证。高流量场景可结合负载均衡(如Nginx反向代理)进一步提升性能。