在 CentOS 上优化 Apache(通常是 httpd),一般从 系统层面、Apache 配置、模块、缓存、安全与监控 几个方面入手。下面按实用优先级给你一套可落地的优化方案(以 CentOS 7/8 + Apache 2.4 为例)。
getenforce
# 如果是 Enforcing 且不影响业务,可设为 Permissive
setenforce 0
# 永久
sed -i 's/SELINUX=enforcing/SELINUX=permissive/' /etc/selinux/config
ulimit -n 65535
永久生效:
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
sysctl -p
查看当前 MPM:
httpd -V | grep -i mpm
eventpreforkevent修改:
vim /etc/httpd/conf.modules.d/00-mpm.conf
示例(event):
LoadModule mpm_event_module modules/mod_mpm_event.so
vim /etc/httpd/conf.d/mpm.conf
<IfModule mpm_event_module>
ServerLimit 16
StartServers 4
MinSpareThreads 64
MaxSpareThreads 128
ThreadsPerChild 64
MaxRequestWorkers 1024
MaxConnectionsPerChild 10000
</IfModule>
调优原则:
MaxRequestWorkers = ServerLimit × ThreadsPerChild
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
vim /etc/httpd/conf.d/deflate.conf
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
vim /etc/httpd/conf.d/expires.conf
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 30 days"
ExpiresByType text/css "access plus 7 days"
ExpiresByType application/javascript "access plus 7 days"
</IfModule>
Apache (event) + PHP-FPM
<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
vim /etc/php-fpm.d/www.conf
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 40
CustomLog logs/access_log combined
# 高并发可关闭或异步
Options -Indexes
# 隐藏版本
ServerTokens Prod
ServerSignature Off
httpd -t
systemctl restart httpd
ab -n 10000 -c 200 http://localhost/
top / htopss -ant | wc -lmod_status启用:
<Location /server-status>
SetHandler server-status
Require local
</Location>
| 问题 | 原因 | 解决 |
|---|---|---|
| 并发上不去 | prefork + mod_php | 换 event + PHP-FPM |
| CPU 高 | 未开 gzip | 启用 deflate |
| 内存爆 | MaxRequestWorkers 过大 | 降低 |
| 响应慢 | KeepAlive 过长 | 调小 |
如果你愿意,可以告诉我:
我可以给你一套针对性配置模板。