Simple load balancing with apache

This guide is for setting up balancing in apache. The concept is universal but in different environments the configuration will not be the same.

Sometimes you need two instances of the same application running. Maybe you have heavy traffic or you want to avoid downtime when updating your app to the latest version.

Your solution: balancing.

requirements

  • apache2
  • mod_proxy
  • lbmethod_byrequests
  • proxy_balancer

installing and enabling

First (if you haven't done so yet) install apache:

sudo apt-get update && apt-get install apache2

After successfully installing apache you need to install mod_proxy. This is the module that will direct traffic to your app.

sudo apt-get install libapache2-mod-proxy-html

Now you need to enable all the necessary modules.

First run sudo a2enmod. You will be asked which modules you want to enable. Just list them separated by spaces, then hit enter:

proxy proxy_balancer lbmethod_byrequests

configuration

Before you go on you can check out this guide on how apache configuration works.

In your configuration file, within the <VirtualHost> tag add the following:

ProxyPreserveHost On  
  <Proxy balancer://hotcluster>
    BalancerMember http://FIRST-INSTANCE timeout=15 retry=300
    BalancerMember http://SECOND-INSTANCE status=+H
  </Proxy>
  ProxyPass / balancer://hotcluster/

You can add as many BalancerMembers as you like, and apache will balance incoming requests among them.

Note the status=+H after the second instance address. It means that only if all other members are unavailable will this member get the traffic. This is useful if you want to set up a backup server in case your main server fails.

There you have it, a happily balanced system.


I am also on twitter, see you there.
@fonorobert