Deploying Django Project with PostgreSQL, Gunicorn and Nginx

March 18th, 2013

Install libraries and compilers.

We need a few tools and additional libraries to compile python modules.

sudo apt-get install build-essential python-dev python-setuptools libjpeg-dev git-core libpq-dev

Install pip and virtualenv

Virtualenv is a great tool to create sandbox for your python requirements modules.

sudo easy_install pip
sudo pip install virtualenv

Upload django application

sudo mkdir /var/www
sudo chown -R www-data:www-data sample
cd sample
sudo -u www-data virtualenv env
 
sudo -u www-data env/bin/pip install psycopg2
sudo -u www-data env/bin/pip install gunicorn

Install and configure postgresql

sudo apt-get install postgresql
 
sudo -u postgres psql template1
 
ALTER USER postgres with encrypted password 'awe1245';
template1=# CREATE DATABASE test;
template1=# CREATE USER test WITH PASSWORD 'test';
template1=# GRANT ALL PRIVILEGES ON DATABASE test to test;
template1=#\q
 
sudo vim /etc/postgresql/9.1/main/pg_hba.conf
 
local all postgres peer
local all all peer
 
change to
 
local all postgres md5
local all all md5
 
sudo service postgresql restart

Install and configure nginx

sudo apt-get install nginx

Create and edit /etc/nginx/sites-available/sample

server {
  listen 80;
  server_name 192.168.43.136;
 
  access_log /var/www/sample/logs/access.log;
  error_log /var/www/sample/logs/error.log;
 
  gzip  on;
  gzip_http_version 1.1;
  gzip_vary on;
  gzip_comp_level 6;
  gzip_proxied any;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
 
  location /media {
    root /var/www/sample/;
    expires max;
  }
 
  location /static {
    root /var/www/sample/;
    expires max;
  }
 
  location / {
    proxy_pass http://127.0.0.1:8009;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_intercept_errors off;
  }
}

Configure upstart for monitoring gunicorn process

Create and edit file /etc/init/sample.conf

start on runlevel [2345]
stop on runlevel [!2345]
kill timeout 5
respawn
script
cd /var/www/sample/
exec /var/www/example/env/bin/gunicorn sample.wsgi:application \
--log-file=/var/log/nginx/sample_gunicorn.log \
--bind=127.0.0.1:8009 \
--user=www-data \
--group=www-data \
--max-requests=100 \
--workers=4 \
--name=sample
end script

Related posts:

  1. How to Install OSQA in Ubuntu Server
  2. Sphinx search introduction
  3. Relative Path for your Django Project
  4. CakePHP Tutorial:Installing CakePHP on Ubuntu

5 Comments