Setting up Django + uWSGI + Nginx for production by mraziz

Compatible with:

Here is my setup for a production Ubuntu server running Nginx as a web server and uWSGI to wrap my Django project and execute python code.

You need to place your project somewhere, usually I create an OS user for my project and create a virtual environment in there. For this example:

Nginx

To install Nginx: sudo apt-get install nginx.

The configuration file resides in /etc/nginx/conf.d/projectname.conf, Nginx automatically includes all configuration files that end with .conf:

upstream django {
    server unix:///tmp/projectname.sock;
}

# configuration of the server
server {
    listen 80;
    server_name projectname.com;
    charset utf-8;

    access_log /var/log/nginx/projectname_access.log;
    error_log /var/log/nginx/projectname_error.log;

    root /home/projectuser/env/django;

    client_max_body_size 75M;

    location /media {
        alias /home/projectname/env/django/media;
    }

    location /static {
        alias /home/projectname/env/django/static;
    }

    location / {
        uwsgi_pass unix:///tmp/projectname.sock;
        include /etc/nginx/uwsgi_params;
    }
}

The socket path unix:///tmp/projectname.sock is where Nginx forwards requests to uWSGI through a socket file

Alter client_max_body_size to your project needs, it's useful to increase it if you have large file uploads. The default value of 1 MB is quite conservative. If the content of an HTTP request is larger than the specified size, HTTP response code 413 "Request Entity Too Large" will return.

Aliases /media and /static are not necessary if you are using cloud storage (e.g. AWS S3) for your static content.

uWSGI

To install uWSGI, activate your virtualenv environment and run: pip install uwsgi.

Supervisor

Supervisor is a daemon that runs as processes management and monitoring tool. Typically you would need to run cron jobs to check if any of your stack components is down, however with supervisor you just configure one or more of your stack components and it will monitor your processes and take action if necessary.

To install supervisor: sudo apt-get install supervisor.

To include uWSGI under supervisor's command, edit /etc/supervisor/supervisord.conf and append the following:

[program:projectname_uwsgi]
command = uwsgi --plugins python --socket /tmp/projectname.sock --chdir /home/projectname/env/django --module project.wsgi --virtualenv /home/projectname/env --chmod-socket=666
stderr_logfile = /home/projectname/env/logs/uwsgi_stderr.log
stdout_logfile = /home/projectname/env/logs/uwsgi_stdout.log
autostart=true
autorestart=true
stopsignal=INT

To manage supervisor, you can use supervisorctl. For instance, to run the uWSGI instance we just defined: sudo supervisorctl start projectname_uwsgi.