upstream closed prematurely nginx

How to Fix NGINX : Upstream Closed Prematurely Error

While using NGINX as a reverse proxy server, you may get “Upstream Closed Prematurely” error message occasionally. It happens because your upstream web server closes connection due to timeout. Any error message which mentions “upstream” deals with your upstream (backend) web server. In this article, we will look at how to fix Upstream Closed Prematurely error message in NGINX.


How to Fix NGINX : Upstream Closed Prematurely Error

Here are the steps to fix NGINX: Upstream Closed Prematurely error.


1. Open NGINX configuration file

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf


2. Increase Proxy Timeout

Add these following lines to increase proxy timeout for upstream server.

proxy_read_timeout 300s;     
proxy_connect_timeout 75s;
proxy_send_timeout 300s;

The above code increases the read & send timeout values to 300 seconds, and connection timeout to 75 seconds. According to NGINX docs, connection timeout cannot exceed 75 seconds.

Depending on your requirement, place the above code in http, server or location block. If you get this error for all websites hosted on your server, place it in http block.

http {
   ...
   proxy_read_timeout 300s;     
   proxy_connect_timeout 75s;
   proxy_send_timeout 300s;
   ...
}

If you face this error in one of your websites, but on all its URLs, then place the code in server block for that website.

https {
...
   server {
      ...
      proxy_read_timeout 300s;     
      proxy_connect_timeout 75s;
      proxy_send_timeout 300s;
      ...
   }
}

If you get this error on only specific URLs such as /upload then place the 3 lines in location block for that URL.

location /upload {
   ...
   proxy_read_timeout 300s;     
   proxy_connect_timeout 75s;
   proxy_send_timeout 300s;
   ...
}


3. Restart NGINX

Finally, run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

In this article, we have seen different ways to increase the request timeout values to fix “upstream closed prematurely” error. Depending on your requirement, place the code to increase timeout values in appropriate block. If it still does not solve your problem, then you need to look at the configuration of your upstream server.

Also read :

How to Serve Static Files from Different Folder in NGINX
How to Pass Parameters to Shell Script Functions
How to Retrieve POST Request Data in Django
How to Return Value in Shell Script
How to Force NGINX to Serve New Static Files