Tuesday, August 16, 2011

How to Install django on Debian using nginx uwsgi

Here we are going install a basic django application using uwsgi application server and nginx as load balancer. Requirements:
  • django code location: /usr/local/lib
  • django project: hello
Let install few packages we need:
 apt-get -y install nginx uwsgi \ uwsgi-plugin-python python-django 
Create a simple django application:
 cd /usr/local/lib django-admin startproject hello 

uWSGI

Create uWSGI configuration (file /etc/uwsgi/apps-available/hello.yaml):
 uwsgi: uid: www-data gid: www-data socket: /tmp/uwsgi-hello.sock plugins: http, python module: django.core.handlers.wsgi:WSGIHandler() pythonpath: /usr/local/lib chdir: /usr/local/lib/hello env: DJANGO_SETTINGS_MODULE=hello.settings  
Enable this configuration and restart uwsgi server:
 ln -s /etc/uwsgi/apps-available/hello.yaml \ /etc/uwsgi/apps-enabled/hello.yaml /etc/init.d/uwsgi restart 

nginx

Create nginx site configuration (file /etc/nginx/sites-available/hello):
 upstream backend { server unix:///tmp/uwsgi-hello.sock; } server { location / { uwsgi_pass backend; include uwsgi_params; } location /static/admin/ { alias /usr/lib/pymodules/python2.6/django/contrib/admin/media/; access_log off; expires 7d; } location /static/ { alias /usr/local/lib/hello/static/; access_log off; expires 7d; } } 
Remove default site, enable this configuration and restart nginx server:
 rm /etc/nginx/sites-enabled/default ln -s /etc/nginx/sites-available/hello \ /etc/nginx/sites-enabled/hello /etc/init.d/nginx restart 

nginx - uwsgi_cache

Web sites that serve almost static content (updated let say every 15 mins) can benefit by utilizing content caching:
 ... uwsgi_cache_path /var/cache/hello levels=1:2 keys_zone=NAME:15m inactive=5m; server { location / { uwsgi_pass backend; include uwsgi_params; uwsgi_cache NAME; uwsgi_cache_valid 200 302 15m; uwsgi_cache_key $request_uri; expires 15m; } ... } 
If you experience performance issue with content rendering, overhead of framework internal time, have a willing to fine control content caching consider take a look at the following post and this one.