Apache 在 CentOS 上的并发优化指南
一 选择并配置合适的 MPM
httpd -V | grep -i mpm,输出如 Server MPM: prefork/worker/event。/etc/httpd/conf.modules.d/00-mpm.conf 注释/启用对应模块,例如启用 event:LoadModule mpm_event_module modules/mod_event.so,然后重启 systemctl restart httpd。<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # 并发上限≈该值(每个进程1线程)
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150 # 并发上限≈该值(总线程数)
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
二 连接与协议层优化
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 30 days"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType application/javascript "access plus 30 days"
</IfModule>
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/httpd"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
LoadModule http2_module modules/mod_http2.so
# 在对应虚拟主机启用:Protocols h2 http/1.1
三 操作系统与网络栈优化
/etc/sysctl.conf 增加 fs.file-max = 6815744;生效:sysctl -p。/etc/security/limits.conf 增加* soft nofile 65536
* hard nofile 65536
/etc/sysctl.conf,生效:sysctl -p):net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.ip_local_port_range = 10000 65000
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_syncookies = 1
tcp_tw_recycle 已被移除或不建议启用,优先使用 tcp_tw_reuse。四 监控验证与扩展架构
top/htop、ss -s、netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'。systemctl status httpd、tail -f /var/log/httpd/error_log、/var/log/httpd/access_log;必要时调整 LogLevel(如 warn)降低磁盘 I/O。五 安全与维护建议