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:
- Uncomplicated Firewall (UFW)
- Nginx serving only static content
- Apache with mod_wsgi serving only dynamic content
- Memcached and the cmemcache library
- Subversion
- Django
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
- SSH Setup
- Configure firewall
- Update system and set locale
- Install Build Essentials
- Configure DNS
- Nginx
- Apache
- Install Subversion
- Install Django
- Install Memcached
- Create layout for domains
- Grant Apache Write Permissions
- Install source code
- Create Nginx virtual host
- Create Apache virtual host
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 stopCreate 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:
- http://www.punteney.com/writes/setting-django-slicehost-ubuntu-hardy-postgres-apa/
- http://thisweekindjango.com/screencasts/episode/21/django-ground-episode-13/
- http://wiki.slicehost.com/doku.php?id=dream_geodjango_server/
- http://www.technobabble.dk/2008/aug/25/django-mod-wsgi-perfect-match/
- http://blog.dscpl.com.au/search/label/mod_wsgi/
- http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango/
- http://articles.slicehost.com/2007/9/18/apache-virtual-hosts-permissions/
- http://articles.slicehost.com/2008/5/16/ubuntu-hardy-nginx-virtual-hosts/
- http://articles.slicehost.com/2008/5/15/ubuntu-hardy-nginx-configuration/
- http://articles.slicehost.com/2007/12/13/ubuntu-gutsy-nginx-configuration-1/
- http://articles.slicehost.com/2007/12/17/ubuntu-gutsy-nginx-virtual-hosts-2/
- http://articles.slicehost.com/2008/12/11/ubuntu-intrepid-apache-configuration-1/
- http://articles.slicehost.com/2008/12/11/ubuntu-intrepid-apache-configuration-2/
- http://articles.slicehost.com/2008/12/17/ubuntu-intrepid-apache-virtual-hosts-1/
- http://articles.slicehost.com/2008/12/17/ubuntu-intrepid-apache-virtual-hosts-2/
- http://articles.slicehost.com/2008/11/28/ubuntu-intrepid-setup-page-1/
- http://articles.slicehost.com/2008/11/28/ubuntu-intrepid-setup-page-2/
- http://articles.slicehost.com/2007/9/13/multiple-hosts-layout
- http://www.davidcramer.net/code/django/108/setup-mod_wsgi-for-django-and-shared-hosting.html
Add your comment
No HTML. Line breaks and URLs will automatically be converted.
Comments
Hi, you forgot to include your proxy.conf for nginx
I used the proxy.conf example from this page: http://lethain.com/entry/2009/feb/13/...
Great guide, thanks!
@ Frank Malina
Thanks Frank. I've updated this post with the proxy.conf file.
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.
@ Eliot
Thanks. Good catch.
Thanks so much for writing this, I keep coming back to this article every time I have to setup a new slice :P
Very Nice. Now how much memory did you allocated to memcache and how much memory did you have on your slicehost? Any preference?
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!
Wow, many thanks!
this works on ubuntu 9.04 too, just got my Django, Nginx, Apache, mod_wsgi server up and running on Jaunty
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>
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 -
порно школьница онлайн http://free-3x.com/ порно малолеток фото <a href="http://free-3x.com/">free-3x.com/</a> посмотреть порно видео трахнули училку <a href=http://free-3x.com/>free-3x.com</a>
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.
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
Why are you setting up django/apache on 8080?
Shouldn't be on 80?
Hi,
Very nice, unique and informative post. Thanks for sharing. Keep up the good work.
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.
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!
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.
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.
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>
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.
http://observers.france24.com/en/prof... - Amanda Seyfried nude
http://voir.ca/members/palaumad.aspx - Alison Brie nude
http://healthcentral.com/adhd/c/19672... - Michelle Trachtenberg Nude
http://projectopus.com/user/51773 - Zoe Saldana Naked
http://carrieunderwoodofficial.com/us... - Katy Perry nude
http://123peppy.com/user/273397 - Lady GaGa nude
http://profiles.friendster.com/119372107 - Lindsay Lohan Topless
http://lerparaver.com/blog/2617 - Katrina Bowden Nude
http://maximumpc.com/user/snookie_nude - Snookie nude
Thanks for great tips!
QueepupsTycle
<a href="http://avsrekdncsk.com">ybgf</a>
djubi test
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!
djubi test
http://twitter.com/legalhighsherb <a href=http://twitter.com/legalhighsherb>legal high</a>
If anyone here truly feels fiat currency is worthless then feel free to give me all your money.
Money is so intangible, its almost like a promise and a piece of paper.
russian dating site for sale <a href=http://loveepicentre.com/>radiometric dating</a> free equestrian dating sites http://loveepicentre.com/ singles lesbian
I like your stuff!
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
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
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.
great share thanks for this
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]
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!
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.
Thank you so much for such an article I've been always looking for this type of information