Installing Django on Ubuntu Intrepid: Django, Nginx, Apache, mod_wsgi, cmemcache

A complete start to finish guide.

This guide will cover the complete setup of an Ubuntu Intrepid server as well as the software below:

Please note, this guide was written for Ubuntu Intrepid, but will likely work on other versions of Ubuntu barring any software version differences.

Install Summary


Log in (for Windows users)

  • Download and install PuTTY
  • Configure and connect
  • Click 'yes' when prompted with security warning

Log in (for Linux users)

$ ssh root@<slice ip>

Setup SSH and add new user

Replace sylink with better shell

$ ln -sf /bin/bash /bin/sh

Change root password

$ passwd

Add a new admin user

$ adduser <username>

Grant new user sudo privileges

$ visudo

Add this to end of file and save

$ <username>   ALL=(ALL) ALL

Linux users and SSH key

Create folder to hold keys (on local workstation)

(local)$ mkdir ~/.ssh

Create SSH keys (on local workstation)

(local)$ ssh-keygen -t rsa

Copy public key onto slice (on local workstation)

(local)$ scp ~/.ssh/id_rsa.pub <username>@<slice ip>:/home/<username>/

Create directory in <username>/home folder to hold public key (on slice)

$ mkdir /home/<username>/.ssh
$ mv /home/<username>/id_rsa.pub /home/<username>/.ssh/authorized_keys

Set permissions on key (on slice)

$ chown -R <username>:<username> /home/<username>/.ssh
$ chmod 700 /home/<username>/.ssh
$ chmod 600 /home/<username>/.ssh/authorized_keys

Disable root login

Switch to new user

$ su <username>

Verify use has sudo before disabling. Should print 'root'

$ sudo whoami

Change default SSH config to be more secure

$ sudo nano /etc/ssh/sshd_config
Port 30000                  <--- change to a port of your 
choosing
Protocol 2
PermitRootLogin no
PasswordAuthentication no   <--- yes if windows
X11Forwarding no
UsePAM no
UseDNS no
AllowUsers <username>

Reload SSH config

$ sudo /etc/init.d/sshd reload

Configure firewall

Install firewall

$ sudo aptitude install ufw

Turn on firewall

$ sudo ufw enable

Enable/disable logging

$ sudo ufw logging on

Enable port 80 for TCP only

$ sudo ufw allow 80/tcp

Enable SSH port you chose before

$ sudo ufw allow <SSH port>

Lock down system

$ sudo ufw default deny

Update system and set locale

Update

$ sudo aptitude update

Set locale. This setting is for the US. If you live in another country you will need to use another setting.

$ sudo locale-gen en_US.UTF-8 
$ sudo /usr/sbin/update-locale LANG=en_US.UTF-8

Safe upgrade

$ sudo aptitude safe-upgrade

Full upgrade

$ sudo aptitude full-upgrade

Install Build Essentials

$ sudo aptitude install build-essential

Configure DNS

Creating DNS records on SliceHost

If you aren't hosted on SliceHost the process for creating your DNS records will be different.

Install Nginx

Install Nginx

$ sudo aptitude install nginx

Start Nginx server

$ sudo /etc/init.d/nginx start

Test Nginx is running by opening your favorite browser and navigating to http://<slice ip>. Should display "Welcome to nginx!"

Configure Nginx

Disable default site

$ sudo rm /etc/nginx/sites-enabled/default

Modify config file

$ sudo nano /etc/nginx/nginx.conf
worker_processes  4;     <--- set equal to the number of cores on your server
tcp_nopush     on;
keepalive_timeout  2;
gzip  on;
gzip_comp_level 2;
gzip_proxied any;
gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

Shutdown Nginx

$ sudo /etc/init.d/nginx stop 
Create proxy.conf file
$ sudo nano /etc/nginx/proxy.conf
proxy_redirect              off;
proxy_set_header            Host $host;
proxy_set_header            X-Real-IP $remote_addr;
proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size        10m;
client_body_buffer_size     128k;
proxy_connect_timeout       90;
proxy_send_timeout          90;
proxy_read_timeout          90;
proxy_buffer_size           4k;
proxy_buffers               4 32k;
proxy_busy_buffers_size     64k;
proxy_temp_file_write_size  64k;

