提升 Apache2 并发能力的核心思路是:选对并发模型(MPM)、合理控制连接与超时、减少传输开销、释放更多系统资源,并基于监控数据持续迭代。下面给出一套可落地的优化路径与示例配置。
一、选择并切换合适的 MPM
apache2 -V | grep MPMsudo a2dismod mpm_prefork && sudo a2enmod mpm_event && sudo systemctl restart apache2sudo a2dismod mpm_prefork && sudo a2enmod mpm_worker && sudo systemctl restart apache2/etc/httpd/conf.modules.d/00-mpm.conf 中启用对应模块并重启 httpd。二、关键并发参数配置示例
Timeout 60:减少长等待占用;KeepAlive On;MaxKeepAliveRequests 100~500(并发高可适当放大);KeepAliveTimeout 2~5(静态资源多可略大,API 可略小);ListenBacklog 1024(提升突发排队能力)。<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # 依据内存与单进程占用计算
MaxConnectionsPerChild 1000 # 周期性回收,防内存泄漏累积
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150 # = 进程数 * ThreadsPerChild
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
EnableSendfile On
EnableMMAP On
</IfModule>
ps aux | grep -v grep | awk '/httpd|apache2/{sum+=$6;n++} END{print sum/n}'MaxRequestWorkers ≈ 可用内存(GB) * 1024 / 单进程内存(MB);再结合压测逐步上调,确保峰值期 可用内存 > 工作集。三、减少传输与 I/O 开销
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json
DeflateCompressionLevel 6
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
</IfModule>
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot /var/cache/apache2/mod_cache_disk
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
EnableSendfile On、EnableMMAP On(减少用户态/内核态拷贝与上下文切换)。四、系统与内核层优化
sudo sysctl -w fs.file-max=100000 并写入 /etc/sysctl.conf 持久化;同时调整进程级 limits(如 systemd 服务 LimitNOFILE)。net.ipv4.tcp_fin_timeout、net.ipv4.tcp_max_syn_backlog 等,配合压测逐步验证。五、监控、验证与回滚
http://your_server_ip/server-status 观察 Busy/Idle workers、Scoreboard 等指标;按需调整 MPM 与超时。htop、apachetop、netstat -s 等观察 CPU、内存、连接队列、带宽;出现 MaxRequestWorkers 不足 或 队列堆积 时,优先上调 MPM 或缩短 KeepAliveTimeout,其次再考虑硬件与架构扩展。