Setting up lighttpd/Apache for Django on Slicehost

I finally made the jump and moved the websites I was hosting on my home PC and moved them out to slicehost. Signing up for my slice could not have been easier and so far it has been a flawless experience. The PickledOnion articles were nice to double-check myself to make sure I didn't miss anything.

I opted for the Ubuntu 7.10 256 MB slice since that was what the sites were priorly hosted on. I decided that I wanted to do things by the book so I set up a lighttpd server that served my media straight up and funneled all Django requests through Apache/mod_python. I couldn't find an exact way to this previously published so I thought I would add a few code snippets to help others looking to do the same.

First off, I got the Apache/mod_python setup working. This was pretty much a cut and paste from the deployment docs found in the Django book. Nothing tricky there. By default, Apache runs on port 80, but that will be changed later on.

The next step was to get lighttpd working properly. The relevant snippet is below:

$HTTP["host"] =~ "^(www.)?example.com" {
    $HTTP["url"] !~ "^/(public|media)/" {
        proxy.server = ( "" =>
            ( (
                "host" => "127.0.0.1",
                "port" => 81
            ) )
        )
    }
}

Broken down, this says if we get a request for example.com and the URL does not contain one of our media directories (read: a Django request), proxy it to port 81. This way lighttpd will serve up all the static files and then redirect the Django stuff to our Apache instance that will be listening on port 81.

After that, change the ports.conf file for your Apache instance to listen on port 81, and the “server.port” variable in your lighttpd.conf to listen on port 80, and then restart both servers. If everything went correctly, you should now have a 2 servers doing what they do best and have a happy machine to boot.

I did add a couple of lines to my Apache conf to get better performance.

First off, I turned off KeepAlive as suggested by Jacob Kaplan-Moss. KeepAlive is useful if you are using Apache to serve up several files over one TCP connection, like multiple images on a page load. Since on every page load we are making just one request to Apache (for the HTML itself) and lighttpd is handling all of the static serving (which it is very good at it), KeepAlive helps us none and actually hurts us as Apache will quickly become RAM hungry holding on to your full Django code when there is no need for it.

Second tuning measure was to bump MaxRequestsPerChild up. I set mine at 500 and saw a big RAM usage drop. This way since these are fairly RAM-heavy Apache processes, they'll get cleaned up once they reach a certain number.

Overall, I have been very pleased with slicehost and the Django book was very helpful in getting everything up and running.