How to Fix “nginx 504 gateway time-out”?

The Nginx is an open-source HTTP server which is used to optimize (high-performance and fast) the website. While using Nginx, the website/proxy sometimes takes more time to read and send the response data. The time taken by that website exceeds the timeout limit resulting in Nginx, and thus, the error “nginx 504 gateway time-out” occurs.

This guide will enlist the reasons and the solutions to fix the “nginx 504 gateway time-out” error. 

Reason: Nginx Timeout is Less

The Nginx takes time while connect to the database, fetch (read) data from there, and send back data to the user.

The main cause of the nginx gateway timeout error is that the website/proxy takes more time to read and send the response data to the Nginx than its wait time.

Solution: Increase the Gateway Timeout for Nginx

This error can be fixed by Increasing the proxy_read_timeout value. The server is taking too long to read the response from the upstream server. To remove this error, we need to increase the proxy_read_timeout value in your Nginx configuration by following the below easy steps.

Step 1: Create a Backup Default Configuration File (Optional)

To create a backup file named “/etc/nginx/nginx.conf.backup” use the below copy command:

$ sudo cp -p /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

Step 2: Increase the Gateway Timeout in Nginx Configuration File

We need to increase the time-out settings in the default Nginx configuration file “/etc/nginx/nginx.conf”. First, open the Nginx configuration file by executing this command:

$ sudo nano /etc/nginx/nginx.conf

Note: The default time-out settings for most servers is 60 seconds, including Plesk. We need to increase the proxy and FastCGI (Interface to connect the website to servers) default time-out more than the time taken for reading and sending the data to servers.

Now, add the following code at the end of the http section of the Nginx config file to set the default time-out to 4 minutes (240 seconds):

proxy_connect_timeout 240s;
proxy_send_timeout 240s;
proxy_read_timeout 240s;
fastcgi_send_timeout 240s;
fastcgi_read_timeout 240s

Press the “Ctrl + O” to save and “Ctrl + X” to exit the file.

Step 3: Restart the Nginx Server

Restart the Nginx server to save the changes in the configuration file by running the below-stated command:

$ sudo systemctl restart nginx

The Nginx server is restarted, and the nginx gateway time-out error is resolved.

Conclusion

The Nginx 504 gateway timeout error can occur when the interface connection, read, and send time is more than the default wait time of the Nginx response. This error can be resolved by increasing the proxy and FastCGI interface connect, read and send times to more than the default wait (time-out) time of the Nginx server.