优化 Ubuntu 上 Apache2 的性能可以从系统层面、Apache 配置、模块管理、缓存与压缩、以及架构层面几个方向入手。下面给你一套实用、可落地的优化方案。
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 中添加:
* soft nofile 65535
* hard nofile 65535
apache2ctl -V | grep MPM
推荐:
event(默认新版本)prefork编辑:
/etc/apache2/mods-available/mpm_event.conf
示例(4 核 8G):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
查看已启用模块:
a2dismod
常见可关闭的:
a2dismod status autoindex cgi negotiation userdir
保留核心:
rewriteheaderssslproxy(如使用)a2enmod deflate
配置:
<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"
</IfModule>
apt install php-fpm
a2enmod proxy_fcgi setenvif
a2enconf php-fpm
PHP-FPM 配置:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
SetEnvIf Request_URI "\.(css|js|png)$" dontlog
LogLevel warn
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
用户 → Nginx/CDN → Apache
apt install apache2-utils
ab -n 1000 -c 100 http://localhost/
htop
apache2ctl status
✅ Ubuntu + Apache(event) + PHP-FPM
✅ 开启 deflate / expires
✅ 关闭无用模块
✅ CDN 加速静态资源
如果你愿意,可以告诉我:
我可以直接帮你写一套针对性配置。