Skip to content
statance
MenuClose
← All troubleshooting guides

nginx returns 502 Bad Gateway

Linux

A 502 means nginx could not get a valid response from the upstream application. Read /var/log/nginx/error.log — it names the cause, typically “connect() failed (111: Connection refused)” when the app is not running or not listening where nginx expects, or “upstream prematurely closed connection” when the app crashed mid-request.

Symptoms

  • Browser shows “502 Bad Gateway nginx”
  • Errors start after a deploy, reboot or under load
  • Static files work but dynamic pages fail

How to diagnose it

  1. Read the nginx error log

    The message identifies which upstream failed and why.

    sudo tail -50 /var/log/nginx/error.log
  2. Check the upstream service

    Is PHP-FPM, Node, Gunicorn or the container running?

    systemctl status php8.3-fpm # adjust to your service systemctl --failed
  3. Check it listens where nginx points

    Compare with proxy_pass or fastcgi_pass in your site config.

    sudo ss -ltnp | grep -E "8000|3000|9000" ls -l /run/php/
  4. Request the upstream directly

    Bypasses nginx to see whether the app itself works.

    curl -i http://127.0.0.1:8000/

Common causes and fixes

Application not running

Start it and read its own logs for why it stopped.

sudo systemctl restart APP journalctl -u APP -n 50

Wrong socket path or port

Make fastcgi_pass or proxy_pass match the actual listen address (e.g. PHP version changed the socket name).

Socket permission denied

Error log shows “(13: Permission denied)”. Set listen.owner/listen.group in the PHP-FPM pool to the nginx user.

Workers exhausted or crashing under load

Raise pm.max_children (PHP-FPM) or worker counts within memory limits; check for OOM kills.

SELinux blocking the connection (RHEL family)

Allow nginx to make network connections.

sudo setsebool -P httpd_can_network_connect 1

Prevent it happening again

  • Add an HTTP check with expected status 200 so a 502 alerts within one check interval.
  • Alert on SERVICES_failed to catch the upstream service failing.
  • Use a keyword check on a dynamic page so errors behind a cached homepage are caught.

Set it up: Website uptime monitoring · Keyword monitoring monitoring.

FAQ

What is the difference between 502 and 504?

502 means the upstream returned an invalid response or refused the connection. 504 means it did not respond within proxy_read_timeout.

Is a 502 error my fault or the server’s?

It is a server-side problem between nginx and the application; visitors cannot fix it.

Related guides

Get alerted before this becomes an outage.

Install the agent in one line. Statance watches CPU, memory, disk and services, and its AI assistant helps find the cause.