部署Django应用至DigitalOcean遇502 Bad Gateway,求排查方法
Hey there, 502 Bad Gateway errors can be tricky when you're new to deployment, but the good news is we can dig into logs to figure out exactly what's going wrong. Let's walk through the key places to check step by step:
Since 502 means Nginx can't communicate with your Django app server (Gunicorn, in this DigitalOcean 1-click setup), the Nginx logs will tell you why the connection failed. Run this command to view the latest logs in real-time:
sudo tail -f /var/log/nginx/error.log
Look for critical messages like:
- Connection refused: Gunicorn isn't running or is listening on the wrong port/socket
- Permission denied: Nginx doesn't have access to the Gunicorn socket file
- No such file or directory: The socket path in your Nginx config is incorrect
DigitalOcean's Django 1-click app uses systemd to manage Gunicorn, so you can view its detailed logs with:
sudo journalctl -u gunicorn --follow
This will show you exactly what's happening when Gunicorn tries to start your app. Common issues here include:
- Missing Python dependencies (you might have forgotten to install your
requirements.txton the droplet) - Incorrect path to your Django project or WSGI module
- Database connection errors (wrong credentials, or the database service isn't running)
- Syntax errors in your code that didn't show up locally (maybe a Python version mismatch?)
A quick check to confirm the Gunicorn service is up:
sudo systemctl status gunicorn
If it says failed or inactive, that's a clear red flag. You can try restarting it with:
sudo systemctl restart gunicorn
If the restart fails, the logs from step 2 will tell you exactly why.
If server logs aren't giving you enough context, you can temporarily enable Django's debug mode to see a detailed error page in your browser. Important: Never leave debug mode enabled in production—it exposes sensitive app data!
- Edit your Django project's
settings.pyfile:- Set
DEBUG = True - Add your droplet's public IP to
ALLOWED_HOSTS, likeALLOWED_HOSTS = ['your-droplet-public-ip']
- Set
- Restart Gunicorn to apply changes:
sudo systemctl restart gunicorn
Now when you visit your app, you'll see a full Django traceback if there's an error in your code or configuration.
Since you copied the app from your local machine, make sure you've installed all required packages on the droplet. The 1-click setup uses a virtual environment at /home/django/venv—activate it and install your requirements:
source /home/django/venv/bin/activate pip install -r /path/to/your/project/requirements.txt
Don't forget to restart Gunicorn after installing new packages!
Once you spot the specific error in the logs or debug page, fixing it should be straightforward.
内容的提问来源于stack exchange,提问作者Lorenzo Liguori

