Switching from Unix Sockets to TCP/IP in Nginx

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

Excellent article:

PHP-FPM: Socket vs TCP/IP and sysctl tweaking
In our entire WordPress-Nginx series we have used sockets for FPM (in between Nginx & PHP).

Sockets are slightly faster as compared to TCP/IP connection. But they are less scalable by default.

If you start getting errors like:

connect() to unix:/var/run/php5-fpm.sock failed or **apr_socket_recv: Connection reset by peer (104)**(as faced ovidiu here)

Then it means you need to either switch to TCP/IP or tweak with linux-system parameter so that your OS can handle large number of connections.

Using TCP/IP for FPM

Open PHP-FPM pool config file: vim /etc/php5/fpm/pool.d/www.conf

Replace line: listen = /var/run/php5-fpm.sock

by line: listen =

Next, open Nginx virtual-host config file(s).

Look for line: fastcgi_pass unix:/var/run/php5-fpm.sock;

Replace it with: fastcgi_pass;

Important: Reload php-fpm and nginx so that changes can take effect.

Sysctl.conf Tweaking

Important: I am not familiar with sysctl parameters in-depth, so please be careful while doing this.

Open file /etc/sysctl.d/custom.conf

And add following lines:

fs.file-max = 2097152
kernel.pid_max = 2097152
kernel.shmmax = 4294967296

net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.rmem_default = 1048576
net.core.wmem_default = 1048576
net.core.netdev_max_backlog = 65536
net.core.somaxconn = 65536
net.core.optmem_max = 25165824

net.ipv4.tcp_rmem = 4096 1048576 16777216
net.ipv4.tcp_wmem = 4096 1048576 16777216
net.ipv4.tcp_max_syn_backlog = 65536

vm.max_map_count = 262144
Above config is for a server with 32-GB RAM and 32-Core processors. You may need to change some values depending on your hardware configuration.

Once you save your changes, just run following command for new system settings to take effect.

sysctl -p

Tweaking FPM config:

You may also need to tweak PHP-FPM config to match new sysctl.conf settings.

Open PHP-FPM pool config file: vim /etc/php5/fpm/pool.d/www.conf

Look for line => ;listen.backlog = 128

Change it to => listen.backlog = 65536

Restart php5-fpm service.

Important: Please note that, even if you switch to TCP/IP methods, at some point, you may still need to tweak sysctl.conf to increase TCP/IP connection limit. Above sysctl.conf config already have entries for TCP/IP.