在 Ubuntu 上调整 Apache 内存使用的实用步骤
一 基线评估与监控
二 选择合适 MPM 并调整核心并发参数
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150 # 依据上式计算
MaxConnectionsPerChild 1000 # 定期回收,缓解内存碎片/泄漏
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150 # 依据上式计算
MaxConnectionsPerChild 1000
</IfModule>
sudo apachectl configtest
sudo systemctl restart apache2
三 连接与会话优化
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2
适度降低 KeepAliveTimeout 可在相同内存下支持更多连接;过高会保持过多空闲连接占用内存。# 启用模块
sudo a2enmod deflate expires cache cache_disk
# 示例:磁盘缓存与过期头
<IfModule mod_cache.c>
CacheDefaultExpire 86400
CacheEnable disk /
CacheRoot /var/cache/apache2/mod_cache_disk
CacheDirLevels 2
CacheDirLength 1
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
</IfModule>
修改后执行 sudo apachectl configtest && sudo systemctl restart apache2。四 模块精简与系统层面优化
五 验证与回滚