August 26, 2017

Django on UWSGI

Very simple config for launching django project on uwsgi server.


$ sudo bash -c "apt-get update && apt-get -y dist-upgrade"

$ sudo apt-get install python3-dev python3-setuptools python3-pip python-virtualenv

$ su - site_user

$ git clone git@example.com:/project.git

$ virtualenv -p python3 venv

$ source venv/bin/activate

$ pip3 install -r project/requirements.txt

$ vim project/system/settings.py

$ vim uwsgi.ini

[uwsgi]

socket  = /var/tmp/site.sock
chdir   = /var/www/django/site/project
module  = system.wsgi
wsgi-file = system/wsgi.py
home    = /var/www/django/site/venv
vacuum  = true
chmod-socket = 666
master  = true
pidfile = /var/tmp/site.pid
env = DJANGO_SETTINGS_MODULE=system.settings

daemonize = /var/www/django/site/logs/uwsgi.log
touch-reload = /var/www/django/site/reload

$ vim start_uwsgi.sh

#!/usr/bin/env bash
    
/var/www/django/site/venv/bin/uwsgi --ini /var/www/django/site/project/uwsgi.ini

$ deactivate

$ exit

$ sudo vim /etc/nginx/sites-available/site

upstream project {
    server unix:///var/tmp/site.sock;
}

server {
    listen 80;
    server_name site;
    
    #  auth_basic "Not allowed";
    #  auth_basic_user_file .passwd;
    
    access_log  /var/log/nginx/project_access.log;
    error_log  /var/log/nginx/project_error.log error;
    
    # Django media
    location /media  {
        alias /var/www/django/project/media;  # your Django project's media files - amend as required
    }
    
    # Django static
    location /static {
        alias /var/www/django/project/static;  # your Django project's media files - amend as required
    }
    
    location ^/\.git {
        deny all;
    }
    
    location ~* /\.htaccess {
        deny all;
    }
    
    location ^/robots.txt {
        try_files /robots.txt @robots_allow;
    }
    
    location @robots_allow {
        return 200 "User-agent: *\nAllow: /";
    }
    
    location @robots_deny {
        return 200 "User-agent: *\nDisallow: /";
    }
    
    location / {
        uwsgi_pass project;
        include uwsgi_params;
    }
}

$ sudo ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled

$ sudo adduser nginx site_user

$ sudo service nginx configtest

$ sudo service nginx reload