Nginx + PHP-FPM Randomly Gives 502

1.4k views Asked by At

My site is working fine with Nginx + PHP-FPM but randomly it gives 502 error. Environment Details

OS - CetnOS 6
Nginx
PHP-FPM (php 5.4)
APC (Code Cache APC 3.1.13  beta)
Memcache (data cache)

In php-fpm

pm.max_children = 200
pm.start_servers = 40
pm.min_spare_servers = 30
pm.max_spare_servers = 50
pm.max_requests = 500

Also i am using TCP connection not socket.

If any body has any input please update me.

Thanks

1

There are 1 answers

3
Obscure Geek On

Firstly reduce pm.max_children = 200 to pm.max_children = 50.

You will have to firstly increase the file limit of the system thereby allowing nginx and php-fpm to open a larger number of files. File limit has to be increased as in linux everything in the end is a file. So the more connections you open the more number of files will be required. In ubuntu the file limit configuration are done in /etc/security/limits.conf. You will need to locate this for CentOS.

Then try to increase the internal port range which can be used by php-fpm. Along with this tcp ports are generally associated with a timeout value before they are reused, reduce this timeout so that more ports are freed when their job is done.

Find detailed info here.

Addition:

In case if the error still persists try increasing the number of php-fpm worker processes to 100. Although it is not recommended to set the value so high as they consume addition memory.

pm.max_children = 100
pm.start_servers = 90
pm.min_spare_servers = 70
pm.max_spare_servers = 100

You can try out various values to get the optimum suited for your purpose.

The basic reason for a 502 is when nginx cannot forward or fails to forward the request to php-fpm. Increasing the number of php-fpm worker processes can be one of the way, thereby giving nginx more processes to forward the requests to.