以下是CentOS Apache2性能调优的关键措施:
启用KeepAlive
减少连接建立开销,在/etc/httpd/conf/httpd.conf
中设置:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
调整MPM模块参数
根据服务器资源修改/etc/httpd/conf.modules.d/00-mpm.conf
(以prefork为例):
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # 根据CPU核心数调整
MaxConnectionsPerChild 0
高并发场景可切换为worker
或event
模块(需注释掉prefork配置)。
静态文件缓存
通过mod_expires
减少磁盘访问:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 30 days"
</IfModule>
启用压缩
使用mod_deflate
压缩传输数据:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
优化日志记录
简化日志格式或降低日志级别:
CustomLog logs/access_log common
LogLevel warn
调整内核参数
修改/etc/sysctl.conf
,优化TCP连接和内存管理:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.core.somaxconn = 1024
vm.swappiness = 10 # 减少内存交换
执行sysctl -p
使配置生效。
硬件与文件系统
禁用不必要的模块
编辑httpd.conf
,注释掉未使用的模块(如mod_rewrite
若无需重写规则)。
启用缓存模块
如mod_cache
+mod_disk_cache
,缓存动态内容以减轻后端压力。
top
、htop
、vmstat
等工具监控CPU、内存使用情况。ab
(Apache Benchmark)或wrk
工具测试并发性能,验证优化效果。注意:修改配置后需重启Apache服务(systemctl restart httpd
),建议先在测试环境验证。[1,2,3,4,5,6,7,8,9,10,11]