MPM是Apache处理并发请求的核心模块,不同模式的内存占用差异显著。Debian默认使用prefork(适合兼容性场景)或event/worker(适合高并发场景),需根据服务器资源选择:
/etc/apache2/mods-enabled/mpm_prefork.conf):<IfModule mpm_prefork_module>
StartServers 5 # 启动时的进程数
MinSpareServers 5 # 最小空闲进程数
MaxSpareServers 10 # 最大空闲进程数
MaxRequestWorkers 150 # 最大并发请求数(根据内存调整,如1GB内存建议100-150)
MaxConnectionsPerChild 1000 # 每个进程处理1000个请求后重启(防止内存泄漏)
</IfModule>
event为例(/etc/apache2/mods-enabled/mpm_event.conf):<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0 # 0表示不限制(需配合MaxRequestWorkers限制总并发)
</IfModule>
注:修改MPM后需重启Apache:
sudo systemctl restart apache2。
Apache默认加载的模块较多,禁用未使用的模块可显著减少内存占用:
apache2ctl -M(或httpd -M)。status、autoindex、cgi等):sudo a2dismod status autoindex cgi
sudo systemctl restart apache2
提示:仅保留必需模块(如
authz_core、log_config、expires等)。
KeepAlive可减少TCP连接建立的开销,但过度使用会增加内存占用(每个连接对应一个进程/线程):
KeepAlive On(/etc/apache2/apache2.conf)。MaxKeepAliveRequests 100(避免单个连接占用过多资源)。KeepAliveTimeout 5(单位:秒,默认15秒,5秒足够大多数场景)。MemoryLimit参数(仅prefork模式有效)控制单个进程的最大内存,避免单个进程占用过多内存导致崩溃:<IfModule mpm_prefork_module>
MemoryLimit 128M # 根据应用需求调整(如128M-256M)
</IfModule>
MaxConnectionsPerChild设置每个进程处理的最大请求数(如1000),达到上限后自动重启,防止内存泄漏(即使应用无泄漏,也能定期回收内存)。mod_cache和mod_disk_cache缓存静态文件(如图片、CSS、JS),减少对后端的请求:LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_disk_cache.so
CacheEnable disk / # 缓存根目录下的所有内容
CacheRoot "/var/cache/apache2" # 缓存目录(需提前创建:sudo mkdir -p /var/cache/apache2)
CacheDirLevels 2 # 缓存目录层级
CacheDirLength 1 # 目录名长度
mod_expires和mod_headers设置静态资源的过期时间,让浏览器缓存,减少重复请求:<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "max-age=86400, public" # 缓存1天
</IfModule>
.htaccess文件会让Apache在每个目录中查找配置,增加额外的I/O和处理开销。在虚拟主机配置中禁用:
<Directory /var/www/html>
AllowOverride None # 禁用.htaccess
Require all granted
</Directory>
注意:禁用前需将.htaccess中的配置迁移到主配置文件中。
ExtendedStatus Off(/etc/apache2/apache2.conf),减少状态信息的收集开销。/dev/sdb1),避免单磁盘I/O瓶颈:ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
可通过符号链接将日志目录指向其他磁盘(如sudo ln -s /mnt/log/apache2 /var/log/apache2)。htop(sudo apt install htop)或top命令查看Apache进程的内存占用(按M键按内存排序)。<Location "/server-status">
SetHandler server-status
Require ip 127.0.0.1 # 仅允许本地访问
</Location>
访问http://服务器IP/server-status查看状态(需开启mod_status模块:sudo a2enmod status)。ab(Apache Benchmark)模拟并发请求,测试配置调整后的性能:ab -n 1000 -c 100 http://localhost/ # 1000个请求,100个并发
根据测试结果进一步调整MaxRequestWorkers、KeepAliveTimeout等参数。