Ubuntu Apache2性能调优步骤
sudo apt update && sudo apt upgrade
,确保Apache2及依赖包为最新版本,获取性能改进与安全修复。sudo apt install apache2
完成基础部署。MPM(多处理模块)是Apache2的核心组件,需根据服务器负载类型选择:
/etc/apache2/mods-enabled/mpm_prefork.conf
):<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 4000
</IfModule>
/etc/apache2/mods-enabled/mpm_worker.conf
):<IfModule mpm_worker_module>
StartServers 5
MinSpareThreads 256
MaxSpareThreads 768
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 4000
</IfModule>
/etc/apache2/mods-enabled/mpm_event.conf
):<IfModule mpm_event_module>
StartServers 5
MinSpareThreads 256
MaxSpareThreads 768
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 4000
</IfModule>
注意:修改MPM配置后需重启Apache(
sudo systemctl restart apache2
)。
/etc/apache2/mods-enabled/deflate.conf
中添加:AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
/etc/apache2/mods-enabled/expires.conf
中添加:ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
mod_cache
与mod_cache_disk
,并在配置中添加:LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
CacheEnable disk /
CacheRoot "/var/cache/apache2"
CacheDirLevels 2
CacheDirLength 1
/etc/apache2/sites-available/example.conf
):RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
操作:使用
sudo a2enmod deflate expires cache cache_disk rewrite
启用模块,修改配置后重启Apache。
启用KeepAlive减少TCP握手开销,提升并发效率。在/etc/apache2/apache2.conf
中调整:
KeepAlive On
MaxKeepAliveRequests 100 # 单个连接最大请求数
KeepAliveTimeout 5 # 连接保持时间(秒)
说明:
MaxKeepAliveRequests
过小会导致频繁重建连接,过大则会占用内存;KeepAliveTimeout
过长会增加无效连接占用。
根据服务器资源(CPU、内存)限制并发连接,避免过载:
MaxClients
):最大并发请求数,建议设置为内存容量的1/4(如8GB内存可设为2000);mod_deflate
压缩静态资源,减少网络传输时间(如上述mod_deflate
配置);mod_cache
与mod_expires
缓存静态内容(如图片、CSS),降低服务器负载(如上述mod_cache
与mod_expires
配置)。禁用未使用的模块,减少资源消耗与攻击面。使用sudo a2dismod module_name
(如sudo a2dismod status
禁用状态模块),保留必需模块(如rewrite
、ssl
、deflate
)。
mod_status
监控性能指标,在/etc/apache2/mods-enabled/status.conf
中配置:LoadModule status_module modules/mod_status.so
ExtendedStatus On
<Location "/server-status">
SetHandler server-status
Require ip 127.0.0.1 # 仅允许本地访问
</Location>
访问http://服务器IP/server-status
查看实时性能数据;logrotate
自动清理过期日志,避免日志文件过大占用磁盘空间(默认配置/etc/logrotate.conf
,无需额外修改)。/etc/sysctl.conf
优化网络栈,添加:net.ipv4.tcp_tw_reuse = 1 # 复用TIME_WAIT连接
net.core.somaxconn = 4096 # 增加监听队列长度
net.ipv4.tcp_max_syn_backlog = 4096 # 增加SYN队列长度
运行sudo sysctl -p
使配置生效;/var/www/html
)放在SSD上,提升磁盘I/O性能;ab
(Apache Benchmark)工具模拟高并发请求,评估调优效果:ab -n 1000 -c 100 http://yourdomain.com/
(-n
:总请求数;-c
:并发数);top
、htop
、vmstat
等工具监控CPU、内存、磁盘I/O使用率,根据实际情况调整参数(如MaxRequestWorkers
)。