Serve a Django application using Gunicorn
Create systemd service file
1 |
vi /usr/lib/systemd/system/backend.service |
Add
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[Unit] Description=Gunicorn instance to serve Django Application After=network.target [Service] User=www-data Group=www-data Environment="APP=app" WorkingDirectory=/path/to/app/backend Environment="PATH=/path/to/app/backend/venv/bin" ExecStart=/path/to/app/backend/venv/bin/gunicorn -w 3 --timeout 120 --bind 0.0.0.0:8080 backend.wsgi [Install] WantedBy=multi-user.target |
On the above, you need to replace “/path/to/app/backend” with the path to your application. In backend.wsgi, backend is the application name here, change it to whatever your Django application name is.
1 2 |
User=www-data Group=www-data |
You can change this to whatever user you use to upload your Django application files.
Enable and start the service
1 2 |
systemctl enable backend.service systemctl start backend.service |
Now your Django application will be available on port 8080. You can configure nginx or apache to proxy to this port.
Here is a sample nginx config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
server { listen 443 ssl; server_name app.serverok.in; ssl_certificate /etc/ssl/app.serverok.in.crt; ssl_certificate_key /etc/ssl/app.serverok.in.key; root /var/www/app.serverok.in/html/; index index.html; location /media/ { alias /var/www/app.serverok.in/html/media/; } location /api/ { include proxy_params; proxy_pass http://localhost:8080/api/; } } |
Here Django application is served as /api/ folder, you can change this as required.
Back to Gunicorn