Load-balancing Tomcats using Apache Web Server.

My paid job required me to setup a load balanced system consisted of 2 tomcat servers and 1 Apache Web Server.  The requirement was simple:

  1. There were 3 machines (1 for Apache and 2 for tomcat).
  2. Incoming traffic went to Apache and then forwarded to the tomcats.
  3. There were no need to maintain the sessions.  Round robin could be used for load balancing.
  4. The setup should work as a HA: If one tomcat went down, all traffic should go to the working instance.

Make sure both Tomcats and Apache web servers are working fine and they can `talk’ to each other.  Then, just add the following into the Apache web server’s configuration file:

# Load all required modules.
LoadModule proxy_module          /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module     /usr/lib/apache2/modules/mod_proxy_http.so
LoadModule proxy_ajp_module      /usr/lib/apache2/modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module /usr/lib/apache2/modules/mod_proxy_balancer.so
LoadModule status_module         /usr/lib/apache2/modules/mod_status.so

# Tomcat must reply within 60 seconds or the connection will timeout.
# All incoming traffic with the URL ending with `/myservice' will be
# sent to one of the two tomcats.
ProxyTimeout        60
ProxyPass           /myservice   balancer://tomcatcluster
ProxyPassReverse    /myservice   balancer://tomcatcluster

# Apache talks to Tomcat using AJP (or commented HTTP) protocol.
# `loadfactor' determines the load distribution for the members.
# Use `ping' to test whether the member is up before sending the request.
<Proxy balancer://tomcatcluster>
    BalancerMember  ajp://tomcat1_ip:8009/myservice loadfactor=1 ping=100
    BalancerMember  ajp://tomcat2_ip:8009/myservice loadfactor=1 ping=100
    # BalancerMember  http://tomcat1_ip:8080/myservice loadfactor=1 ping=100
    # BalancerMember  http://tomcat2_ip:8080/myservice loadfactor=1 ping=100

# Point your browser at http://localhost/balancer-manager from the machine
# running the Apache Web Server to access the load balancer manager.
<Location /balancer-manager>
    SetHandler balancer-manager
    Order      Deny,Allow
    Allow from localhost ip6-localhost

Restart the Apache Web Server and start sending traffic to it.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: