Serve a Django application using Gunicorn

Create systemd service file

vi /usr/lib/systemd/system/backend.service

Add

[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.

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

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

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *