下面从 系统层、Apache 本身、模块与代码、监控 几个方面,系统性地讲一下 CentOS + Apache 的优化思路(以 CentOS 7/8 + Apache 2.4 为例,也适用于 Rocky/Alma)。
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
fs.file-max = 1000000
生效:
sysctl -p
# /etc/security/limits.conf
* soft nofile 100000
* hard nofile 100000
getenforce
# 如果是 enforcing 且不影响业务,可设为 permissive
setenforce 0
查看当前 MPM:
httpd -V | grep MPM
CentOS 默认一般是 prefork,建议改为 event:
yum install httpd mod_ssl
编辑:
/etc/httpd/conf.modules.d/00-mpm.conf
LoadModule mpm_event_module modules/mod_mpm_event.so
# 注释掉 prefork / worker
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 64
MaxSpareThreads 128
ThreadsPerChild 64
MaxRequestWorkers 512
MaxConnectionsPerChild 10000
</IfModule>
MaxRequestWorkers 不要超过系统内存承受范围
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
减少攻击面 & 内存占用:
# 注释掉不需要的 LoadModule
mod_status
mod_userdir
mod_autoindex
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
<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>
适合静态内容多的站点。
yum install php-fpm
Apache 配置:
<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
CustomLog logs/access_log combined env=!dontlog
SetEnvIf Request_URI "\.(jpg|css|js|png)$" dontlog
/etc/logrotate.d/httpd
Options -Indexes
LimitRequestBody 10485760
RequestReadTimeout header=10-20,MinRate=500
<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1
</Location>
ab -n 10000 -c 200 http://localhost/
| 现象 | 可能原因 |
|---|---|
| CPU 高 | PHP 慢 / 未开 OPcache |
| 内存爆 | prefork + 进程多 |
| 连接慢 | KeepAlive 过长 |
| 并发上不去 | MaxRequestWorkers 小 |
✅ CentOS + Apache(event) + PHP-FPM + OPcache + gzip + CDN
如果你愿意,可以告诉我:
我可以给你一份 可直接用的配置模板。