Install Apache

Ignore the error after install

$ sudo aptitude install apache2 apache2.2-common apache2-mpm-worker apache2-threaded-dev libapache2-mod-wsgi python-dev

Configure Apache

Modify config file

$ sudo nano /etc/apache2/apache2.conf
Timeout 90
KeepAlive Off
ServerName <server name>

Restart Apache

$ sudo apache2ctl graceful

Test Apache is running by opening your favorite browser and navigating to http://<slice ip>. Should display "It works!"

Disable default site

$ sudo a2dissite 000-default

Change listening port and virtual host to 8080

$ sudo nano /etc/apache2/ports.conf

Change security settings

$ sudo nano /etc/apache2/conf.d/security

Restart Apache, ignore the error

$ sudo apache2ctl graceful

Start Nginx

$ sudo /etc/init.d/nginx start

Install Subversion

$ sudo aptitude install subversion

Install Django

Change directory

$ cd /usr/lib/python2.5/site-packages

Checkout code from Django SVN

$ sudo svn co http://code.djangoproject.com/svn/django/tags/releases/1.0.2/django django

Create symlink

$ sudo ln -s /usr/lib/python2.5/site-packages/django/django/bin/django-admin.py /usr/local/bin/django-admin.py

Install Memcached

Install Memcached and dependencies

$ sudo aptitude install memcached
$ sudo aptitude install libmemcache-dev

Download cmemcached

$ cd /usr/local/src/
$ sudo wget http://gijsbert.org/downloads/cmemcache/cmemcache-0.95.tar.bz2

Install cmemcache

$ sudo tar xjvf cmemcache-0.95.tar.bz2
$ cd cmemcache-0.95
$ sudo python setup.py install

Edit test.py

$ sudo nano test.py
# get stats
#stats = mc.get_stats()
#self.failUnlessEqual(len(stats), 1)
#self.assert_(self.servers[0] in stats[0][0])
#self.assert_('total_items' in stats[0][1])
#self.assert_('bytes_read' in stats[0][1])
#self.assert_('bytes_written' in stats[0][1])

Start Memcached. Be sure to set memory size

$ memcached -d -m <memory size> -l 127.0.0.1 -p 11211

Run test.py

$ python test.py

Create layout for domains

Create parent directory layout

$ mkdir /home/<username>/public_html

Create sub-folders for domain

$ mkdir -p /home/<username>/public_html/<domain name>
$ mkdir -p /home/<username>/public_html/<domain name>/private
$ mkdir -p /home/<username>/public_html/<domain name>/logs

Grant Apache write permissions

Add main user to Apache group

$ sudo usermod -a -G www-data <username>

Make sure public_html folder is owned by <username> and is in the www-data group

$ sudo chgrp -R www-data /home/<username>/public_html

Make sure any new files put into public_html will inherit permissions

$ sudo chmod -R 2750 /home/<username>/public_html

Grant Apache write permissions to private folder (if needed)

$ sudo chmod -R 2770 /home/<username>/public_html/<domain name>/private

Install source code

Change directory and install your source code in this directory

$ cd /home/<username>/public_html/<domain name>

Create .wsgi file

$ mkdir /home/<username>/public_html/<domain name>/<django project name>/apache
$ cd /home/<username>/public_html/<domain name>/<django project name>/apache
$ nano <django project name>.wsgi
import os, sys

apache_configuration= os.path.dirname(__file__)
project = os.path.dirname(apache_configuration)
workspace = os.path.dirname(project)
sys.path.append(workspace) 

sys.path.append('/usr/lib/python2.5/site-packages/django/')
sys.path.append('/home/<username>/public_html/<domain name>/<django project name>')

os.environ['DJANGO_SETTINGS_MODULE'] = '<django project name>.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Create symlink for admin media

$ sudo ln -s /usr/lib/python2.5/site-packages/django/contrib/admin/media /home/<username>/public_html/<domain name>/<django project name>/media/admin

Modify settings.py file of your project

$ sudo nano settings.py
ADMIN_MEDIA_PREFIX = '/media/admin/'
.
.
.
MIDDLEWARE_CLASSES = (
    'django.middleware.http.SetRemoteAddrFromForwardedFor',
)

