Running Python Application with gunicorn and nginx

Create a service file for gunicorn

root@django:~# cat /etc/systemd/system/gunicorn2.service
[Unit]
Description=gunicorn2 daemon
Requires=gunicorn2.socket
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/myapp/wagtail2
ExecStart=/home/ubuntu/myapp/venv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn2.sock \
          wagtailblog4.wsgi:application

[Install]
WantedBy=multi-user.target
root@django:~# 

Here

/home/ubuntu/myapp/wagtail2 = path to the folder where web application is.

/home/ubuntu/myapp/venv/bin/gunicorn = is where gunicorn installed inside virtualenv.

Change these path as required.

Restart gunicorn with

systemctl restart gunicorn2

use following nginx config

root@django:~# cat /etc/nginx/sites-enabled/django.conf
server {
    server_name domain.extn;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/ubuntu/myapp/wagtail2;
    }
    
    location /media/ {
        root /home/ubuntu/myapp/wagtail2;    
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn2.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.extn/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/domain.extn/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}
server {
    if ($host = www.domain.extn) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = domain.extn) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name domain.extn www.domain.extn;
    return 404; # managed by Certbot
}
root@django:~# 

Restart nginx

systemctl restart nginx

Comments

Leave a Reply

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