How to Fix 504 Gateway Timeout Error in NGINX


fix 504 gateway timeout error nginx

When your back end servers take a long time to process requests, NGINX is likely to give a “504: Gateway Timeout” error. It means your requests are taking tool long to run. It may be because there your web server is overloaded, running out of memory, or there is a software bug which causes your server to keep processing forever. Here’s how to fix 504 Gateway Timeout error in NGINX.

 

How to Fix 504 Gateway Timeout Error in NGINX

Here are the steps to fix 504 Gateway Timeout error in NGINX.

 

1. Free up Memory

Open a terminal session or SSH into your Linux system and run the following command to free up memory


$ free -h

 

2. Identify the resource consuming process

Run the top command to check the load on your processor. It will list the top processors that consume most resources. Identify and kill that process with “sudo kill -9 pid” where pid is the process id.

 

3. Configure Proxy timeout

If you have configured NGINX as a reverse proxy, then you need to configure its timeout so that it doesn’t time out too soon.


proxy_connect_timeout 600;
proxy_send_timeout 600;
Proxy_read_timeout 600;
Send_timeout 600;

In the above code, 600 means 600 seconds. Make sure to restart NGINX after you add the above code.


$ sudo systemctl restart nginx

 

4. Frozen Script

Sometimes, your script may freeze due to a bug. In such a case, search your NGINX logs to find which request is causing the issue


$ grep -i "504" /var/log/nginx/access.log

This will give you a list of requests that received 504 error response.

Similarly, look into your NGINX error log.


$ grep -i "504" /var/log/nginx/error.log

 

 

5. Issue with PHP-FPM

If you are using PHP/Apache behind NGINX, then you can use the slow-log feature of php-fpm to identify slow running scripts. Just add the following lines to your configuration file


sudo vi /etc/php-fpm.d/www.conf
slowlog = /var/log/php-fpm/www-slow.log
request_slowlog_timeout = 5s

Now any request that takes more than 5 seconds to run, will be logged.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!