When deploying a Django (or any Python) app using Gunicorn behind Nginx, you might encounter a 502 Bad Gateway error. This article walks you through resolving it, especially if the root cause is:
PermissionError: [Errno 13] Permission denied: '/path/to/app.sock'
🔍 Root Cause
This error occurs when Gunicorn lacks permission to create or connect to the Unix socket file specified in your systemd service file.
This results in:
- Gunicorn crashing
- Nginx failing to connect to the backend
- A 502 Bad Gateway error in the browser
✅ Solution Steps
1. Fix Socket File Permissions
Ensure the user running Gunicorn (e.g., www-data, ubuntu, or a custom deployment user like resquser) has the right permissions to access and create the socket file.
Run the following:
sudo chown -R www-data:www-data /var/www/your_project_directory
sudo chmod -R 755 /var/www/your_project_directory
Replace www-data with the actual user specified in your systemd service file under the [Service] section:
User=www-data
Group=www-data
2. Remove Any Existing Socket File
If a .sock file was previously created by another user or process, delete it:
sudo rm /var/www/your_project_directory/your_app.sock
3. Restart Gunicorn
sudo systemctl daemon-reexec
sudo systemctl restart your_app.service
Verify it’s running without errors:
sudo systemctl status your_app.service
4. (Optional) Add Nginx to Correct Group
If Nginx needs access to the socket file (and the group owner differs from nginx), you can add Nginx to that group:
sudo usermod -aG www-data nginx
Then restart Nginx:
sudo systemctl restart nginx
5. Verify Gunicorn Socket Works
Test Gunicorn’s socket manually:
curl --unix-socket /var/www/your_project_directory/your_app.sock http://localhost
If you get an HTTP response, Gunicorn is now functioning correctly.
🧼 Pro Tips
- Avoid placing
.sockfiles in/tmp/or root-owned directories without adjusting permissions. - Always define a clean
UserandGroupin yoursystemdservice file for predictable file access. - Use
journalctl -u your_app.service -n 50to debug failures.
📌 Summary
| Step | Action |
|---|---|
| 🧾 1 | Ensure directory and socket file permissions are correct |
| 🗑 2 | Delete leftover .sock file |
| 🔁 3 | Restart Gunicorn service |
| 🔐 4 | Add Nginx to appropriate group if needed |
| ✅ 5 | Test socket with curl
|
With these steps, your Gunicorn and Nginx setup should serve your Django app without throwing 502 Bad Gateway errors.
Let me know if you will get stuck
Top comments (0)