Create Nginx virtual host

Create new virtual host file

$ sudo nano /etc/nginx/sites-available/<domain name>
upstream backend {
  server 127.0.0.1:8080;
}

server {
            listen   80;
            server_name www.<domain name> <domain name>;

            access_log /home/<username>/public_html/<domain name>/logs/nginx_access.log;
            error_log /home/<username>/public_html/<domain name>/logs/nginx_error.log;

            location / {
                        proxy_pass  http://backend;
                        include     /etc/nginx/proxy.conf;
            }

            location  /media/ {
                        root /home/<username>/public_html/<domain name>/<django project name>/;
            }
}

Create symlink to enable new domain

$ sudo ln -s /etc/nginx/sites-available/<domain name> /etc/nginx/sites-enabled/<domain name>

Restart Nginx

$ sudo /etc/init.d/nginx stop 
$ sudo /etc/init.d/nginx start

Create Apache virtual host

Create new virtual host file

$ sudo nano /etc/apache2/sites-available/<domain name>
<VirtualHost *:8080>
    #Basic setup
    ServerAdmin <admin email>
    ServerName www.<domain name>
    ServerAlias <domain name>

    <Directory /home/<username>/public_html/<domain name>/<django project name>/apache/>
        Order deny,allow
        Allow from all
    </Directory>

    LogLevel warn
    ErrorLog  /home/<username>/public_html/<domain name>/logs/apache_error.log
    CustomLog /home/<username>/public_html/<domain name>/logs/apache_access.log combined
    
    WSGIDaemonProcess <domain name> user=www-data group=www-data threads=25
    WSGIProcessGroup <domain name>
    
    WSGIScriptAlias / /home/<username>/public_html/<domain name>/<django project name>/apache/<django project name>.wsgi
</VirtualHost>

Enable new site

$ sudo a2ensite <domain name>
$ sudo /etc/init.d/apache2 reload

Your new server should now be up and running. If you'd like more information on the above directions please consult the sources below:


Comments

Frank Malina (15 Feb 2009)

Hi, you forgot to include your proxy.conf for nginx

Ben (25 Feb 2009)

I used the proxy.conf example from this page: http://lethain.com/entry/2009/feb/13/...

Great guide, thanks!

meppum (06 Mar 2009)

@ Frank Malina

Thanks Frank. I've updated this post with the proxy.conf file.

Eliot (07 May 2009)

A formatting nit: under "Create .wsgi file", I think the background colors for the code blocks should be swapped.

Otherwise, excellent, complete, guide. I'm looking to install mod_wsgi with almost exactly the same setup. I will definitely reference this article.

meppum (08 May 2009)

@ Eliot

Thanks. Good catch.

Jonathan Biddle (25 Jun 2009)

Thanks so much for writing this, I keep coming back to this article every time I have to setup a new slice :P

vn44ca (07 Jul 2009)

Very Nice. Now how much memory did you allocated to memcache and how much memory did you have on your slicehost? Any preference?

Andrew (23 Jul 2009)

Thanks for the awesome guide. I followed this to get my own server started. I however ran into problems when handling hotlinking prevention.

I added the following to my /etc/nginx/sites-available file
location ~* ^.+\.(gif|jpg|png)$ {
valid_referers none blocked http://127.0.0.1:8080 server_name;
if ($invalid_referer) {
return 404;
}
}

regardless of what i put after the "valid_referers none blocked" I block my server from getting the images

Please let me know if you have a way of fixing this. Thanks!

to (22 Sep 2009)

Wow, many thanks!

clark (22 Sep 2009)

this works on ubuntu 9.04 too, just got my Django, Nginx, Apache, mod_wsgi server up and running on Jaunty

Adam Nelson (23 Sep 2009)

This should be done in /etc/apache2/conf.d/<project name>.conf rather than /etc/apache2/apache2.conf for easier portability/upgrading/maintenance:

Timeout 90
KeepAlive Off
ServerName <server name>

Charles (30 Sep 2009)

This worked superbly crunchbang 9.04. I had apache / mysql / php from an earlier `sudo tasksel install lamp-server` - just wasn't sure how to get nginx & apache synced up. Great work -

