← All articles

How to fix Nginx 502 Bad Gateway on Ubuntu

A 502 means Nginx could not reach your app upstream. Check if the backend is running, review error logs, and verify socket or port config—here is the fix order.

Nginx 502 Bad Gateway means your reverse proxy is up but the app behind it is not responding. Fix the upstream first—almost never Nginx itself.

Fix order (Ubuntu / Debian)

  1. Check the backend service

    sudo systemctl status nginx
    sudo systemctl status your-app   # e.g. php8.2-fpm, gunicorn, pm2-managed unit

    If inactive or failed, read the status output and journal: sudo journalctl -u your-app -n 50 --no-pager

  2. Read Nginx error log

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

    Look for connect() failed, upstream prematurely closed, or wrong socket paths.

  3. Confirm upstream address Open your site config (/etc/nginx/sites-enabled/) and verify proxy_pass or fastcgi_pass matches where the app actually listens (127.0.0.1:3000, unix socket, etc.).

  4. Test the upstream directly

    curl -I http://127.0.0.1:PORT/health

    If curl fails locally, Nginx will 502 every time.

  5. Restart in order

    sudo systemctl restart your-app
    sudo nginx -t && sudo systemctl reload nginx

Common causes

SymptomLikely cause
After deployApp crash, wrong port, missing env vars
Intermittent 502OOM kill, worker timeout, disk full
After rebootService not enabled: sudo systemctl enable your-app
PHP sitesphp-fpm down or wrong socket in fastcgi_pass

Safe checks before restart

  • df -h — disk full prevents writes and crashes apps
  • free -h — OOM kills backends silently
  • Recent deploy logs — did the release change the listen port?

When an AI DevOps Copilot helps

If you are not comfortable reading logs under pressure, Ohuriya AI is an AI DevOps Copilot that connects to your VPS, proposes diagnostic commands, and waits for your approval before anything runs. Describe “502 after deploy” and paste log snippets—connect in ~30 seconds.

More: high CPU on a VPS · disk full

Quick answers

What causes Nginx 502 Bad Gateway?

Usually the upstream app (Node, PHP-FPM, Gunicorn, etc.) is down, crashed, or listening on the wrong port/socket. Less often: firewall, SELinux, or a full disk preventing the backend from starting.

Where do I look first for a 502?

Run sudo systemctl status on your app service, then sudo tail -50 /var/log/nginx/error.log. The error log often names the upstream that failed.

Can AI help fix a 502 on my VPS?

Yes—describe the symptom and paste recent log lines. An AI DevOps Copilot like Ohuriya can propose diagnostic commands and wait for your approval before running them on your server.