AutoDeploy
← All guides

Nginx

HIGHOtherINTERMEDIATE

Nginx 502 Bad Gateway Error

Nginx returns 502 when it can't get a valid response from the upstream application server.

Est. Time

20 minutes

Version

v1.0.0

Updated

7/26/2026

Author

AutoDeploy Team

Tags

#nginx#proxy#502#upstream

Prerequisites

  • Nginx installed
  • Access to nginx error logs

Setup Guide

Download guide

Nginx 502 Bad Gateway Error

Problem

Nginx returns 502 Bad Gateway when acting as a reverse proxy in front of an application server.

Symptoms

  • Browser shows 502 Bad Gateway
  • nginx error.log shows connect() failed or upstream prematurely closed connection
  • Intermittent — works sometimes, fails under load

Root Cause

Nginx couldn't get a valid response from the upstream application server — the upstream process crashed or isn't running, it's refusing the connection (wrong port/host), it's too slow and hit Nginx's proxy timeout, or it sent a malformed response.

Solution

1. Check nginx's error log for the specific upstream failure

sudo tail -f /var/log/nginx/error.log

2. Confirm the upstream app is actually running and listening on the expected port

sudo ss -tlnp | grep <port>

3. Verify the proxy_pass target matches where the app actually listens

location / {
    proxy_pass http://127.0.0.1:3000;
}

4. If the app is just slow, raise proxy timeouts rather than assuming it's broken

proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;

5. Check the app's own logs for crashes around the same timestamps

6. If using Docker, confirm both containers are on the same network and the hostname resolves

docker exec <nginx-container> getent hosts <app-service-name>

7. Restart the upstream service and watch whether 502s stop

sudo systemctl restart <app-service>

Prevention

  • Add a health check + auto-restart to the upstream service
  • Set proxy timeouts based on the app's real response times, not defaults
  • Monitor upstream response times so a slowdown is caught before it becomes a 502
  • Run more than one upstream instance behind Nginx so one crash doesn't take down the whole site

References

Last updated on 7/26/2026 · Part of the AutoDeploy DevOps Documentation library