Load-balancing Tomcats using Apache Web Server.
November 2, 2011
Posted by on
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:
- There were 3 machines (1 for Apache and 2 for tomcat).
- Incoming traffic went to Apache and then forwarded to the tomcats.
- There were no need to maintain the sessions. Round robin could be used for load balancing.
- 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.
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.
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.
Allow from localhost ip6-localhost
Restart the Apache Web Server and start sending traffic to it.