Apache proxy auto-re-loader

Sunday 17 February 2008

On my development machine, I use the Django development web server, proxied by Apache so that static files can be served directly by Apache. Because of the way the Django development server works, when I edit a source file, it automatically restarts, and I can reload my browser page to see the effects of the new code.

This works great, except that it takes a little time for Django to restart. As my Ctrl-S (save the file), Alt-Tab (switch back to the browser), Ctrl-R (reload the page) twitch gets faster, the browser reloads before Django has restarted, and I end up with a stupid error page:

Bad Gateway

The proxy server received an invalid response from an upstream server.

Then I keep hitting Ctrl-R until the page comes up. The last thing I need is another pellet lever in my life.

This simple hack solved my problem. In Apache’s http.conf, add this line:

# If Django isn't ready yet, try again automatically.
ErrorDocument 502 "<meta http-equiv='refresh' content='2'>Retrying in 2 secs."

This makes use of the fact that Apache ErrorDocument directives can specify the literal content to return to the browser in addition to the usual filename or URL to return. 502 is the error status for Bad Gateway. Now when Django isn’t ready, the browser shows a simple message, then reloads automatically every two seconds until it gets a real page.

Of course, you could write a nicer page, maybe with some attempt to not reload forever in the case that the server really isn’t coming up, but this quick hack works and makes those slow restarts a small moment of peace.

Comments

[gravatar]
Marius Gedminas 1:18 PM on 17 Feb 2008

Yes, this is a nice trick. I use it on a production server to make upgrades less painful for users.

The only downside with this solution is that if you try to POST a form and end up on this 502 page, all that form data will get lost.

[gravatar]
Dave St.Germain 9:32 PM on 17 Feb 2008

in Apache 2.2, I think the best way to handle this situation is to set the retry to 0 in the options to the ProxyPass directive:

ProxyPass /foo http://backend/foo retry=0

I haven't tried it yet.

[gravatar]
Matt Oyer 7:25 PM on 19 Feb 2008

if done server side (with php or python or perl or w/e) you could simply not return the page until its ready (preserving all post's and other paraphernalia)

mabey code a "im alive" signal into the startup to be sent to a listening script?

[gravatar]
Florian 12:09 PM on 31 Mar 2009

ProxyPass /foo http://localhost:1234/foo retry=1 timeout=1

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.