Troubleshooting
#django
#nginx
#gunicorn
#deployment

Fix Django 502 Bad Gateway (Nginx + Gunicorn) – Step-by-Step Guide

If you're seeing a 502 Bad Gateway error when deploying Django with Nginx and Gunicorn, it usually means:

Nginx cannot connect to your Django application (Gunicorn)

This guide walks you through exactly how to diagnose and fix it, step by step.

⚡ Quick Fix (Try This First)

Run:

sudo systemctl status gunicorn
sudo systemctl restart gunicorn
sudo systemctl restart nginx

Then reload your site.

👉 If it works, Gunicorn likely crashed or wasn’t running.

If not, continue below.

🧠 What a 502 Bad Gateway Means

In this setup:

  • Nginx = web server
  • Gunicorn = application server
  • Django = your app

A 502 error means:

Nginx tried to forward a request → but Gunicorn didn’t respond

🧪 Step-by-Step Diagnosis

Follow these steps in order. Don’t skip ahead.

1. Check if Gunicorn is running

sudo systemctl status gunicorn

Expected:

active (running)

If NOT running:

Start it:

sudo systemctl start gunicorn

Then retry your site.

2. Check Gunicorn logs

journalctl -u gunicorn --no-pager -n 50

Look for:

  • Python errors
  • Import issues
  • Missing dependencies

3. Check Gunicorn socket or port

If using a socket:

ls /var/www/myproject/

You should see:

gunicorn.sock

If missing:

Gunicorn failed to start properly → check logs again.

4. Test Gunicorn directly

curl http://127.0.0.1:8000

OR (if using socket, skip this)

If this fails: Problem is in Django or Gunicorn (not Nginx)

5. Check Nginx configuration

sudo nginx -t

Expected:

syntax is ok
test is successful

6. Restart Nginx

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

7. Check Nginx error logs

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

🔥 Common Causes (and Fixes)

🔴 Gunicorn is not running

Fix:

sudo systemctl start gunicorn
sudo systemctl enable gunicorn

🔴 Wrong socket path

Your Nginx config must match Gunicorn exactly:

Nginx:

proxy_pass http://unix:/var/www/myproject/gunicorn.sock;

Gunicorn:

--bind unix:/var/www/myproject/gunicorn.sock

🔴 Gunicorn crashed on startup

Check:

journalctl -u gunicorn

Common causes:

  • Missing packages
  • Django errors
  • Wrong settings module

🔴 Nginx cannot access socket

Fix permissions and ensure:

  • Same user/group
  • Correct file ownership

🧠 Debugging Tips

Check Gunicorn logs:

journalctl -u gunicorn

Check Nginx logs:

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

Restart everything cleanly:

sudo systemctl restart gunicorn
sudo systemctl restart nginx

✅ Quick Fix Checklist

2026 · DJANGO DEPLOYMENT
Deploy Django with Confidence