Apache proxy auto-re-loader

Sunday 17 February 2008This is almost 17 years old. Be careful.

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.

» 4 reactions

Comments

[gravatar]
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]
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]
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]
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:
Comment text is Markdown.