优化 Apache 以提升访问量与并发能力
一 核心思路与前置检查
二 调整 MPM 并发参数
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 1000
MaxConnectionsPerChild 1000
</IfModule>
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 256
MaxRequestWorkers 150 # 依据内存与单进程占用调整
MaxConnectionsPerChild 1000
</IfModule>
三 连接、超时与压缩缓存
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 30
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
</IfModule>
# Ubuntu/Debian
sudo a2enmod cache
sudo a2enmod cache_disk
# CentOS/RHEL
sudo yum install mod_cache mod_cache_disk
# 配置示例
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
</IfModule>
</IfModule>
四 操作系统与网络栈优化
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
# /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
# 应用
sudo sysctl -p
五 扩展与架构优化
<Proxy balancer://mycluster>
BalancerMember http://node-a:8080
BalancerMember http://node-b:8080
</Proxy>
ProxyPass / balancer://mycluster/
ProxyPassReverse / balancer://mycluster/