How to Fix Nginx 504 Gateway Time-out

          When setting up an LNMP stack on CentOS, I typically use the same configuration files without any issues. However, recently after installing the same environment on a VPS, the site became extremely slow with just over 10 users online. Several times, requests hit the maximum script timeout of 300 seconds set in Nginx, causing Nginx to send a 504 Gateway Time-out error to the client browser. After analysis, I modified several configuration settings and finally resolved the problem.

Based on the error code, it was clear the issue was not with Nginx itself, but rather with requests submitted to php-fpm not receiving proper feedback. Normally, when handling dynamic requests, Nginx forwards the request to php-fpm, which then assigns a php-cgi process to handle it. The results are then returned in sequence, with Nginx delivering the final output to the client browser. However, this VPS is running a pure PHP application, meaning virtually all user requests are PHP requests. Some requests take a long time to process, causing all php-cgi processes to be fully occupied. Meanwhile, the php-fpm configuration was set to spawn only 10 php-cgi process groups. With slightly higher online traffic, requests could not be processed properly, leading to errors.

After roughly analyzing the cause, making fixes was relatively straightforward. First, I adjusted several settings in the php-fpm configuration:

Changed max_children from 10 to 30, ensuring an ample supply of php-cgi processes for handling requests;

Changed request_terminate_timeout from 0s to 60s, setting the script processing timeout for php-cgi processes to 60 seconds, which prevents processes from hanging and improves utilization efficiency.

Next, I modified several Nginx configuration settings to reduce FastCGI request overhead while keeping buffers stable:

  fastcgi_buffers changed from 4 64k to 2 256k;
  fastcgi_buffer_size changed from 64k to 128K;
  fastcgi_busy_buffers_size changed from 128K to 256K;
  fastcgi_temp_file_write_size changed from 128K to 256K.

After reloading both the php-fpm and Nginx configurations and testing again, no 504 Gateway Time-out errors have occurred for two weeks now. I’d say it achieved the desired result.

Additionally, the default static processing mode of php-fpm can cause php-cgi processes to occupy memory long-term without releasing it, which is another factor contributing to Nginx errors. Therefore, you can switch the php-fpm processing mode to apache-like.

<value name=”style”>apache-like</value>

Testing since the changes shows the above approach has been clearly effective, with not

Leave a Comment

Your email address will not be published.