July 06, 2017

PHP-FPM: Process Management

Learn how to manage how PHP-FPM creates and uses PHP processes to get the most out of your server.

Learn how to manage how PHP-FPM creates and uses PHP processes to get the most out of your server.I'm running Ubuntu 14.04 in this video:

# See the version used.
lsb_release -a

Nginx is configured to run PHP with PHP-FPM via the default configuration found at /etc/nginx/sites-available/default, with the PHP portions uncommented, so PHP requests are proxied to PHP-FPM.

The only php file used is index.php which simply contains <?php phpinfo();.

PHP-FPM

We can see the stock configuration of PHP-FPM process management at /etc/php5/pool.d/www.conf.

While we edit and save this configuration, we'll see how processes are created on the right half of the screen using htop.

Static Process Management

First we'll try static process management:

pm = static
pm.max_children = 5
sudo service php5-fpm restart

We'll see that there are 5 PHP-FPM processes running.

Test that by using ab to send web requests:

ab -n 1000 -c 10 http://localhost/index.php
ab -n 5000 -c 20 http://localhost/index.php

Then test using the pm.max_requests parameter, which kills and respawns processes after handling a certain number of requests. Edit /etc/php5/pool.d/www.conf:

# Uncomment this line if needed
pm.max_requests = 500

Then test that again to see if processes are killed and respawned.

sudo service php5-fpm restart
ab -n 5000 -c 20 http://localhost/index.php

We saw some processes died and then some processes were killed and then respawned!

Dynamic Process Management

Edit /etc/php5/pool.d/www.conf once again.

pm = dynamic

Now we can decide how many processes the server is allowed to spin up. Here's a generic formula:

Total Max Processes = (Total Ram - (Used Ram + Buffer)) / (Memory per php process)

This server is has about 3.5gb of ram. Let's say PHP uses about 30mb of ram per request.

We can start with: (1024*3.5) / 30 = 119.46. Let's just go with 100 max servers.

Note that I didn't take into account used ram and add in a buffer. That'd be need if the server did more, such as also hosted a database.

pm.max_children = 100 # The hard-limit total number of processes allowed
pm.start_servers = 20 # When php-fpm starts, have this many processes waiting for requests
pm.min_spare_servers = 10 # Number spare processes php-fpm will create
pm.max_spare_servers = 20 # Max number of spare (waiting for connections) processes allowed to be created
pm.process_idle_timeout = 10s;

Restart it:

sudo service php5-fpm restart

We'll use htop and ab to test this again. We can see we'll have 20 start servers available, waiting for requests.

Test it out some more with ab. We'll see processes killed and spawned as they reach the 500 limit, and we'll see the number of processes increase dramatically when we handle lots and lots of requests.

ab -n 10000 -c 200 http://localhost/index.php

All Topics