Duerobete (16 Oct 2009)

порно школьница онлайн http://free-3x.com/ порно малолеток фото <a href="http://free-3x.com/">free-3x.com/</a> посмотреть порно видео трахнули училку <a href=http://free-3x.com/>free-3x.com</a>

Matt McClanahan (16 Oct 2009)

I would strongly recommend changing the "Install Django" section to use a release version of Django, installed from an Ubuntu package, a release tarball, or using easy_install or pip. It's risky for people to run a production server off of a subversion checkout. It's also a fairly poor sysadmin practice to manually install a package within /usr/lib, which the FHS recommends be managed by the system's packaging tools.

Robert Adams (19 Oct 2009)

Thank you very much for writing this tutorial.

It has proven invaluable. I have consulted it countless times in the past few days.

Thanks again

Esteban Feldman (02 Nov 2009)

Why are you setting up django/apache on 8080?
Shouldn't be on 80?

Assignment Help (22 Jan 2010)

Hi,
Very nice, unique and informative post. Thanks for sharing. Keep up the good work.

Daycle (23 Jan 2010)

Nationwide Houses Nationwide Homes Nationwide Realty. <a href=http://alqdosugdkc.freehostia.com/map.html>advance cash guaranteed</a> We offer Business Loans and Cash Advances in Utah. Dba NATIONAL CASH ADVANCE. New first american cash advance first american cash advance faxing payday. Easy Lawsuit funding company offers Litigation financing Lawsuit loans Legal. Article and News of Payday Loans Cash Loans Payday Advance Canada Ontario.

Writing Services (28 Jan 2010)

This post helped me a lot since I have been using Ubuntu for my small business. I'm not really into computers so I have to look for published info online that could help me when I encounter problems regarding my system. Thanks!

KonnieNf32 (29 Jan 2010)

You are apparently, a professional of essay thesis related to this good topic composing but if you want to opt for the <a href="http://www.topthesis.com">thesis</a>, I would ofer you to coose the greates item.

Daycle (31 Jan 2010)

Cash Advance businesses are popping up all over the United States Canada. A payday loans direct loan is similar to a cash advance. UC Berkeley employees can obtain cash advances for business travel by using. It39s On Advance America To Stop Providing Payday Loans to Military Personnel middot. <a href=http://bssvetapj.100webspace.net/map.html>bbb accredited cash advance</a> If approved the cash advance may be received through an electronic funds. VISA Platinum Basic Credit Card.

dxrgjjuukdd (04 Feb 2010)

http://observers.france24.com/en/prof... - Amanda Seyfried nude <a href="http://observers.france24.com/en/profile/20100203-amanda-seyfried-nude">Amanda Seyfried nude</a>
http://voir.ca/members/palaumad.aspx - Alison Brie nude <a href="http://voir.ca/members/palaumad.aspx">Alison Brie nude</a>
http://healthcentral.com/adhd/c/19672... - Michelle Trachtenberg Nude <a href="http://healthcentral.com/adhd/c/196726/profile">Michelle Trachtenberg Nude</a>
http://projectopus.com/user/51773 - Zoe Saldana Naked <a href="http://projectopus.com/user/51773">Zoe Saldana Naked</a>
http://carrieunderwoodofficial.com/us... - Katy Perry nude <a href="http://carrieunderwoodofficial.com/us/blog/kpn">Katy Perry nude</a>
http://123peppy.com/user/273397 - Lady GaGa nude <a href="http://123peppy.com/user/273397">Lady GaGa nude</a>
http://profiles.friendster.com/119372107 - Lindsay Lohan Topless <a href="http://profiles.friendster.com/119372107">Lindsay Lohan Topless</a>
http://lerparaver.com/blog/2617 - Katrina Bowden Nude <a href="http://lerparaver.com/blog/2617">Katrina Bowden Nude</a>
http://blackamericaweb.com/?q=content... - Kristen Stewart Nude <a href="http://blackamericaweb.com/?q=content/kristen-stewart-nude">Kristen Stewart Nude</a>
http://maximumpc.com/user/snookie_nude - Snookie nude <a href="http://maximumpc.com/user/snookie_nude">Snookie nude</a>

