Fine-Tune PHP-FPM and Apache for Optimal Performance

If you have a high-spec server for a web app, but the server isn’t optimized to handle large traffic, you may experience timeouts when loading the app. This issue is often due to the web server not being properly configured for heavy traffic. In this article, we will explore how to fine-tune PHP-FPM and Apache for optimal performance.

Let’s start with Apache. The server OS is Ubuntu.

Apache

It depends on which Apache configuration you are using. If it is plain PHP, it will most likely be mpm_prefork; if it is PHP-FPM, then it will be mpm_event.

PHP

If you are using plain PHP, the file you need to edit is /etc/apache2/mods-available/mpm_prefork.conf.

vim /etc/apache2/mods-available/mpm_prefork.conf

Now, look for the following options and change them as needed. Start with the settings below and gradually increase them if your app demands it and your server specifications allow.

<IfModule mpm_prefork_module>
       StartServers              4
       MinSpareServers          20
       MaxSpareServers          40
       MaxRequestWorkers       200
       MaxConnectionsPerChild 4500
</IfModule>

Save and restart Apache.

PHP-FPM

Apache mpm_event works with PHP-FPM. We will update the configuration for the event module.

vim /etc/apache2/mods-available/mpm_event.conf

Similar to PHP, start with the following settings and increase them as needed.

<IfModule mpm_event_module>
       StartServers             8
       MinSpareThreads          25
       MaxSpareThreads          75
       ThreadLimit              64
       ThreadsPerChild          50
       MaxRequestWorkers        500
       MaxConnectionsPerChild   4500
</IfModule>

Save and restart Apache.

PHP-FPM

I assume, and it is most likely, that you are using PHP-FPM instead of PHP. In this case, we will need to make some changes to the PHP-FPM configuration as well to manage its processes, since PHP-FPM has separate processes that are not dependent on Apache.

If you have multiple versions of PHP, you will find them in the /etc/php folder.

In my case, it’s PHP 8.1. Let’s update it.

cd /etc/php/8.1/fpm/pool.d

vim www.conf

Look for the following options and update them accordingly.

pm = dynamic
pm.max_children = 12
pm.start_servers = 6
pm.min_spare_servers = 4
pm.max_spare_servers = 8
pm.max_requests = 0

You can increase or change them anytime you want.

Restart PHP-FPM afterward.

systemctl restart php8.1-fpm

This should handle the heavy lifting for your web app, and you may see improved performance.