When a site suddenly returns 502 or 504, visitors just see an error line. Both almost always live "between the reverse proxy (like Nginx) and the backend app". This guide helps you pinpoint it fast.

1. 502 vs 504

  • 502 Bad Gateway: when Nginx forwards to the backend, the backend doesn't respond, crashed, or is unreachable.
  • 504 Gateway Timeout: the backend responds but too slowly, beyond the wait limit.

2. Most Common Causes

  • The backend (Node / PHP-FPM / Python, etc.) crashed or never started.
  • Nginx's proxy_pass port/address is wrong, or the backend changed ports.
  • Slow backend (slow queries, infinite loops, external API timeouts) → 504.
  • Memory exhausted and the process killed by the system OOM killer.

3. Troubleshooting Steps

  • Is the backend up? Use pm2 list / systemctl status SERVICE to confirm it's running.
  • Check the port: ss -lntp to see if the backend listens on the port Nginx forwards to.
  • Read the Nginx error log: tail -f /var/log/nginx/error.log — 502/504 states whether it's connect refused or timeout.
  • Hit the backend locally: curl http://127.0.0.1:PORT — if it works the issue is Nginx config; if not, the backend itself is broken.

4. Matching Fixes

  • Backend down → restart the process and check its logs for the crash cause.
  • Wrong port → fix Nginx's proxy_pass, then nginx -t and reload.
  • 504 slowness → optimize the slow query/API, or raise proxy_read_timeout (a band-aid).
  • OOM → add swap or upgrade RAM (see the "Out of Memory (OOM)" article in the Help Center).