Production Server for a Django App
Nginx Unit as WSGI Server for a Django Application
Why Nginx Unit?
Unlike traditional WSGI servers like Gunicorn or uWSGI, Nginx Unit can be configured dynamically via a REST API. Reloading the server process for configuration changes is eliminated. Unit is lightweight, extremely fast, and processes static files efficiently in parallel with the Django Python code.
1. Installation
Install Nginx Unit and the required Python module on your Ubuntu/Debian server:
sudo apt update
sudo apt install unit unit-dev unit-python3
2. Create JSON configuration
Unit does not use classic configuration files, but a JSON payload. Create a file named `config.json` and adjust the paths to your Django project:
```json
{
"listeners": {
"*:8000": {
"pass": "applications/django"
}
},
"applications": {
"django": {
"type": "python 3",
"path": "/var/www/myproject/",
"module": "myproject.wsgi",
"environment": {
"DJANGO_SETTINGS_MODULE": "myproject.settings"
}
}
}
}
```
3. Apply configuration
Send the JSON configuration via curl to the Unit-Control socket. This applies the settings immediately, without restarting the service.
sudo curl -X PUT --data-binary @config.json --unix-socket /var/run/control.unit.sock http://localhost/config/
Your Django application is now running and accessible via port 8000. You can dynamically scale worker processes via the same API by adjusting the JSON and resending it!