Ever since my move to a VPS, one of the drawbacks is that mod_php uses a lot of memory since Apache has to load the PHP stuff every time a page loads. This can be solved by switching to PHP5-FPM and Fast CGI, which gives the performance of Mod_PHP without the high memory usage.
What is PHP5-FPM? It’s a separate process on FastCGI and separately from the web server. It’s commonly used with Nginx, but I decided against using that server since it would cause a configuration nightmare, especially since my .htaccess files only works with Apache.
To do this, do the following…
Add the respotories
Not necessary for Ubuntu 11.10 or later since PHP5-FPM is included in their repos
sudo aptitude install python-software-properties
sudo add-apt-repository ppa:brianmercer/php
Or the more up to date PPA (recommended)
sudo aptitude install python-software-properties
add-apt-repository ppa:l-mierzwa/lucid-php5
Update list
sudo aptitude -y update
Switch to mpm-worker
sudo apt-get install apache2-mpm-worker
To revert, do this command
sudo apt-get install libapache2-mod-php5 apache2-mpm-itk
Install PHP5-FPM
sudo aptitude -y install php5-fpm libapache2-mod-fastcgi
Enable the necessary modules
sudo a2enmod actions fastcgi alias
Create a new file called php5-fcgi.conf to /etc/apache2/conf.d and add this:
<IfModule mod_fastcgi.c>
Alias /php5.fcgi /home/<username to run Apache>/www/fastcgi/php5.fcgi
FastCGIExternalServer /home/<username to run Apache>/www/fastcgi/php5.fcgi -flush -host 127.0.0.1:9000
AddType application/x-httpd-fastphp5 .php
Action application/x-httpd-fastphp5 /php5.fcgi
<Directory “/home/<username to run Apache>/www/fastcgi/”>
Order deny,allow
Deny from all
<Files “php5.fcgi”>
Order allow,deny
Allow from all
</Files>
</Directory>
</IfModule>
In the directory you specified the fastcgi folder, create a folder with that name. If you don’t do this, you will receive 404 errors.
Edit the php5-fpm.conf in /etc/php5/fpm/ and adjust to these settings
For Ubuntu 11.10 or higher, edit the /etc/php5/fpm/pool.d/www.conf file
emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 0
pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 2
This will ensure lower memory usage if you are running a small or medium traffic site.
Change user and group run:
sudo nano /etc/php5/fpm/php5-fpm.conf
If you are running Apache off a different user, change the username to the one that you use to run the Apache process as shown bellow
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
user = chikorita157
group = www-data
Restart PHP5-fpm to apply the new settings
sudo service php5-fpm restart
View the PHPinfo page. If it shows FPM/FastCGI, you have successfully installed it.
Leave a Reply