Apache2优化Ubuntu服务器性能的完整指南
sudo apt update && sudo apt upgrade,确保Ubuntu内核、Apache2及依赖模块为最新版本,获取性能改进与安全补丁。apachectl -M查看已加载模块,通过sudo a2dismod [模块名](如mod_status、mod_autoindex)禁用未使用的模块,减少内存与CPU占用。sudo a2enmod deflate(压缩)、expires(缓存过期)、rewrite(URL重写)、cache(缓存),并通过sudo systemctl restart apache2生效。Apache2的MPM(多路复用模块)决定了进程/线程的管理方式,需根据服务器用途选择:
/etc/apache2/mods-enabled/mpm_prefork.conf,调整参数:<IfModule mpm_prefork_module> StartServers 5 # 启动时的进程数 MinSpareServers 5 # 最小空闲进程数 MaxSpareServers 10 # 最大空闲进程数 MaxRequestWorkers 150 # 最大并发请求数(根据内存计算:总内存/单个进程内存) MaxConnectionsPerChild 1000 # 每个进程处理1000个请求后重启(防止内存泄漏) </IfModule> /etc/apache2/mods-enabled/mpm_worker.conf,调整参数:<IfModule mpm_worker_module> StartServers 2 # 启动时的进程数 MinSpareThreads 25 # 最小空闲线程数 MaxSpareThreads 75 # 最大空闲线程数 ThreadLimit 64 # 线程数上限 ThreadsPerChild 25 # 每个子进程的线程数 MaxRequestWorkers 150 # 最大并发请求数 MaxConnectionsPerChild 0 # 0表示不限制(或设为较大值) </IfModule> 注:
MaxRequestWorkers需根据服务器内存计算(如1GB内存的服务器,每个Apache进程约占用100MB,则MaxRequestWorkers可设为10-15)。
/etc/apache2/mods-enabled/deflate.conf,添加压缩类型:<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json </IfModule> 压缩可减少传输数据量(通常减少50%-70%),提升页面加载速度。/etc/apache2/mods-enabled/expires.conf,设置静态资源过期时间:<IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" </IfModule> 缓存可减少重复请求,降低服务器负载。/etc/apache2/apache2.conf,开启持久连接:KeepAlive On MaxKeepAliveRequests 100 # 每个连接最大请求数(避免单个连接占用过久) KeepAliveTimeout 5 # 空闲连接超时时间(秒) KeepAlive可减少TCP握手开销(约60%的延迟降低),但需平衡MaxKeepAliveRequests与KeepAliveTimeout,避免过多空闲连接占用内存。/etc/apache2/apache2.conf,缩短请求超时时间:Timeout 30 # 默认120秒,缩短至30秒(减少长时间占用连接) top/htop查看Apache进程的内存/CPU占用;apachetop(sudo apt install apachetop)实时监控请求速率与响应时间;vmstat 1查看系统级资源使用(如CPU、内存、I/O)。/etc/apache2/sites-available/[站点配置],将CustomLog/ErrorLog设为/dev/null(仅用于生产环境,调试时开启);logrotate自动清理旧日志:sudo logrotate -f /etc/logrotate.conf(避免日志文件过大占用磁盘空间)。sudo systemctl restart apache2),释放内存碎片与缓存,保持服务稳定。MaxRequestWorkers;/etc/sysctl.conf,优化网络与内存设置:fs.file-max = 65536 # 最大文件描述符数 net.ipv4.tcp_tw_reuse = 1 # 重用TIME_WAIT连接 vm.swappiness = 10 # 减少交换空间使用(优先使用内存) 运行sudo sysctl -p使配置生效。通过以上步骤,可显著提升Ubuntu服务器上Apache2的性能,适用于大多数中小型网站与Web应用。优化过程中需根据实际负载(如并发数、内存占用)调整参数,避免过度配置导致资源浪费。