PHP-FPM can provide an alternative to spawn-fcgi when setting up Lighttpd with PHP. It has several advantages over using spawn-fcgi, among them:
- It can dynamically scale and spawn new processes as needed.
- It can gracefully respawn PHP processes after a configuration change.
- It comes with an
init.dscript, so there is no need to write your own. - It can log slow PHP script execution (similar to MySQL’s slow query log).
Installation
PHP-FPM is available from the Ubuntu (since 12.04) and Debian repositories, so all you need to do is:
$ sudo apt-get install php5-fpm
Configuration
PHP-FPM works with process pools. Each pool spawns processes independently and has different configurations. This can be useful to separate the PHP processes of each user or major site on the server. PHP-FPM comes with a default pool configuration in /etc/php5/fpm/pool.d/www.conf. To create new pools, simply copy the default pool configuration and edit it. At a minimum, you will need to set the following:
- Pool name –
[www]. I name mine according to the user the pool serves. user– I set the user to the appropriate user, and leavegroupaswww-data.listen = /var/run/php.$pool.sock– Unix sockets have lower overhead than TCP sockets, so if both Lighttpd and PHP run on the same server, they are preferable.$poolwill be expanded to your pool name. Also, it is more secure to create the sockets in a directory that is not globally writable (such as/tmp/), so/var/runis a good choice.listen.ownershould match the PHP user, whilelisten.groupshould match the group Lighttpd runs in, so both have access to the socket.
If you copied www.conf to create a new configuration, you will need to rename it to something like www.conf.default in order to disable it.
In the Lighttpd configuration, you need to add the following to each vhost that uses PHP:
fastcgi.server = ( ".php" =>
((
"disable-time" => 0,
"socket" => "/var/run/php.pool.sock",
))
)
Here, pool in the socket configuration is replaced by the matching pool name in the PHP-FPM configuration. Overriding disable-time and setting it to 0 is suitable in the case where you have only one PHP backend and it’s local. In this scenario, attempting to connect to the backend is cheap, and if it gets disabled, no requests will get through anyway.
Useful Files
/etc/php5/fpm/pool.d– The PHP-FPM pool configuration directory./var/log/php5-fpm.log– The PHP-FPM error log. It will display errors and warnings notifying you whenpm.max_childrenhas been reached, when processes die unexpectedly, etc.