症状:

服务器负载高或不稳定,可能导致响应缓慢、服务中断或资源耗尽。

故障排除步骤:

  1. 检查 Apache MPM 设置
    使用以下命令查看当前使用的 MPM 模式:

    bash apachectl -V | grep MPM

    如果输出显示 Server MPM: worker,则表示当前使用的是 Worker MPM。

  2. 调整服务器进程和线程的数量
    根据服务器的硬件资源和负载需求,调整 Worker MPM 的关键参数。编辑 Apache 配置文件(通常是 /etc/httpd/conf/httpd.conf 或 /etc/apache2/apache2.conf),找到以下配置段:

    apache <IfModule mpm_worker_module> StartServers 2 MaxRequestWorkers 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxConnectionsPerChild 0 </IfModule>

    • StartServers:Apache 启动时创建的子进程数量。默认值为 2。
    • MaxRequestWorkers:同时处理的最大请求数。默认值为 150。
    • MinSpareThreads 和 MaxSpareThreads:分别表示最小和最大空闲线程数。
    • ThreadsPerChild:每个子进程的线程数量。默认值为 25。
    • MaxConnectionsPerChild:每个子进程在重启之前能处理的最大连接数。默认值为 0(不限制)。

    根据服务器的负载需求,可以适当调整这些参数。例如:

    apache StartServers 4 MaxRequestWorkers 200 MinSpareThreads 50 MaxSpareThreads 100 ThreadsPerChild 50 MaxConnectionsPerChild 10000

  3. 监控服务器资源
    使用工具(如 top、htop 或 vmstat)监控服务器的 CPU、内存和磁盘 I/O 使用情况。如果资源使用率过高,可能需要进一步调整 MPM 参数。

  4. 重启 Apache
    在调整配置后,重启 Apache 服务以使更改生效:

    bash systemctl restart httpd

    或:

    bash systemctl restart apache2

  5. 优化其他配置

    • 启用 KeepAlive:允许浏览器与服务器保持连接,减少重复握手的开销。在配置文件中添加以下内容:

      apache KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5

    • 启用缓存机制:使用 mod_cache 或 CDN 缓存静态资源,减轻服务器负载。

  6. 选择合适的 MPM 模式
    根据应用场景选择合适的 MPM 模式:

    • Worker MPM:适用于高并发场景,能够更好地利用多核处理器。
    • Event MPM:基于事件驱动,适合处理大量非阻塞请求。
    • Prefork MPM:适合运行不支持线程安全的模块。

通过以上步骤,可以优化 Apache 的 Worker/MPM 配置,降低服务器负载,提升性能和稳定性。