I use AWS: ELB (classic) → EC2 (with Node.js)
Problem. Sometimes some requests return 502 Bad Gateway error. In Nginx error log a I see "upstream prematurely closed connection while reading response header from upstream" error.
Not timeout issue. This error happens the same second this request in handled by Node.js application. So it is not a timeout issue because of the long response.
Client doesn't break connection. I tried to make request programaticly (to be sure that client doesn't break connection). And sometimes got the same error, while test client-application got response with 502 error from Ngnix.
Who can close connection and why? How to fix this issue?
Who can close the connection and why? That Nginx error indicates that the connection was closed by your upstream server (ie "node.js"). You can resolve this by setting a higher timeout value for the proxy:
location / { proxy_read_timeout 300s; proxy_connect_timeout 75s; proxy_pass http://localhost:3000; }
Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html