Load Balancing With Apache |
Server - Web Server |
Apache makes for a great load balancer, with the help of mod_proxy and mod_proxy_balancer. If you use Apache as the back end, this makes deploying new back ends very easy, as everything in the cluster will use the same software load out.
In this tutorial, we'll assume that you already have a site set up and working in Apache. We'll also assume that you have separate back end servers. File locations and directory paths will be based on Debian/Ubuntu standards, so change them as needed for other distributions.
The first step to take is to enable the modules.
a2enmod mod_proxy a2enmod mod_proxy_balancer
Now, make a new virtual host, and configure it like this: <VirtualHost *:80> ProxyRequests off #disable forward proxying
ServerName beginlinux.com
<Proxy balancer://cluster> BalancerMember http://172.31.0.42:80 BalancerMember http://172.31.0.44:80
#security Order Deny,Allow Deny from none Allow from all
#use round-robin balancing ProxySet lbmethod=byrequests </Proxy>
#balance-manager is a tool that lets you configure and tune Apache <Location /balancer-manager> SetHandler balancer-manager
#lock this down tightly Order deny,allow Allow from all </Location>
#what to actually balance #in this case, balance everything except the manager ProxyPass /balancer-manager ! ProxyPass / balancer://cluster/ </VirtualHost>
At this point you're practically done. Move all the site files over to the back end servers (and perhaps set up unison to keep the files synchronized), and change the default catch-all virtualhost as needed to make your site run correctly.
The configuration above uses a round-robin approach to load balancing, which is good for anything that doesn't involve user sessions. If you have user authentication of some kind in your application, and sessions are not somehow shared between the back end servers (usually through a database), then you will have to use persistent sessions.
This problem often manifests itself as browsing the site, logging in, then sometimes being logged out and back in, as you browse the site. To fix it, we'll need another Apache module.
a2enmod mod_headers
We'll then need to change a few lines around the Proxy block of configuration.
Header add Set-Cookie "ROUTEPATH=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED <Proxy balancer://cluster> BalancerMember http://172.31.0.42:80 route=1 BalancerMember http://172.31.0.44:80 route=2 ProxySet stickysession=ROUTEPATH </Proxy>
Now which server you're using will be stored as a cookie, and you will always connect to that same server. |