Ubuntu下Apache2性能提升实操指南
一 基础与架构优化
二 关键参数与示例配置
| 参数 | 作用 | 建议起点 | 说明 |
|---|---|---|---|
| KeepAlive | 持久连接 | On | 减少TCP握手 |
| MaxKeepAliveRequests | 单连接最大请求数 | 100 | 过高会占用连接资源 |
| KeepAliveTimeout | 持久连接超时 | 5 秒 | 过大浪费资源 |
| Timeout | 请求整体超时 | 5 秒 | 视业务与上游而定 |
| MaxRequestWorkers | 最大并发工作者 | 依内存与MPM估算 | 见下方估算方法 |
| ServerLimit | prefork的Server上限 | 与MaxRequestWorkers匹配 | prefork特有 |
| StartServers/MinSpareServers/MaxSpareServers | 进程池规模 | 依负载阶梯设置 | prefork特有 |
| MaxConnectionsPerChild | 进程回收 | 3000–10000 | 防内存泄漏累积 |
| ThreadsPerChild | 每进程线程数 | 依CPU与内存 | worker/event特有 |
| ServerTokens / ServerSignature | 版本信息暴露 | Prod / Off | 降低攻击面 |
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 256
MaxRequestWorkers 256
MaxConnectionsPerChild 4000
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 5
HostnameLookups Off
ServerTokens Prod
ServerSignature Off
# 压缩
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript
# 过期策略
ExpiresActive On
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/png "access plus 1 year"
# 静态资源磁盘缓存(按需)
CacheEnable disk /
CacheRoot "/var/cache/apache2"
CacheDirLevels 2
CacheDirLength 1
三 启用HTTP/2与SSL
四 监控验证与上线流程
sudo apache2ctl configtestsudo systemctl restart apache2top/htop、vmstat 1、netstat -s、ss -s观察CPU、内存、连接数、套接字状态。五 场景化建议与注意事项