优化 Ubuntu 上 Apache2 的性能,通常可以从系统层面、Apache 配置、模块管理、缓存与压缩、PHP/后端、监控几个方面入手。下面给你一套比较实用、可落地的优化方案。
编辑 /etc/sysctl.conf:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 1000000
应用:
sysctl -p
编辑 /etc/security/limits.conf:
* soft nofile 100000
* hard nofile 100000
apachectl -V | grep MPM
eventpreforkevent + php-fpm(推荐)启用 event:
a2dismod mpm_prefork
a2enmod mpm_event
编辑 /etc/apache2/mods-enabled/mpm_event.conf:
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 64
MaxSpareThreads 128
ThreadLimit 256
ThreadsPerChild 64
MaxRequestWorkers 512
MaxConnectionsPerChild 10000
</IfModule>
根据内存调整:
MaxRequestWorkers ≈ 可用内存 / 每进程内存
查看已启用模块:
apache2ctl -M
常见可关闭:
a2dismod status
a2dismod autoindex
a2dismod cgi
保持最小集:
a2enmod deflate
/etc/apache2/mods-enabled/deflate.conf:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
a2enmod expires
示例:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
/etc/apache2/apache2.conf:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
避免过长占用连接。
apt install php-fpm
a2enmod proxy_fcgi setenvif
a2enconf php8.2-fpm
关闭 mod_php:
a2dismod php8.2
PHP-FPM 池优化:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
ProxyPass /api/ http://127.0.0.1:8080/
减少日志量:
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
或使用:
LogLevel warn
a2enmod status
访问:
http://your-server/server-status
ab -n 10000 -c 200 http://localhost/
或:
wrk -t4 -c200 -d30s http://localhost/
✅ 最佳实践:
如果你愿意,可以告诉我:
我可以帮你直接给出一份可用的 Apache 配置文件。