
A Fix for the Nginx 502 Bad Gateway Error
When Nginx is under high load, uploading images or executing long-running scripts often triggers the 502 Bad
Gateway error repeatedly. Searching online, most results point to a well-known solution by a certain Master Zhang that involves increasing the FastCGI request timeout values. His solution adds the following to nginx.conf:
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300; /
fastcgi_read_timeout 300;
However, I ran into this issue in practice. Even after setting these values to 500, the error still occurred, just less frequently than when I had them set to 120.
Later, I discovered this mainly happened during certain POST requests or database operations. It never occurred with static pages.
I repeatedly investigated the problem and debugged, even increasing the number of CGI processes. // 内容来自技术世界www.js4j.com 专业技术//
Pushing it to 256 and beyond can make things very slow and consume a lot of memory.
There is another setting in php-fpm.conf that I might have overlooked initially but accidentally changed at some point.
request_terminate_timeout
This value is max_execution_time, which is the execution time limit for a FastCGI script.
0s means disabled, allowing unlimited execution time. (I hadn’t checked carefully during installation and just changed a number.) I found that the problem was solved, and even very long-running
scripts no longer produced errors.
When optimizing FastCGI, you can also adjust this value, say 5s. I finally discovered that the 502 error is actually not an Nginx issue.
Insufficient PHP-CGI processes, long PHP execution times, or a dead PHP-CGI process can all cause the 502 error.