KirstenTS25 (04 Feb 2010)

Really important issue of university students' life is to get an academic success and to do this, they must show the <a href="http://quality-papers.com/topics/sociology_essays">custom sociology essays</a> of perfect quality. Furthermore, the best writing services will assist to gain the aim quickly.

Custom web design (09 Feb 2010)

Thanks for great tips!

Witpranna (11 Feb 2010)

QueepupsTycle
<a href="http://avsrekdncsk.com">ybgf</a>

Djubrail (16 Feb 2010)

djubi test

Alica Brown (17 Feb 2010)

Thanks for the detailed information! Everything is clear and understandable. Everybody will be able to use the info for his/her benefit following the provided guide!

Djubrail (18 Feb 2010)

djubi test
http://twitter.com/legalhighsherb <a href=http://twitter.com/legalhighsherb>legal high</a>

Learning german (18 Feb 2010)

If anyone here truly feels fiat currency is worthless then feel free to give me all your money.

Dronorceacriz (22 Feb 2010)

Money is so intangible, its almost like a promise and a piece of paper.

cleglergo (27 Feb 2010)

russian dating site for sale <a href=http://loveepicentre.com/>radiometric dating</a> free equestrian dating sites http://loveepicentre.com/ singles lesbian

essay help (27 Feb 2010)

I like your stuff!

phophyMex (03 Mar 2010)

toshiba laptop <a href=http://www.hqlaptopbatteries.com/-j60-laptopbatterymodel1935.html>universal laptop battery</a> Laptop AC Adapter http://www.hqlaptopbatteries.com/-v50... AC Adapter
laptop batteries <a href=http://www.hqlaptopbatteries.com/battery-9502wlmi-batterytype1.html>laptop comparison</a> high quality new notebook batteries http://www.hqlaptopbatteries.com/-400... universal laptop battery
Fujitsu Laptop <a href=http://www.hqlaptopbatteries.com/-4400lmi-laptopbatterymodel1041.html>best laptops</a> toshiba laptop http://www.hqlaptopbatteries.com/-250... Lenovo Laptop

Crergemurtumn (03 Mar 2010)

adjusting a pioneer auto dvd <a href=http://www.cardvdplanet.com/768t-is-multi-function-portable-dvd-rotation--discount-price97.html>auto audio chesapeake virginia</a> compatible wireless headphones for all auto dvd systems http://www.cardvdplanet.com/car-dvd-p... ipod touch auto audio cable
auto audio for sale <a href=http://www.cardvdplanet.com/10-4-inch-tft-lcd-color-super-clear-picture--discount-price81.html>honda car audio code</a> car audio 1995 infiniti j30 repair http://www.cardvdplanet.com/9-0-inch-... car audio systems integrated ford falcon
auto audio chesapeake virginia <a href=http://www.cardvdplanet.com/7-inch-display-car-dvd-player-touchscreen--discount-price44.html>chrysler concorder factory car audio amplifier</a> car audio equipment for gmc http://www.cardvdplanet.com/9-inch-po... car audio toyota

business loans (04 Mar 2010)

People deserve very good life time and <a href="http://lowest-rate-loans.com">loan</a> or credit loan can make it better. Just because freedom is based on money state.

Logo Design (05 Mar 2010)

great share thanks for this

health care (07 Mar 2010)

Thanks for the detailed information! Everything is clear and understandable. Everybody will be able to use the info for his/her benefit followin g the prov
[URL=http://www.style360spot.blogspot.com]fashion[/URL]

خدمة العملاء (08 Mar 2010)

Thanks for the detailed information! Everything is clear and understandable. Everybody will be able to use the info for his/her benefit following the provided guide!

Promotional gifts (08 Mar 2010)

A formatting nit: under "Create .wsgi file", I think the background colors for the code blocks should be swapped. Otherwise, excellent, complete, guide. I'm looking to install mod_wsgi with almost exactly the same setup. I will definitely reference this article.

CRM (08 Mar 2010)

Thank you so much for such an article I've been always looking for this type of information

Add your comment

No HTML. Line breaks and URLs will automatically be converted.

(private)