在 Debian 上优化 Apache2,可以从系统层面、Apache 配置、模块、缓存、安全、监控几个方面入手。下面按「实用 + 可操作」的方式说明。
编辑 /etc/sysctl.conf:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 100000
执行:
sysctl -p
ulimit -n 65535
写入:
/etc/security/limits.conf
www-data soft nofile 65535
www-data hard nofile 65535
mpm_event(高并发)查看当前 MPM:
apache2ctl -V | grep MPM
启用 event MPM:
a2dismod mpm_prefork
a2dismod mpm_worker
a2enmod mpm_event
编辑:
/etc/apache2/mods-enabled/mpm_event.conf
示例(4 核 8G):
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 64
MaxSpareThreads 128
ThreadsPerChild 64
MaxRequestWorkers 512
MaxConnectionsPerChild 10000
</IfModule>
经验值:
MaxRequestWorkers ≈ 内存 / 每进程内存MaxConnectionsPerChild 防止内存泄漏查看已启用模块:
apache2ctl -M
常见可禁用:
a2dismod status
a2dismod autoindex
a2dismod negotiate
a2dismod cgi
a2enmod cache cache_disk expires headers
<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>
a2enmod deflate
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
/etc/apache2/apache2.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
太高会占用连接,太低会增加 TCP 握手
apt install php-fpm
a2enmod proxy_fcgi setenvif
a2enconf php-fpm
关闭:
a2dismod php8.*
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
或关闭多余日志:
LogLevel warn
a2enmod headers
ServerTokens Prod
ServerSignature Off
apache2ctl status
apt install apache2-utils
ab -n 10000 -c 200 http://localhost/
| 项目 | 优化前 | 优化后 |
|---|---|---|
| 并发 | 200 | 2000+ |
| 内存 | 高 | 低 |
| 响应 | 慢 | 快 |
你可以告诉我:
我可以给你一套精准的 Apache 配置模板。