Tutorial

Using mod_wsgi to Serve Applications on Ubuntu 12.04

Published on July 19, 2012
Using mod_wsgi to Serve Applications on Ubuntu 12.04

Status: Deprecated

This article covers a version of Ubuntu that is no longer supported. If you are currently operate a server running Ubuntu 12.04, we highly recommend upgrading or migrating to a supported version of Ubuntu:

Reason: Ubuntu 12.04 reached end of life (EOL) on April 28, 2017 and no longer receives security patches or updates. This guide is no longer maintained.

See Instead:
This guide might still be useful as a reference, but may not work on other Ubuntu releases. If available, we strongly recommend using a guide written for the version of Ubuntu you are using. You can use the search functionality at the top of the page to find a more recent version.

Prerequisites

Before starting on this article, be sure that you have gone through the previous 2 in this series. You can find them here:

Installing Django on Ubuntu 12.04

Installing mod_wsgi on Ubuntu 12.04

Creating the Django Application:

First of all, we will navigate to the home directory. Create a new directory and switch into it:

mkdir  -p ~/public_html/domain1.com
cd ~/public_html/domain1.com

After that, go ahead and create a project with the help of the django-admin.py tool.

django-admin.py startproject MyTestProject

Creating the Virtual host & WSGI file:

To serve a Django app properly, it is important for Apache to know that it is supposed to forward certain types of requests to mod_wsgi. It is also important to create wsgi file that tells mod_wsgi how to handle these requests. We will setup a virtual host to accomplish these tasks. It will tell Apache the location of wsgi file and setup the file accordingly.

Open up the new virtual host file.

sudo nano /etc/apache2/sites-available/domain1.com

Next, enter below definition for the virtual host:

<VirtualHost *:80>
        ServerName domain1.com
        ServerAlias www.domain1.com
        WSGIScriptAlias / /home/username/public_html/domain1.com/MyTestProject.wsgi
</VirtualHost>

Once we have instructed apache to use the wsgi file specified above and pass the receiving request to mod_wsgi, we will create the mod_wsgi file itself.

nano ~/public_html/domain1.com/MyTestProject.wsgi

Type in the following configuration:

import os
import sys	
sys.path.append('~/public_html/domain1.com/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'MyTestProject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

This definition ensures that the necessary modules will be imported. Moreover, it appends the Django project’s path to Python’s path and sets up a number of variables that helps mod_wsgi to work. Once you are done with it, you will need to enable the virtual host and restart Apache.

sudo a2ensite domain1.com
sudo /etc/init.d/apache2 reload

If everything goes as expected, you will be able to see your domain (droplet IP) in the browser, and get the newly created application. Reload Apache in case you receive any NameVirtualHost or port errors.

Static Content

There is a caveat to virtual host definitions. Static content is not supported. To serve the static content properly, you can update few settings in the file MyTestProject/settings.py and use following definition of virtual host.

<VirtualHost *:80>
        ServerName domain1.com
        ServerAlias www.domain1.com
        WSGIScriptAlias / /home/username/public_html/domain1.com/MyTestProject.wsgi
        Alias /static/ /home/username/public_html/domain1.com/static/
        <Location "/static/">
            Options -Indexes
        </Location>
</VirtualHost>

The Alias Directive lets Apache know that it should not allow Django or mod_wsgi to handle anything located under the /static/ directory of your domain. You can use any directory but make sure that it is available under /home/username/public_html/domain1.com/. In our example, the name of the directory is static. Update settings.py by setting the variables for MEDIA_ROOT and MEDIA_URL.

 nano /home/username/public_html/domain1.com/MyMyTestProject/settings.py

Find and update the settings below.

MEDIA_ROOT = '/home/username/public_html/domain1.com/static/'
MEDIA_URL = '/static/'

Finally, restart Apache to the changes into effect.

 sudo /etc/init.d/apache2 reload

You can access any items that have been placed in the MEDIA_ROOT through http://www.domain1.com/static/path/to/file.

Changes to Django App

It is a good idea to get into the habit of restarting apache every time you make changes to the project.

Etel Sverdlov

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I couldn’t get this working with Django 1.4. I used the wsgi.py file that is created with the project. Then I had to add the following lines to it so it would find the settings file:

base = os.path.dirname(os.path.dirname(file)) base_parent = os.path.dirname(base) sys.path.append(base) sys.path.append(base_parent)

Thanks a lot, it worked awesome. First time I tried Python, first time I tried Django and just worked straight away. This never happened before! Great tutorial, thanks again.

Tried it with Django 1.5. Didn’t work too well for me. Everything seemed to go more or less smoothly, but after I created the .wsgi file and restarted apache I noticed that nothing changed, still get the default apache web page rather than the Django app page.

I’m open to suggestions

Here is a full tutorial I wrote for setting up django 1.4 project on Apache2 with mod_wsgi and virtual env http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/ based from my experiences on digitalocean Ubuntu VPS. Hope you find it helpful.

Hi, I’m getting a 500 Internal Server Error. Where would I find an error log to review?

Answer, the log file is here: /var/log/apache2/error.log

On reading the output, the issue is here:

raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))

ImportError: Could not import settings ‘MyTestProject.settings’ (Is it on sys.path?): No module named MyTestProject.settings

Any suggestions?

Thanks, Matt

katlis’ comment above has provided me with the solution I needed.

I’ve followed the steps in this and the previous two pages for setting up django and I can’t get any further than the default apache2 ‘It works’ page.

sudo service apache2 restart gives the following;

“apache2: could not reliably determine the serv’s fully qualified domain name, using 127.0.0.1 for servername”

If I attempt, service apache2 restart , I instead get,

“(13) Permission denied: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down”

I’m relatively new to this but I’m presuming that something is blocking port 80. Does anyone know where to go from here with this?

Problem fixed. I had to run, sudo a2dissite default

Then I had to modify my wsgi.py file in my django project folder to include sys.path.append(‘/home/username/public_html/domain1.com/MyProject/’)

(This is so apache2 can find the settings module)

terminal > django-admin.py startproject MyTestProject -bash: django-admin.py: command not found

:( Try:

terminal > django-admin startproject MyTestProject

:)

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.