Saturday, February 16, 2008

Load Balance Rails Mongrel Clusters With Apache

A simple solution for load balancing a Ruby on Rails Mongrel cluster with an Apache front end is to use the randomizing feature in Apache module mod_apache’s rewrite map feature. Say, for instance, you have 3 Mongrel servers, running on ports 4000 to 4002 on localhost. First create a file map.txt containing these numbers:

ports 4000|4001|4002


Then ensure the following directives are present inside the VirtualHost stanza in your Apache configuration:

ProxyRequests Off
ProxyPassReverse / http://localhost:4000/
ProxyPassReverse / http://localhost:4001/
ProxyPassReverse / http://localhost:4002/
ProxyPreserveHost On
RewriteEngine On
RewriteMap servers rnd:/path/to/your/map.txt
RewriteRule ^/(images|stylesheets|javascripts)/?(.*) $0 [L]
RewriteRule ^/(.*)$ http://localhost:${servers:ports}/$1 [P,L]

Restart Apache, and that is it.

I have had great success using both the Pound load balancer, and Nginx, which I suggest highly, but Apache does a great job when necessary.

No comments: