October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Tomcat clustering and failover

 

In this post I will describe how to implement a functional Tomcat cluster with load balancing and failover

I did a great deal of research trying to get this environment working. There are a number of good tutorials for simple Tomcat clustering and load balancing. I was unable to find an example that was complete which provided a load balanced solution with failover.

Example 1 shows load balancing with a single server.

Example 2 shows load balancing with a multiple Tomcat servers.

Example 3 shows load balancing with failover which is described in this post.

The first step in setting up a cluster like we have above is to insure that multicast works in your environment. In order to check for multicast support on Linux first check to see if your kernel was compiled with multicast support by trying the following:

cat proc/net/dev_mcast

If the file doesn’t exist a kernel recompile is in order, the instructions for this are outside the scope of this post. Assuming we have kernel multicast support we must check that it is working. This can be done with a simple java utility contained in the zipfile multicasttest.zip. There are 2 classes in the zipfile, TestServer and TestClient first start the test client on all nodes in the cluster, then run TestServer on one of the nodes with the number of messages to send as a count. This will send a message every 3 seconds until the message count is reached. All of the clients should report each message in the form “Received: Message 1 of 10? and the server will display “Sending message 1?. If each of the clients report the messages your clustering should work.

Next configure your Tomcat servers for clustering and failover. Samples of the configuration file shown below are contained in the zipfile SampleConfig.zip.

Add the following block in your [TOMCAT]/conf/server.xml:

 

 

<!– mod_jk ajp protocol connector –>

<Connector port=”8009? protocol=”AJP/1.3? redirectPort=”8443? server=”Apache” />

 

<!-- Engine with clustering support set jvmRoute to "jvm"+id unique to tomcat instance -->

 

<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm2">

 

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">

 

<Manager className="org.apache.catalina.ha.session.DeltaManager" expireSessionsOnShutdown="false" notifyListenersOnReplication="true"/>

 

 

 

 

<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<!--Membership address and port should be set to the proper
value for the environment -->
<Membership className="org.apache.catalina.tribes.membership.McastService"
address="228.0.0.4" port="45564" frequency="500" dropTime="3000"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
</Sender>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="auto" port="4000" autoBind="100" selectorTimeout="5000" maxThreads="6"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=""/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>

 

 

 

 

Create an [APACHE]/conf/httpd.conf:
Include conf/mod_jk.conf

Save the following to [APACHE]/conf/mod_jk.conf and enter the following:

LoadModule jk_module modules/mod_jk.so

# Specify path to worker configuration file
JkWorkersFile conf/workers.properties

# Configure logging and memory
JkShmFile logs/mod_jk.shm
JkLogFile logs/mod_jk.log
JkLogLevel debug

# Configure monitoring
JkMount /jkmanager/* jkstatus

<Location /jkmanager>
Order deny,allow
Deny from all
Allow from localhost
</Location>

# Configure applications
JkMount /myApp/* loadbalancer
JkMount /myOtherApp/* loadbalancer

 

Create an [APACHE]/conf/workers.properties and enter the following:

# Define worker names
worker.list=worker1, worker2, jkstatus, loadbalancer

# Create virtual workers
worker.jkstatus.type=status
worker.loadbalancer.type=lb

# Declare Tomcat server worker 1 on the localhost
worker.worker1.type=ajp13
worker.worker1.distance=1
worker.worker1.port=8009
worker.worker1.host=localhost

# Declare Tomcat server worker 2 on the remote host
# setting the host value to the remote ip address
worker.worker2.type=ajp13
worker.worker2.distance=10
worker.worker2.port=8009
worker.worker2.host=XXX.XXX.XXX.XXX #IP address of remote server

# Associate real workers with virtual LoadBalancer worker
worker.loadbalancer.balanced_workers=worker1, worker2
worker.loadbalancer.sticky_session=1

You should now be able to start your Apache and Tomcat instances and have clustering and failover.

For this example Tomcat 6.0.29 was used with Apache 2.2 and mod_jk 1.2.31.

 

 

 

Clustering allows us to run an application on several parallel servers (i.e. cluster nodes). The load is distributed across different servers, and even if any of the servers fails the application is still accessible via other cluster nodes. Clustering is crucial for scalable enterprise applications, as you can improve performance by simply adding more nodes to the cluster.

This document provides step by step instructions for configuring Apache server which handles  
request for static contents and delegates request for dynamic pages (i.e. JSP or Servlet) to two  instances of Tomcat server using JK Connectors.

  • Installation of Apache Server
  • Setting up tomcat instances 
  • Configuration of Clustering for tomcat instances with JK Connectors 
Installation of Apache Server

Download windows installer for Apache Server 2.0.63 from http://httpd.apache.org/download.cgi and install the same into C:\Program Files\Apache 
Software Foundation.

Setting up tomcat instances

Download apache-tomcat-6.0.20 from http://tomcat.apache.org. Create 3 instances of tomcat named tomcatA, tomcatB with following configuration in conf/server.xml.

Uncomment the following entry in server.xml in all the instances of tomcat.

<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->

 

Define the HTTP, AJP Connector, Shutdown ports for all the tomcat instances as below,

 

tomcatA

HTTP 8081
Shutdown 8105
AJP Connector 8109
jvmRoute tomcatA

 

tomcatB

HTTP 8082
Shutdown 8205
AJP Connector 8209
jvmRoute tomcatB

 

Deploying web application in all tomcat instances:

 

Deploy the Hello world JSP web application into all the tomcat instances, Make your HelloWorld.jsp with following content to feel the load balancing and session replication,

 

tomcatA – hello.jsp

 

<%
session.setAttribute(“name” , “bala”);
%>
From tomcatA - Name from session - <%= session.getAttribute(“name”); %>
Session ID - <%= session.getID() %>

 

tomcatB – hello.jsp

 

From tomcatB - Name from session - <%= session.getAttribute(“name”); %>
Session ID - <%= session.getID() %>

 

<distributable/> tag should be defined in web.xml of your application, so that session replication will be supported by the web container.

 

web.xml

 

<webapp>

..
<distributable/>
..
..
</webapp>

 

Configuring JK Connector for routing request to Tomcat from Apache Server:

 

Download JK connector 1.2.8 from http://tomcat.apache.org/connectors-doc and place mod_jk-1.2.28-httpd-2.2.3.so in modules/ directory of Apache server.

 

Add following configuration to httpd.conf file of Apache server,

 

LoadModule jk_module modules/mod_jk-1.2.28-httpd-2.2.3.so
JkWorkersFile C:\cluster\workers.properties
JkLogFile "logs/mod_jk.log"
JkLogLevel trace
JkMount /cluster loadbalancer
JkMount /cluster/* loadbalancer

 

workers.properties should have the details about the tomcat instances which we have created as below,

 

workers.tomcat_home=/tomcatA
workers.java_home=$JAVA_HOME
ps=/
worker.list=tomcatA,tomcatB,loadbalancer
worker.tomcatA.port=8109
worker.tomcatA.host=localhost
worker.tomcatA.type=ajp13
worker.tomcatA.lbfactor=1
worker.tomcatB.port=8209
worker.tomcatB.host=localhost
worker.tomcatB.type=ajp13
worker.tomcatB.lbfactor=1
worker.loadbalancer.type=lb
worker.loadbalancer.balanced_workers=tomcatA,tomcatB
worker.loadbalancer.sticky_session=1

 

Now restart the Apache Server, TomcatA and TomcatB instances and access the HelloWorld application via URL, http://localhost/Helloworld/hello.jsp.

 

Now you can see the session created by tomcatA will available in tomcatB also when accessing

the above URL repeatedly.

Implement a Dynamic Tomcat Cluster with Mod_Cluster

Apache Tomcat, the open source Web application server, hosts an estimated 70 percent of small Java Web applications. However Tomcat can become overburdened when faced with spikes in user requests. One way to ensure that your Tomcat servers are utilized to their maximum capacity is to connect and cluster them in a single environment and then load balance the servers in that environment. The mod_cluster module enables you to do just that: connect multiple servers and perform load balancing. Using mod_cluster, you can use a single IP address to connect multiple deployed Web servers.

Load balancing is basically defined as connectivity with one or more Web application servers for handling increasing user loads. Apart from checking the connected server load, load balancing also helps to route user requests to free servers, thereby lessening the burden on loaded servers. The two supported cluster modes are single-cluster mode and dynamic-cluster mode, with single-cluster mode being the default. In single-cluster mode, all server machines are used even when very few users access the Web application, which is a waste of network, power and server resources. If the number of users increases, then the response of the application will go down, because fewer servers are used to serve the request.

By setting up a dynamic Tomcat cluster environment where you can add or remove servers dynamically based on the user load, you can implement a sort of Tomcat platform as a service (PaaS) that ably addresses the problem of resource utilization. The following figure illustrates the Tomcat PaaS architecture.

This solution will improve resource utilization while load balancing the environment. In this tutorial, we explain how to implement a dynamic Tomcat cluster with mod_cluster.

The Case for Mod_cluster

Mod_cluster is an httpd-based load balancer that uses a communication channel to forward requests from httpd to a set of application server nodes. Unlike mod_jk and mod_proxy, mod_cluster utilizes an additional connection between the application server nodes and httpd. The application server nodes use this connection to send server-side load balance factors and lifecycle events back to httpd via the Mod-Cluster Management Protocol (MCMP), a custom set of HTTP methods. With this additional feedback channel, mod_cluster can provide more intelligence and granularity than many other load-balancing alternatives, as well as the following advantages.

  • Dynamic configuration of httpd workers
  • Server-side load balance factor calculation
  • Fine-grained Web app lifecycle control
  • AJP is optional

 

Mod_Cluster Configuration in Apache Web Server

Add the following modules in your Apache Web Server to enable clustering and load balancing:

  1. mod_proxy_ajp
  2. mod_proxy
  3. mod_proxy_cluster
  4. mod_manager
  5. mod_advertise
  6. mod_slotmem

The Apache Web Server has an httpd.conf file. This file contains loading module, cluster, load balancer, host, and log format configuration details. The configuration data below needs to be added for enabling clustering and load balancing in the Apache Web Server. Also below is the required module for enabling clustering and load balancing.

Configuration data for load module

LoadModule proxy_module modules/mod_proxy.so 
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule slotmem_module modules/mod_slotmem.so
LoadModule manager_module modules/mod_manager.so
LoadModule proxy_cluster_module modules/mod_proxy_cluster.so
LoadModule advertise_module modules/mod_advertise.so

Configuration for mod_cluster and load balancer

# MOD_CLUSTER configuration details 
<IfModule manager_module>
Listen *:9999
ManagerBalancerName paascluster
<VirtualHost *:9999>
<Directory />  
Order deny,allow  
Deny from none  
Allow from all
</Directory>
KeepAliveTimeout 300
MaxKeepAliveRequests 0
ServerAdvertise on
http://localhost:9999
AdvertiseFrequency 5
<Location /mod_cluster_paas>
SetHandler mod_cluster-manager
Order deny,allow
Deny from none
Allow from all
</Location>
</VirtualHost>
</IfModule>

After adding the above configuration in the httpd.conf file, you have to restart Apache Web Server. To verify the clustering and load balancing, follow these steps:

  1. Open a Web browser.
  2. Type this address: http://localhost:9999/mod_cluster_paas

If the details below appear in the browser, then the cluster and load balancer are enabled.

 

Dynamic Clustering in Tomcat

To enable clustering in Tomcat, add the following JAR in the lib folder:

Jar name: Mod_cluster.1.1.3.jar : This jar is provided by jboss Jar download URL : http://www.jboss.org/mod_cluster/downloads/1-1-3

Using the above JAR connects Apache Web Server with Tomcat Application Server via AJP.

Below is the Apache Application Server configuration for clustering and load balancing with Apache Web Server:

  1. Add the below listener entry on top of the server tag in Apache Application Server’s server.xmlfile.
    <Listener className="org.jboss.modcluster.catalina.ModClusterListener" advertise="true" proxyList="localhost:9999"/>
  2. Enable AJP connector tag in the server.xmlfile.
    <Connector protocol="AJP/1.3" port="8669" redirectPort="8443"/>
  3. Add the jvmRoute name in the engine tag in server.xml. This name is useful for identifying the system in the cluster and gives a different name to each Tomcat application server.
    <Engine name="jboss.web" defaultHost="localhost" jvmRoute="node1">
  4. Add cluster and channel details to the engine tag in the server.xml file. This configuration is used for enabling different groups of clusters in Apache Web Server. The membershiptag is used for setting the multicast IP for different groups of clusters based on multicast IP address.
    <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="6">
    <Manager className="org.apache.catalina.ha.session.BackupManager" expireSessionsOnShutdown="false" notifyListenersOnReplication="true" mapSendOptions="6"/>
    <Channel className="org.apache.catalina.tribes.group.GroupChannel">
    <Membership className="org.apache.catalina.tribes.membership.McastService" address="228.0.0.4" port="45564" frequency="500" dropTime="3000"/>
    <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver" address="auto" port="5000" selectorTimeout="100" maxThreads="6"/>
    <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
    <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
    </Sender>
    <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
    <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
    <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
    </Channel>
    <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer" tempDir="/tmp/war-temp/" deployDir="/tmp/war-deploy/" watchDir="/tmp/war-listen/" watchEnabled="false"/>
    <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
    </Cluster>

 

Dynamic Clustering in Apache Application Server

To enable dynamic clustering in Apache Application Server, JMS is required. Java Messaging System (JMS) communicates with the server through messaging and is used for configuring server properties dynamically without restarting the server system. The following code snippet gives the option for enabling clustering with Apache Web Server:

Registry registry =Registry.getRegistry(); MBeanServer mBeanServer = Registry.getRegistry().getServer() String beans[]=registry.findManagedBeans(); ManagedBean mbeanProxy = registry.findManagedBean("org.jboss.modcluster.ModClusterListener"); ClassNameMBean mbean= new ClassNameMBean(); mbean.setManagedBean(mbeanProxy); OperationInfo info[] = mbeanProxy.getOperations() ; for(int i=0;i-1){ OperationInfo opinfo=info[i]; ParameterInfo param[]=opinfo.getSignature(); Object params[] = {"localhost",9999}; String sig[] = {"java.lang.String","int"}; mbeanProxy.getInvoke("addProxy",params,sig,mbean,null); } } 

Dynamically Deploying/Undeploying Apps in Tomcat

The following code snippet is for deploying Web applications in Tomcat:

DeployTask dt = new DeployTask(); dt.setUrl("http://localhost:8080/manager"); dt.setUsername("admin"); dt.setPassword("admin"); dt.setPath("/examples11"); dt.setWar("d:/cas-cert/examples1/examples11.war"); dt.execute(); 

The following code snippet is for undeploying Web applications in Tomcat.

UndeployTask udt = new UndeployTask(); udt.setUrl("http://localhost:8080/manager"); udt.setUsername("admin"); udt.setPassword("admin"); //http://localhost:8080/manager/undeploy?path=/examples11 udt.setPath("/examples11"); udt.execute(); : : : : : 

 

 

 

Crazy way to do JBOSS and Tomcat Loadbalancing :)

Crazy way to do JBOSS and Tomcat Loadbalancing

Mod clusteris an http based load balancer which greatly simplify the setup of an http cluster. It ships as a set of modules which need to be installed on the httpd server and a Service Archive Library (.sar) which needs to be deployed on JBoss AS (It is built-in in JBoss AS 6/7).

Compared with the former mod_jk, the new mod_cluster has the great advantage to accept a dynamic configuration of httpd workers. This can be done through an advertise mechanism where all httpd workers communicate lifecycle events (like startup or shutdown) thus leveraging dynamic configuration of nodes.

 
 
 
What is mod_cluster?
• Set of modules for Apache httpd and a Tomcat-based
webserver
• Apache httpd-2.2.8+
• JBoss AS 5.0.0.GA+, JBoss Web 2.1.1+, Tomcat 6
• Allows httpd to act as a load balancer in front of Tomcatbased
web servers
• similar to mod_jk and mod_proxy_balancer
• JBoss.org project
• http://www.jboss.org/mod_cluster
• LGPL
• Current release is 1.0.0.Beta4
• First Release Candidate expected this month
 

User requests proxied
to backend server
using AJP
• HTTP/HTTPS also
supported
• Request handling on
Java side not affected by
mod_cluster
• Key difference – back
channel from backend
server to httpd
• Lifecycle information
• Load balancing
information
• Uses HTTP or HTTPs

 

1.mod_cluster Profile

        mod_cluster mod_jk, mod_proxy similar httpd-based load balancing project to a proxy request to based on the Tomcat web server cluster (support any independent Tomcat, separate JBoss Web or JBoss AS embedded JBoss Web). the distinction mod_cluster mod_jk and mod_proxy, mod_cluster provide background channel between a web server and httpd server. web server using a background channel httpd end of the current status information.
2.mod_cluster advantages

Able to dynamically configure the httpd tasks: httpd-side without the need to configure each server’s IP and port, auto-discovery mechanism.
2. Provide server-side load weighting factor calculated automatically by the web server side: the server node CPU, memory, jvm stack, database connection pool, thread pool usage, calculate the load weight, can reduce the pressure of the httpd server side
3 the better granularity web application management (event notification mechanism): a web-app deployment / unloading will be notified to the httpd server, so httpd server it would not forward the request to a solution to deploy the application Server, to reduce the time expenditure. Disable and Enable operation and detected the server.
Support AJP, HTTP, HTTPS protocols

3.mod_cluster necessary condition

    * Httpd-2.2.8 +
    * JBoss AS 5.0.0 + or JBossWeb 2.1.1 +
    * Other servers can not be used directly, the need to transform

4.mod_cluster works
5.mod_cluster configure load balancing example with Tomcat

Here only a brief description of mod_cluster + tomcat + ajp protocol + session non-pro + load-demo.war scene detailed installation and configuration refer to the official document: http://docs.jboss.org/mod_cluster/1.1.0/html_single/ # Quick_Start_Guide.
5.1 install httpd server (windows, installing a new the httpd can also upgrade existing httpd, here is the installation of a new httpd)

5.1.1 Download

http://www.jboss.org/mod_cluster/downloads/1-1-0.html download the latest mod_cluster 1.1.0.Final zip bundles

5.1.2 extracting installer

Decompression mod_cluster-1.1.0.Final-windows-x86-ssl.zip, unpacked, there will be a httpd-2.2 directory, execute the its next bin directory under the installation configuration script installconf.bat
5.2 to configure the httpd server

This version of httpd is completely bound mod_cluster component, so long as to httpd_home / conf / httpd.conf to add some mod_cluster load balancing configuration, content and brief description follows (if installed upgrade existing httpd configuration is different, refer to the official documentation for details.):

The Xml code Favorites code

    # For mod_cluster
    # Load necessary. So modules
    LoadModule proxy_module modules / mod_proxy.so
    LoadModule proxy_ajp_module modules / mod_proxy_ajp.so
    LoadModule slotmem_module modules / mod_slotmem.so
    LoadModule manager_module modules / mod_manager.so
    LoadModule proxy_cluster_module modules / mod_proxy_cluster.so
    LoadModule advertise_module modules / mod_advertise.so
      
       
    # Set the listener host IP and port
    Listen 192.168.11.24:6666
       
    # Configure virtual host
      
    <VirtualHost 192.168.11.24:6666>
       
      <Directory />
        Order deny, allow
        Deny from all
        # Allow from 127.0.0.1
        Allow from all
      </ Directory>
       
      KeepAliveTimeout 60
      MaxKeepAliveRequests 0
       
    # Declare a load balancer
      ManagerBalancerName mycluster
      AdvertiseFrequency 5
      ServerAdvertise On
      AllowDisplay On
    </ VirtualHost>
       
    # Set the proxy forwards all requests are forwarded to the mycluster load balancer
    ProxyPass / balancer :/ / mycluster /
       
    # The configuration mod_cluster-manager, so that it can access the management page to mod_cluster-manager
    <Location /mod_cluster-manager>
    SetHandler mod_cluster-manager
    Order Deny, Allow
    Deny from all
    Allow from all
    </ Location>

5.3 Installation of the server-side components

http://www.jboss.org/mod_cluster/downloads/1-1-0.html download the latest java mod_cluster 1.1.0.Final, under JBossWeb-Tomcat jar package decompression after copy to tomcat_home / lib.
5.4 Configuring the server-side

Modify tomcat_home / conf / server.xml:
The Xml code Favorites code

    <Listener ClassName=”org.jboss.modcluster.catalina.ModClusterListener” advertise=”true”/> / / add this line configuration
      
     <Engine Name=”Catalina” defaultHost=”localhost” jvmRoute=”tomcat1″> / / in this line configuration add jvmRoute attributes

5.5 visit mod_cluster-manager to view the configuration

Instructions in accordance with 5.3, 5.4, multiple tomcat installed and configured the server-side components, to Note jvmRoute to be configured into different identity. Start the Tomcat Server and httpd, visit the apache mod_cluster-manager page: http://ip:port/mod_cluster-manager <! – @ Import url (scrollbar.css); -> page display mod_cluster to some state information and monitored web server, and each server application, and can Disable and Enable operation of these applications can be dynamically updated in the page, and start and stop the web server and the web-app deployment / uninstall. As shown below:
[Click to view original size picture]

Note: If the page does not display status information mod_cluster Please check whether the set <VirtualHost> </ VirtualHost> AllowDisplay On
5.6 load-demo.war test

the demo directory http://www.jboss.org/mod_cluster/downloads/1-0-3-GA download java mod_cluster 1.0.3.GA Extract Extract demo / server / load-demo.war Executive demo \ client \ the run-demo.bat will pop up a similar LoadRunner graphical interface tools (see the specific use of the official documentation http://docs.jboss.org/mod_cluster/1.1.0/ deploy to each the Tomcat Server html / demo.html), from the test results, apache simulated uniform requests forwarded to the various Tomcat Server. As shown below:

Special Note: Do not use the load-demo.war java mod_cluster 1.1.0.Final this version of the bug the load-demo.war have impossible, I spent a lot of time, it is recommended to use java mod_cluster 1.0.3. GA version of the demo.

6 a app-server with mod_cluster integration needs to do the work

1. To configure a Listerner components.

mod_cluster background channel between the web server and httpd server the background channel need server-side web server to placement a Listerner components (such as tomcat server to need a ModClusterListener components). This component is responsible to interact with the httpd server: for example, to calculate the load weight factor web-app lifecycle status information is pushed to the http server. Now tomcat and jboss provide the configured in server.xml Listener:

The Xml code Favorites code

    <Listener ClassName=”org.jboss.modcluster.catalina.ModClusterListener” advertise=”true”/>

TongWeb configuration file and management console did not to provide configure the Listener place, but com.tongweb.web.core.core.StandardServer in providing addLifecycleListener () method can be added lifecycle Listener.

2. Transformation mod_cluster provide the server-side components

Rely on some source of tomcat or jboss simple to view the server-side components provided mod_cluster jar package source code, which is part of the source code example, ModClusterListener has some dependencies:

 

 

Advantages of mod_cluster vs mod_jk

Hello All,
       Maximum times I have heard about mod_jk. So, I was a little bit confused that which one better and better performer than others. So I have just searched and found really good and interesting answer and sharing this as below. So if anyone knows something interesting or new about the comparison of these both, then please share your thoughts.
 

Overview

mod_cluster is an httpd-based load balancer. Like mod_jk and mod_proxy, mod_cluster uses a communication channel to forward requests from httpd to one of a set of application server nodes. Unlike mod_jk and mod_proxy, mod_cluster leverages an additional connection between the application server nodes and httpd. The application server nodes use this connection to transmit server-side load balance factors and lifecycle events back to httpd via a custom set of HTTP methods, affectionately called the Mod-Cluster Management Protocol (MCMP). This additional feedback channel allows mod_cluster to offer a level of intelligence and granularity not found in other load balancing solutions.
Within httpd, mod_cluster is implemented as a set of modules for httpd with mod_proxy enabled. Much of the logic comes from mod_proxy, e.g. mod_proxy_ajp provides all the AJP logic needed by mod_cluster.
 

 

Advantages

mod_cluster boasts the following advantages over other httpd-based load balancers:

Dynamic configuration of httpd workers
Traditional httpd-based load balancers require explicit configuration of the workers available to a proxy. In mod_cluster, the bulk of the proxy’s configuration resides on the application servers. The set of proxies to which an application server will communicate is determined either by a static list or using dynamic discovery via the advertise mechanism. The application server relays lifecycle events (e.g. server startup/shutdown) to the proxies allowing them to effectively auto-configure themselves. Notably, the graceful shutdown of a server will not result in a failover response by a proxy, as is the case with traditional httpd-based load balancers.
Server-side load balance factor calculation
In contrast with traditional httpd-based load balancers, mod_cluster uses load balance factors calculated and provided by the application servers, rather than computing these in the proxy. Consequently, mod_cluster offers a more robust and accurate set of load metrics than is available from the proxy. (see Load Metrics for more)
Fine grained web-app lifecycle control
Traditional httpd-based load balancers do not handle web application undeployments particularly well. From the proxy’s perspective requests to an undeployed web application are indistinguishable from a request for an non-existent resource, and will result in 404 errors. In mod_cluster, each server forwards any web application context lifecycle events (e.g. web-app deploy/undeploy) to the proxy informing it to start/stop routing requests for a given context to that server.
AJP is optional
Unlike mod_jk, mod_cluster does not require AJP. httpd connections to application server nodes can use HTTP, HTTPS, or AJP.

How to add Gnome to a CentOS 6 minimal install

I have been using the minimal iso (CentOS-6.0-x86_64-minimal.iso) to install CentOS 6. I wanted to add a GUI to my vm, but I could not find easy documentation showing how to add a GUI, or Gnome in this case, to a CentOS 6 minimal install. I was not looking for the smallest X windows install, I was just trying to get the Desktop to function like it would as if I installed from the full DVD.

There are a lot of results of how to do this, but things have been renamed in CentOS 6, so that made it more difficult to figure out. Also, there are “Short Names” and I am assuming they are called “Long Names” associated with a yum groupinstall, which added to my confusion.

To add Gnome/GUI to a minimal CentOS 6 install run (short name version):

yum groupinstall basic-desktop desktop-platform x11 fonts

And the “long name” version:

yum groupinstall "Desktop" "Desktop Platform" "X Window System" "Fonts"

Hope that helps someone or at least help me to remember.

Windows Azure Virtual Machines IIS 7.5 FTP

When enabled on the Windows Azure Virtual Machines Windows Server 2008 R2 virtual machine, most users will need to pass the files, programs, etc. on the needs of the cloud. Next, describes how Windows Server 2008 R2 in Windows Azure Virtual Machines enable the FTP file transfer service.

To demonstrate, we establish the named MyFTP Windows Server 2008 R2 virtual machine.

 

 

And external DNS name of this virtual machine is set to the My-FTP.cloudapp.net.

When after the start of the virtual machine, enter the Windows Server 2008 R2 virtual machines connected through Remote Desktop Remote Desktop. Just installed is completed, the entire Windows Server 2008 R2 without any installation roles (Role), as shown in the diagram below we can in the Server Manager, click Add Roles ready to add the new role.

 

Select the Figure marked Web Server (IIS), Microsoft’s IIS 7.5 has built-in FTP service, click after pressing the Next button.

 

 

 

IIS 7.5 includes a considerable number of additional services, the Figure marked at we must check install FTP Server add service finished, press the Next button.

At this point Windows Server 2008 R2 will begin the installation of IIS 7.5 FTP Server If the installation goes well we will see the following figure like the screen, you can press the Close button when we see a message that indicates the installation was successful.

IIS installation is complete, as shown on the left pane, expand the Server Manager, click the Web Server IIS management screen.

Before setting the FTP, we need to know about FTP connection mode, the vast majority of FTP file transfer software, Passive Mode, and when. FTP client software to connect to the FTP Server TCP Port 21 to request a connection, and the completion of the command the establishment of the channel. When both ends of the need to transfer data, FTP client software will send a PASV command through command channels to the FTP Server Passive Mode transmission mode requested access. FTP Server will then randomly select a TCP port (PS1) in the following figure, through command channels to tell the FTP client software, FTP client after just told FTP Server TCP Port (PS1) in the following figure to connect to FTP Server setting up a data channel (Data Channel). When all goes well, soon began to transfer files via the data channel (Data Channel).

 

Windows Azure foreign all network traffic will be through the load balancer (Load Balancer) virtual machine all external connections are required in the Windows Azure Management Interface add Endpoint current Windows Azure does not allow to set for some interval of TCP / UDP Port, only one add Endpoint, and a maximum of only 25 external Endpoint let Passive Mode FTP service to work properly, in addition, we also must limit shrinkage data channel (Data add to a TCP 21 Port Endpoint Channel) required TCP Port, or FTP Server a wide range of random establishment of the data channel TCP Port Windows Azure load balancing difficult operation.

Therefore, we next want to FTP Passive Mode will use the data channel TCP Port range is reduced limit of two TCP Port (Data Channel), add Endpoint order after the Windows Azure management interface. Please pay special attention to the left pane of the need to click on the correct FTP firewall settings, we can through the Server Manager, click the the following figure MyFTP server level.

Take over the data channel (Data Channel) TCP Port range shown for 5432-5433, complete the Apply button and then press the right pane. Accomplish this setup FTP Server will only be between two TCP Port randomly selected to data channel (Data Channel). The following figure in the External IP Address can be left blank.

Next, we can add FTP Site, as shown in the diagram below in the Connection pane, click Sites Right-click and select add new FTP Site.

Then we set the name of the FTP Site for Temp Files Upload, and physical folder set in the D: \ InstallFiles again remind the user in normal applications, FTP entity data folder must be built on a new virtual disk, do not the the FTP folder settings in the D: drive. Windows Azure Virtual Machines service each virtual machine’s C: drive by default in order to increase efficiency, will read and write to the disk cache turned on, open the write cache, FTP upload files in C : risk of missing write data on the disk, FTP file placed in temporary use D: drive is dangerous, the D: drive is the local hard drive, there is no automatic data backup one-third, especially when the virtual machine restart D: the contents of the disk will be lost, therefore only as a temporary use. In order to save space, this time we set up an FTP only to temporarily upload files to this virtual machine for software installation, FTP entity folder set in the D: drive, FTP entity folder must be set in the real application a new virtual disk, never set in the C: drive or D: drive.

Setting up the entity folder, as shown below do not need to use SSL encrypted transmission, same here only the FTP install the demonstration, please pay attention to the security problems of data transmission in real applications.

Next set to allow anonymous users (Anonymous) can log on to read and write to the file, the same in this only the FTP install the demonstration, in real applications, please pay attention to the setting of user access rights. After pressing the Finish button to complete the temporary file upload FTP Site.

Set properly named Temp Files Upload FTP Site, we turn to face a new problem, FTP Passive mode in the establishment of the data channel, we need to inform this virtual machine’s external IP Address FTP Server, in order to avoid FTP internal IPv4 address to an FTP client, which will cause the Windows Azure in the process of the establishment of the data channel in the door. As shown in the Connections pane, click Temp Files Upload FTP Site, and then in the right pane of the FTP FTP Site level firewall settings.

We can check in the Windows Azure Management Portal Foreign Public Virtual IP (VIP) 168.63.133.209.

Back to the Server Manager, the following diagram fill in this virtual machine within the External IP Address of Firewall the Foreign the IP Address: 168.63.133.209 finished, press the right side of the Apply button.

At this point, the FTP Server installation and configuration has been completed, these settings action is completed within IIS Manager, but all relevant firewall settings also affect to the system, it is recommended to restart this virtual machine, confirm that the entry into force of the relevant firewall settings missed this little trick wasted three hours of holiday time. The next we want to FTP used TCP Port setting in the Windows Azure Endpoint. A Windows Server 2008 R2 virtual machine just created, for safety reasons, only the Remote Desktop Remote Desktop Endpint has been established. + Button in the case in the following figure can increase other Endpoint.

Increase the new Endpoint picture, select Add endpoint.

Next most important added FTP Endpoint is TCP Port 21, the FTP command channel used in the TCP Port.

Then follow the same method, the FTP data channels need the TCP Port 5432 TCP Port 5433 into Endpoint after you’re done.

Next, I use free FTP software FileZilla to test the connection, as shown in the following figure like the type my-ftp.cloudapp.net Domain Name press the Connect button to connect to the cloud.

For Windows Server FTP operation and settings, you can refer to http://learn.iis.net/page.aspx/309/configuring-ftp-firewall-settings-in-iis-7/

HTTP Load Balancing using Application Request Routing – IIS 7

Overview

This topic leads the reader through the steps to configure Application Request Routing to load balance HTTP requests to achieve high availability and scalability.  The walkthrough also highlights a couple of core features on how Application Request Routing monitors the health of the content servers and affinitizes requests from a client to a content server.

Goal

To load balance HTTP requests across several content servers using Application Request Routing, as shown below:

Prerequisites

This walkthrough requires the following prerequisites:

  • IIS 7.0 or above on Windows 2008 (any SKU) or newer.
  • Microsoft Application Request Routing Version 1 and dependent modules.
  • Minimum of two content servers with working sites and applications.

If Application Request Routing Version 1 has not been installed, it is available for download at:

  • Microsoft Application Request Routing Version 1 for IIS 7 (x86) here.
  • Microsoft Application Request Routing Version 1 for IIS 7 (x64) here.

Follow the steps outlined in this document to install Application Request Routing. 

Another prerequisite is that the reader has defined and configured a server farm using the steps outlined in Define and Configure an Application Request Routing (ARR) Server Group.

Step 1 – Verify URL rewrite rules

Provided that the server farm has been created using the steps outlined in Define and Configure an Application Request Routing (ARR) Server Group, the URL rewrite rules have already been created for a simple load balancing scenario.

To verify URL rewrite rules using the UI:

1.  Launch IIS Manager.

2.  Select the server farm, myServerFarm, which was created in Define and Configure an Application Request Routing (ARR) Server Group.

3.  The following icons are shown:

4.  Double-click Routing Rules.

5.  Verify that the Use URL Rewrite to inspect incoming requests checkbox is checked.

6.  SSL offloading is enabled by default.  When this feature is enabled, all communication between the ARR server and the application servers are done in clear text, even for HTTPS requests from clients to the ARR server.  When both the ARR server and the application servers are deployed within a trusted network, such as within the same datacenter, enabling SSL offloading does not sacrifice security.  Also, enabling this feature can further help to maximize the server resources on the application servers, since they do not have to spend cycles in encrypting and decrypting requests and responses.

To disable SSL offloading, uncheck the Enable SSL offloading checkbox, and then click Apply.

7.  Open a browser and send several requests to the ARR server.

8.  To verify that the requests are being load balanced equally between the application servers, select myServerFarm.  Double-click Monitoring and Management.

9.  In the dashboard view, verify that the requests are being evenly distributed.

 

To verify URL rewrite rules using the command-line:

1.  Open a command prompt with administrator privileges.

2.  Navigate to %windir%\system32\inetsrv.

3.  To verify that the URL rewrite rules have been created correctly, enter appcmd.exe list config -section:system.webServer/rewrite/globalRules.  It returns the globalRules that looks like the following:

<system.webServer>
  <rewrite>
    <globalRules>
      <rule name=”ARR_myServerFarm_loadbalance” patternSyntax=”Wildcard” stopProcessing=”true”>
        <match url=”*” />
        <conditions>
        </conditions>
        <action type=”Rewrite” url=”http://myServerFarm/{R:0}” />
      </rule>
    </globalRules>
  </rewrite>
</system.webServer>

4.  To disable SSL offloading, first remove all URL rewrite rules:

  • appcmd.exe clear config -section:system.webServer/rewrite/globalRules

     Then, create the URL rewrite rules to forward HTTPS traffic.  More specifically, with this rule, ARR forwards requests using SSL if the incoming requests are HTTPS:

  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /+”[name=’ARR_myServerFarm_loadbalance_SSL’,patternSyntax=’Wildcard’,stopProcessing=’True’]” /commit:apphost
  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /[name=’ARR_myServerFarm_loadbalance_SSL’,patternSyntax=’Wildcard’,stopProcessing=’True’].match.url:”*”  /commit:apphost
  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /+”[name=’ARR_myServerFarm_loadbalance_SSL’,patternSyntax=’Wildcard’,stopProcessing=’True’].conditions.[input='{HTTPS}’,pattern=’On’]” /commit:apphost
  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /[name=’ARR_myServerFarm_loadbalance_SSL’,patternSyntax=’Wildcard’,stopProcessing=’True’].action.type:”Rewrite” /[name=’ARR_myServerFarm_loadbalance_SSL’,patternSyntax=’Wildcard’,stopProcessing=’True’].action.url:”https://myServerFarm/{R:0}”  /commit:apphost

      Finally, create the URL rewrite rules to forward HTTP traffic in clear text to the application servers:

  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /+”[name=’ARR_myServerFarm_loadbalance’,patternSyntax=’Wildcard’,stopProcessing=’True’]” /commit:apphost
  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /[name=’ARR_myServerFarm_loadbalance’,patternSyntax=’Wildcard’,stopProcessing=’True’].match.url:”*”  /commit:apphost
  • appcmd.exe set config  -section:system.webServer/rewrite/globalRules /[name=’ARR_myServerFarm_loadbalance’,patternSyntax=’Wildcard’,stopProcessing=’True’].action.type:”Rewrite” /[name=’ARR_myServerFarm_loadbalance’,patternSyntax=’Wildcard’,stopProcessing=’True’].action.url:”http://myServerFarm/{R:0}”  /commit:apphost

5.  To verify that the URL rewrite rules have been created correctly with SSL offloading disabled, enter appcmd.exe list config -section:system.webServer/rewrite/globalRules.  It returns the globalRules that looks like the following:


<system.webServer>
  <rewrite>
    <globalRules>
      <rule name=”ARR_myServerFarm_loadbalance_SSL” patternSyntax=”Wildcard” stopProcessing=”true”>
        <match url=”*” />
        <conditions>
          <add input=”{HTTPS}” pattern=”On” />
        </conditions>
        <action type=”Rewrite” url=”https://myServerFarm/{R:0}” />
      </rule>
      <rule name=”ARR_myServerFarm_loadbalance” patternSyntax=”Wildcard” stopProcessing=”true”>
        <match url=”*” />
        <conditions>
        </conditions>
        <action type=”Rewrite” url=”http://myServerFarm/{R:0}” />
      </rule>
    </globalRules>
  </rewrite>
</system.webServer>

 

Step 2 – Configure health check monitoring

Application Request Routing monitors the health of the content servers in two ways:

  • Via the live traffic
  • Via an explicit URL testing

The live traffic testing is performed automatically by default when the requests are made to Application Request Routing.  The explicit URL testing is an additional test that can be used with the live traffic testing.  In this section, the walkthrough guides you through configuring the explicit URL testing.

To configure health check monitoring using the UI:

1.   The URL testing requires a specific URL to test.  To satisfy this requirement, use Notepad to create a text file named healthCheck.txt that contains the sentence “I am healthy.

2.   Place the healthCheck.txt file on the application servers.

3.   Verify that the healthCheck.txt is rendering properly by opening the page in a browser.

4.   In IIS Manager, select the server farm, myServerFarm.  The following icons are shown:

 

5.  Double-click Health Test.

6.  Enter http://(server name or FQDN of ARR server)/healthCheck.txt as the URL value.

7.  Enter healthy as the Response match value.  Response match is an optional test to make sure that the body of the response contains the expected string.  In this case, since healthCheck.txt contains the sentence “I am healthy.“, Response match will look for the word “healthy“.

8.  Click Apply to save the changes.

9.  To verify the functionality of health check monitoring, stop the monitored site on one of the application servers.  Since the Interval (seconds) value is set to 30 seconds, wait for 30 seconds for the next health check.

10. After waiting for 30 seconds, send several requests to the ARR server.

11. To verify that all requests are going to the healthy server(s), double-click Monitoring and Management, and then refresh the dashboard by using the F5 key.  Note that the runtime statistics have been reset.  This is by design.  You may want to send additional requests and refresh the dashboard, as needed.

12.  Health monitoring is also used to detect when an unhealthy server becomes healthy.  To verify this functionality, start the site that was stopped in Step 9.  Again, since the Interval (seconds) value is set to 30 seconds, wait for 30 seconds for the next health check.

13.  After waiting for 30 seconds, send several requests to the ARR server.

14.   To verify that the requests are distributed evenly between servers, refresh the dashboard in IIS Manager.  Note that the runtime statistics have been reset.  This is by design. You may want to send additional requests and refresh the dashboard, as needed.

 

To configure health check monitoring using the command-line:

1.  Open a command prompt with administrator privileges.

2.  Navigate to %windir%\system32\inetsrv.

3.  To set the URL to http://(server name or FQDN of ARR server)/healthCheck.txt with I am healthy. as the string to match, enter:

  • appcmd.exe set config  -section:webFarms /[name=’myServerFarm1′].applicationRequestRouting.healthCheck.url:”http://(server name or FQDN of ARR server)/healthCheck.txt ” /[name=’myServerFarm1′].applicationRequestRouting.healthCheck.responseMatch:”I am healthy.”  /commit:apphost

  

Step 3 – Configure client affinity

Application Request Routing provides a client affinity feature that maps a client to a content server behind Application Request Routing for the duration of a client session.  When this feature is enabled, the load balancing algorithm is applied only for the very first request from the client. From that point on, all subsequent requests from the same client would be routed to the same content server for the duration of the client session.  This feature is useful if the application on the content server is stateful and the client’s requests must be routed to the same content server because the session management is not centralized.

To configure client affinity using the UI:

1.  Launch IIS Manager.

2.  Select the server farm, myServerFarm, which was created in Define and Configure an Application Request Routing (ARR) Server Group.

3.  The following icons are shown:

4.  Double-click Server Affinity.

5.  To enable client affinity, check the Client affinity checkbox, and then click Apply.

Application Request Routing uses a cookie to enable client affinity.  The Cookie name will be used to set the cookie on the client.  That said, the client must accept cookies for client affinity to work properly.

6. To verify the functionality of client affinity, send several requests to the ARR server.  Refresh the dashboard in IIS Manager (Monitoring and Management).  Verify that the runtime statistics are changing for only one of the application servers to where the client is affinitized.  You may want to send additional requests and refresh the dashboard, as needed. 

 

To configure client affinity using the command-line:

1.  Open a command prompt with administrator privileges.

2.  Navigate to %windir%\system32\inetsrv.

3.  To enable client affinity, enter:

  • appcmd.exe set config  -section:webFarms /[name=’myServerFarm1′].applicationRequestRouting.affinity.useCookie:”True”  /commit:apphost

 

Step 4 – Disallow new connections

Disallowing new connections on a server is a graceful way of taking the server out of the server farm environment.  It is more meaningful when the client affinity feature is in use, because Application Request Routing will honor the existing sessions when disallowing new connections.  That is, when a client is affinitized to the server that is disallowing new connections, the client will continue to be routed to the same server and, therefore, there is no impact on the client.  However, no new clients will be routed to the server that is disallowing new connections.

To disallow new connections using the UI:

1.  Using the setup from Step 3 above, identify the server to which your client is affinitized.

2.  Select the server farm, myServerFarm, which was created in Define and Configure an Application Request Routing (ARR) Server Group.

3.  The following icons are shown:

4.  Double-click Monitoring and Management.

5.  Select the server to where your client is affinitized.  In the Actions pane, click Disallow New Connections.

6.  In the confirmation dialog box, click Yes.

7.  To verify that the requests from your clients continue to get routed to the affinitized server, which is now disallowing new connections, send several requests to the ARR server.  Refresh the dashboard in IIS Manager.  Verify that the runtime statistics are changing only for the server to where the client is affinitized.  You may want to send additional requests and refresh the dashboard, as needed.

8. To verify that new clients are not being routed to the server that is disallowing new connections, remove the cookie set by Application Request Routing by closing and restarting the browser.

9. Send several requests to the ARR server.  Refresh the dashboard in IIS Manager.  Verify that the runtime statistics are changing only for the servers that are Available.  More specifically, verify that the runtime statistics for the server that is disallowing new connections are not changed.  You may want to send additional requests and refresh the dashboard, as needed.

 

Summary

You have now successfully configured a number of settings for Application Request Routing to scale out and distribute the load evenly.  For more advanced routing capabilities using Application Request Routing, refer to Using Application Request Routing.

Apache and Tomcat With mod_jk Installation and Configuration

What is Apache Tomcat?
Apache Tomcat is the servlet container that is used in the official Reference Implementation for the Java Servlet and JavaServer Pages technologies.

Apache Tomcat powers numerous large-scale, mission-critical web applications across a diverse range of industries and organizations

What is mod_jk?

mod_jk is a replacement to the elderly mod_jserv. It is a completely new Tomcat-Apache plug-in that handles the communication between Tomcat and Apache.

Why mod_jk?

Several reasons

mod_jserv was too complex. Because it was ported from Apache/JServ, it brought with it lots of JServ specific bits that aren’t needed by Apache.

mod_jserv supported only Apache. Tomcat supports many web servers through a compatibility layer named the jk library. Supporting two different modes of work became problematic in terms of support, documentation and bug fixes. mod_jk should fix that.

The layered approach provided by the jk library makes it easier to support both Apache1.3.x and Apache2.xx.
Better support for SSL. mod_jserv couldn’t reliably identify whether a request was made via HTTP or HTTPS. mod_jk can, using the newer Ajpv13 protocol.

Apache2 Installation and Configuration

For apache2 Installation click here and we will see now some configuration

Edit /etc/apache2/apache2.conf. Change

DirectoryIndex index.html index.cgi index.pl index.php index.xhtml

to

DirectoryIndex index.html index.htm index.shtml index.cgi index.php index.php3 index.pl index.xhtml

Edit /etc/mime.types and comment out the following lines:

1
2
3
4
5
6
7
8
#application/x-httpd-php phtml pht php#application/x-httpd-php-source phps
#application/x-httpd-php3 php3#application/x-httpd-php3-preprocessed php3p
#application/x-httpd-php4 php4
Edit /etc/apache2/mods-enabled/php4.conf and comment out the following lines:
<IfModule mod_php4.c>
# AddType application/x-httpd-php .php .phtml .php3
# AddType application/x-httpd-php-source .phps
</IfModule>

Edit /etc/apache2/ports.conf and add Listen 443

1
2
Listen 80
Listen 443

Now we have to enable some Apache modules (SSL, rewrite and suexec):

1
2
3
4
#a2enmod ssl
#a2enmod rewrite
#a2enmod suexec
#a2enmod include

Restart Apache:

1
#/etc/init.d/apache2 restart

Installing JDK in Debian

In order to run Tomcat, you will need to install JDK and set the JAVA_HOME environment variable to identify the location of the JDK environment on your system.

1. You can download JDK 5.0 at http://java.sun.com/j2se/1.5.0/download.jsp.

2. Click on Download JDK 5.0 Update 6 to go to the download page.

3. Click Accept to accept the license agreement.

4. Next choose the Linux self-extracting file. This is the download for the self-extracting binary file rather than the rpm.

5. Download to your preferred download directory. Change to that directory and make it executable by executing the following command

#chmod +x jdk-1_5_0_06-linux-i586.bin

Now execute the file:

#./jdk-1_5_0_06-linux-i586.bin

You should now have a new directory called jdk1.5.0_06. Now move this directory to the location where it should be run. We chose /usr/lib/.

#mv jdk1.5.0_06 /usr/lib

Now create a symbolic link called jdk to JAVA_HOME by the following command. This allows you to easily switch back and forth between different jvms should you ever need to.

#cd /usr/lib

#ln -s jdk1.5.0_06 jdk

Now we need to set the JAVA_HOME environment variable. Add the following at the end of /etc/profile just after export PATH.

JAVA_HOME=”/usr/lib/jdk”
export JAVA_HOME

/etc/profile is executed at startup and when a user logs into the system. In order to update the environment you will need to log out and log back in to the system.

Check to make sure JAVA_HOME is defined correctly by executing the command below. This should report the location of the Java SDK which should be /usr/lib/jdk.

echo $JAVA_HOME

Installing Tomcat in Debian Linux

In this section you will download and install Apache Tomcat 5.5.16. For this particular setup, there is no need to build the package from source, we will download the binary version.

1. Download the binary version to your preferred download directory from here: http://tomcat.apache.org/download-55.cgi. Choose the tar.gz from the core section for 5.5.16.

2. Now change to that directory and extract the files using the following command:

#cd /downloads #(be sure to change to your download directory)

#unp apache-tomcat-5.5.16.tar.gz

You should now have a new directory called apache-tomcat-5.5.16. Now move this directory to the location where it should be installed. Again, We chose /usr/lib/. Note that this location will be referred to as CATALINA_HOME in the Tomcat documentation.

#mv apache-tomcat-5.5.16 /usr/lib

3. Next change to the /usr/lib/ directory.

#cd /usr/lib

4. Now create a symbolic link called apache-tomcat to the CATALINA_HOME by the following command.

#ln -s apache-tomcat-5.5.16 apache-tomcat

This will save you from having to make changes to startup and shutdown scripts each time you upgrade Tomcat and if you so desire, it also allows you to keep several versions of Tomcat on your system and easily switch amongst them.

You should now be able to start and stop Tomcat from the CATALINA_HOME/bin directory. If you are using another shell other than the bash shell you will nee to add sh to the beginning of the command. You should now be able to test that Tomcat is installed by starting it and opening yourbrowser and entering http://localhost:8080 into your browser. Port 8080 is the default port for Tomcat and can be easily changed in the /usr/lib/apache-tomcat/conf/server.xml file. (We will work with this file later on.) If you plan to access this page remotely, be sure to forward the respective port to your server’s IP address within your router. You should now see the Tomcat welcome page that contains links to Tomcat documentation as well as sample JSP/Servlet scripts. Verify that Tomcat is running by executing some of the examples found on the welcome page.

#cd /usr/lib/apache-tomcat/bin

#./startup.sh

To shutdown the server, you will need to execute the following command. Feel free to try it, but for now we will leave Tomcat running.

#./shutdown.sh

Installing and configuring mod_jk 

In order to make the connection between Tomcat and Apache, we will need to download and install mod_jk connector. You will find that the Apache documentation recommends that you install the packaged version of mod_jk if it is available for your particular Linux distribution. Many outdated resources recommend installing the mod_jk2 connector, but we have found that it has been deprecated and although mod_jk was developed before mod_jk2, it is still fully supported and is very stable.

1. Download the current source from the Apache archives:

http://archive.apache.org/dist/jakarta/tomcat-connectors/jk/source/jk-1.2.15/.

Download the jakarta-tomcat-connectors-1.2.15-src.tar.gz file to your /usr/src/ directory.

2. Change to the /usr/src directory.

#cd /usr/src

3. Next, extract the contents to create the /usr/src/jakarta-tomcat-connectors-1.2.15-src directory.

#unp jakarta-tomcat-connectors-1.2.15-src.tar.gz

4. Change to the /usr/src/jakarta-tomcat-connectors-1.2.15-src/jk/native directory.

#cd jakarta-tomcat-connectors-1.2.15-src/jk/native

5. Now you are ready to create the custom configure file for your system. Execute the following:

#./buildconf.sh

This will create a configure file in the /usr/src/jakarta-tomcat-connectors-1.2.15-src/jk/native directory.

6. Execute the following command in order to configure mod_jk for your system.
Important note: You will need to have apxs2 (APache eXtension tool) installed and configured with Apache. If you do not have it, as was my case, you can download and install the apache2-threaded-dev package (which replaced the former apache-dev package) from www.debian.org. At the time of this writing, the Debian package archive at www.debian.org was down and they referred me to their temporary site until they resolved their issues pdo.debian.net. I found the apache2-threaded-dev package and was able to install it successfully.

Be sure to include the correct location apxs2 on your system in the path of the command.

#./configure –with-apxs=/usr/bin/apxs2

7. Now build the mod_jk with the following:

#make

8. Finally, if you were successful with the previous commands, copy the newly created mod_jk.so to your Apache2 modules directory. My modules were located at /usr/lib/apache2/modules.

#cd apache-2.0

#cp /usr/src/jakarta-tomcat-connectors-1.2.15-src/jk/native/apache-2.0/mod_jk.so /usr/lib/apache2/modules

You now are ready to move to the next stage which is to begin configuring Apache and Tomcat. You can find more information about the mod_jk connector here http://tomcat.apache.org/connectors-doc/howto/apache.html.

Configuring Tomcat and Apache 

Create the workers.properties file.

Important note: Be sure to make a backup copy of your config files before modifying.
The workers.properties file contains the details about how each process is linked to Tomcat by defining workers that communicate through the ajpv13 protocol. Refer to the Workers HowTo for more detail.

1. First create the workers.properties file in your Apache2 root directory.

#touch /etc/apache2/workers.properties

2. Next, open the workers.properties file and add the following. You can find many other examples of the workers.properties file on the internet, but this is the one that I created and it seems to work fine with the other portions that have already been configured in this tutorial.

1
2
3
4
5
6
7
8
workers.tomcat_home=/usr/lib/apache-tomcat
workers.java_home=/usr/lib/jdk
ps=/
worker.list=worker1
worker.default.port=8009
worker.default.host=localhost
worker.default.type=ajp13
worker.default.lbfactor=1

3. Save and close the file.

4. Now we need to open the /etc/apache2/apache2.conf file and add the following lines at the bottom. (httpd.conf is just for backward compatibility):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so
# Where to find workers.properties
JkWorkersFile /etc/apache2/workers.properties
# Where to put jk
logsJkLogFile /var/log/apache2/mod_jk.log
# Set the jk log level
[debug/error/info]JkLogLevel info
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"
# Send servlet for context / jsp-examples to worker named worker1
JkMount /jsp-examples worker1
# Send JSPs for context /jsp-examples/* to worker named worker1
JkMount /jsp-examples/* worker1

Save and close the file.Now a final security point.

We will create a group and user tomcat tomcat like that:

#groupadd tomcat

#useradd -g tomcat tomcat

Then change the user and group of the Tomcat path:

#chown -R tomcat:tomcat /usr/lib/apache-tomcat-5.5.16

To change the password of tomcat user, with root type:

#passwd tomcat

and follow the instructions.

Then to start and stop the Tomcat server you should use the tomcat user.

#su – tomcat

Now stop and start Tomcat:

#cd /usr/lib/apache-tomcat/bin

#./shutdown.sh

#./startup.sh

And restart Apache:

#/etc/init.d/apache2 restart

Testing Your Installation

In this test, we are directing all URLs that begin with “/jsp-examples” to Tomcat.
In a real world situation, we might only direct JSPs or servlets to the JK worker.

Make sure no other server is running on the default Tomcat ports of 8005, 8009 and 8080.
Make sure no other server is running on the Apache port, which is normally 8080 or 80.

Start Tomcat first: Always start Tomcat first and then start Apache.
If you have to bounce Tomcat, remember to take down Apache first and restart it after Tomcat restarts.
Start Apache: Point your browser to http://localhost and verify that you get the default Apache page. Substitute “localhost” for the actual machine name/IP if necessary.

Point your browser to http://localhost:8080 and verify that you get the default Tomcat page.

Point your browser to http://localhost/jsp-examples/ and verify that you get the index page for the Tomcat examples.

This will be served by Apache and will indicate that you have completed your integration of Apache and Tomcat successfully.

Important References and paths

Tomcat conf

/usr/lib/apache-tomcat/conf/server.xml

Tomcat stop and start

cd /usr/lib/apache-tomcat/bin
./shutdown.sh
./startup.sh

Apache modules

/usr/lib/apache2/modules

Apache conf

/etc/apache2/workers.properties
/etc/apache2/apache2.conf
/etc/apache2/httpd.conf

Apache2

/etc/init.d/apache2 restart
/etc/init.d/apache2 stop
/etc/init.d/apache2 start

Apache-Tomcat Clustering

This parameter is the one that is taken for granted in the current era. All applications are assumed to be stable enough to work 24×7, 365 days a year. This is considered as the assumed parameter of measurement.

1). Scope

To ascertain that the parameters of speed, concurrency and stability are handled when an application is being developed, developers/designers have to work on two levels:

  • Application level
  • Server level

Application Level

This is the level where the architecture of the application is designed, the optimum software’s to be used for writing the business logic is decided and the best design is brought up to bring out the best results for all the above three parameters mentioned apart of a whole lot of others.

Server Level

This is the level where certain critical decisions are taken with respect to the server on which the application is built on. The server level decisions play a major part in obtaining the optimum results for the above parameters. Whatever is done in the application level, an incorrect decision made at the server level for make everything futile. Hence, consultants/designers have to brainstorm on various aspects to arrive at the final and optimum selection of server and the corresponding configuration to obtain the best results of speed, concurrency and stability of the web application.

In this paper, I will only be focusing on the server level decision that has to be made to achieve best results of speed, concurrency and stability. I will be comparing the pros and cons of various web servers in various measurement parameters and would highlight the implementation details for integrating Apache and Tomcat servers to achieve the maximum throughput of the above parameters for certain specific application requirements.

2). Design Intention

2.1 Design level server parameters

The main design parameters that are considered while taking server related design decisions are: –

Page Load Time

This refers to the Average Page Duration as measured with each server under an increasing load. When the load on the server is less, Tomcat outperforms WebSphere and WebLogic and is considered to be very fast. But, Tomcat performs poorly as the load increases. That is, as the number of concurrent users increase, performance comes down in the case of Tomcat. Other application servers like WebSphere and WebLogic are found to be more stable when compared to Tomcat. Tomcat typically supports around 150 concurrent users without much problem while WebSphere and WebLogic support around 400 concurrent users. This is one major reason for the architects to go for WebSphere and WebLogic when compared to Tomcat as it tends to become unstable as the load increases. Apache server is considered to be as stable as WebSphere and WebLogic and fast for static content.

Error Count

This refers to the errors that come up when the load on the server is increased. As proved by many reviews and benchmarks, WebSphere and WebLogic throw up less number of errors as the load is increased when compared to Tomcat. Apache also throws up less number of errors.

Cost and Support

Cost of WebSphere is termed to be around $12000 for 1 CPU and WebLogic comes with a price tag of around $10000 per CPU. Tomcat and Apache servers come for free. As evident, WebSphere and WebLogic come up with support while Tomcat and Apache do not.

Other Features

WebSphere and WebLogic are fully integrated J2EE application servers while Tomcat is not. They provide for EJBs and have build in JMS queue implementations. The commercially available server comes up with a host of other useful features that reduce the application development effort. Tomcat provides very minimal ease of development features.

2.2 Architectural Decision

As an architect/designer/consultant, we have to make decisions on which server the application will be deployed. All the above parameters discussed above will be considered. In the existing outsourcing revolution, customers pay minimal attention on the ease of development of an application as development is not longer their headache. As most of the development is being outsourced, customers are primary concerned with the amount of fixed or variable cost they have incurred for building an application. Thus, thinking from the cost perspective of the customer, they will be more inclined to go for Tomcat than any of the commercially available servers. Customers are increasing assuming that the applications being developed will not require any server level support in the future. Customers are assuming that applications will be bug free and stable. The parameters that are primary for any customer with respect to selection of the appropriate server are: –

  • Low/no cost
  • Low/no support cost
  • High stability

hus an architect working in the software services industry has to arrive at the decision of the server taking the above parameters into consideration. As cost is a factor that is above the control of an architect, he/she will be more inclined towards using Tomcat. But Tomcat has a dismal stability record though it provides the best throughput. In a nutshell, Tomcat scores on cost but not on stability

Apache (httpd) server is another server from the Apache Jakarta group which is a freeware. This server scores well on stability and speed for static content but low on performance throughput. This does not support JSP and servlets.

The next few sections of this paper will focus on clustering Tomcat and Apache servers to leverage the low cost advantage of Tomcat with the high stability and speed advantage of Apache.

3). Technical – Apache-Tomcat Clustering

3.1 Tomcat Worker

Tomcat worker refers to one single thread of Tomcat that is run as a slave server and is controlled by the master Apache server. Clustering involves the use of Tomcat workers to achieve the dual advantage of speed and concurrency. By limiting the number of requests to a Tomcat worker to its optimum level, the throughput requirement for that many requests can be achieved. A tomcat worker will be listening to its custom port which will be hid from the requesting user. A worker will act as a standalone Tomcat server though it will be controlled and monitored by the master Apache server.

3.2 Apache Master Server

To provide support for many concurrent users, we club the concept of Tomcat worker and Apache Master server. To support concurrent users, more than one Tomcat workers are spawned based on the optimum throughput obtained for one single Tomcat worker. Eg: – We find that one single Tomcat standalone server provides the maximum throughput without any error count till X number of concurrent users. The application has a requirement to support Y number of concurrent users. Then the formula to decide on the number of Tomcat workers is Y/X: –

Once the number of tomcat workers is decided, we would have arrived at a number that would support the required concurrent users with the optimum throughput. But the question is, each of the Tomcat worker will be listening to its own port, resulting is so many URLs. Thus, we need a master server that can receive requests in a single URL and delegate the requests to the available Tomcat workers. This results in a single URL for the end user. This configuration results in the application to leverage the speed of Tomcat and the stability of Apache server at no cost at all.

 

Once the number of tomcat workers is decided, we would have arrived at a number that would support the required concurrent users with the optimum throughput. But the question is, each of the Tomcat worker will be listening to its own port, resulting is so many URLs. Thus, we need a master server that can receive requests in a single URL and delegate the requests to the available Tomcat workers. This results in a single URL for the end user. This configuration results in the application to leverage the speed of Tomcat and the stability of Apache server at no cost at all.

3.3 High Level Clustering Diagram

 

4). Implementation Details

4.1 Compile, Install and Configure Apache

4.1.1    Install Apache and Tomcat

Download and install Apache in the system. You can download Apache from the site http://ww.apache.com/dist/httpd by selecting the downloadable file corresponding to your operating system.

I have downloaded Apache into /usr/local/apache2.

Download Tomcat also into the system. You can download Tomcat from the site http://tomcat.apache.org/download-41.cgi by selecting the downloadable file corresponding to your operating system.

I have downloaded Tomcat into /usr/local/tomcat.

NOTE: In the rest of the section, we will be dealing with Apache 2 and Tomcat 4x versions.

4.1.2 Configure the JK Module in httpd.conf

Edit the Apache server’s configuration file httpd.conf which is located in the /usr/local/apache2/conf directory.

Below “# LoadModule foo_module modules/mod_foo.so”, insert the following lines:

#

# Load mod_jk

#

LoadModule jk_module modules/mod_jk.so

 

#

# Configure mod_jk

#

JkWorkersFile conf/workers.properties

JkLogFile logs/mod_jk.log

JkLogLevel info

NOTE: You will need to change mod_jk.so to mod_jk.dll for Windows.

4.1.3 Create the workers.properties file

Now we will create a file called workers.properties, and we will place it under /usr/local/tomcat/jk/apache2. The workers.properties file tells Apache about the various Tomcat servers that are running, and on which port they are listening.

In my setup, I installed the two Tomcat workers in different directories, on the same machine as Apache. Feel free to put your Tomcat workers on different machines.

I made the first Tomcat worker’s AJP13 connector listen on port 11009 instead of the default port that is 8009, and the second one listens on port 12009.

I have decided to name my tomcat workers tomcat1 and tomcat2.

Create the file exactly like this:

#

# workers.properties

#

# In Unix, we use forward slashes:

ps=/

# list the workers by name

worker.list=tomcat1, tomcat2, loadbalancer

# ————————

# First tomcat server

# ————————

worker.tomcat1.port=11009

worker.tomcat1.host=localhost

worker.tomcat1.type=ajp13

# Specify the size of the open connection cache.

#worker.tomcat1.cachesize

#

# Specifies the load balance factor when used with

# a load balancing worker.

# Note:

#  —-> lbfactor must be > 0

#  —-> Low lbfactor means less work done by the worker.

worker.tomcat1.lbfactor=100

# ————————

# Second tomcat server

# ————————

worker.tomcat2.port=12009

worker.tomcat2.host=localhost

worker.tomcat2.type=ajp13

 

# Specify the size of the open connection cache.

#worker.tomcat2.cachesize

 

#

# Specifies the load balance factor when used with

# a load balancing worker.

# Note:

#  —-> lbfactor must be > 0

#  —-> Low lbfactor means less work done by the worker.

worker.tomcat2.lbfactor=100

# ————————

# Load Balancer worker

# ————————

 

#

# The loadbalancer (type lb) worker performs weighted round-robin

# load balancing with sticky sessions.

# Note:

#  —-> If a worker dies, the load balancer will check its state

#        once in a while. Until then all work is redirected to peer

#        worker.

worker.loadbalancer.type=lb

worker.loadbalancer.balanced_workers=tomcat1, tomcat2

 

#

# END workers.properties

#

4.2 Install and Configure the Tomcat Workers

Now let’s suppose that Java 1.4.x is installed under /usr/local/jdk1.4.x/. Create two Tomcat 4.x workers under /usr/local/:

For this, you need to copy the directories conf, logs, temp and webapps from the actually installed Tomcat server directory (/usr/local/tomcat) to two new directories say /usr/local/tomcat1 and /usr/local/tomcat2.

In both /usr/local/tomcat1 and /usr/local/tomcat2, the same files will be modified. I here by present the modifications made to the files contained in the /usr/local/tomcat1 directory tree structure. You should also apply the same changes to the corresponding files located under the /usr/local/tomcat2 directory tree structure.

4.2.1 Modify conf/server.xml

Change the control port

At line 13, replace:

<Server port=”8005?

with:

<Server port=”11005?

For the tomcat2 server, replace port 8005 with 12005. This will prevent the two workers from conflicting.

Change the AJP13 port

At line 75, in the AJP 13 connector definition, replace:

port=”8009?

with:

port=”11009?

For the tomcat2 worker, replace port 8009 with 12009.

Disable the standalone HTTP port

We don’t want or need our tomcat servers to directly respond to HTTP requests. So we comment out the HttpConnector section between lines and 58 in the server.xml file.

Example:

<!– Define a non-SSL HTTP/1.1 Connector on port 8080 –>

<!–

<Connector className=”org.apache.catalina.connector.http.HttpConnector”

port=”8080? minProcessors=”5? maxProcessors=”75?

enableLookups=”true” redirectPort=”8443?

acceptCount=”10? debug=”0? connectionTimeout=”60000?/>

–>

NOTE: If you don’t comment this out, you will need to change the port numbers so they don’t conflict between tomcat instances.

Disable the WARP connector

At line 314, comment out the <Connector…WarpConnector…> tag.

Example:

<Service name=”Tomcat-Apache”>

<!–

<Connector className=”org.apache.catalina.connector.warp.WarpConnector”

port=”8008? minProcessors=”5? maxProcessors=”75?

enableLookups=”true” appBase=”webapps”

acceptCount=”10? debug=”0?/>

–>

Do not forget to do the same thing to tomcat2?s server.xml file.

NOTE: You might want to comment out the entire <Service name=”Tomcat-Apache”> element. If so, make sure and remove the comments within it – XML doesn’t like comments within comments.

4.2.2 Create test JSP pages (index.jsp)

Create a file named index.jsp and put it in the /usr/local/tomcat1/webapps/ROOT directory:

<html>

<body bgcolor=”red”>

<center>

<%= request.getSession ().getId () %>

<h1>Tomcat 1</h1>

</body>

</html>

Create a file named index.jsp and put it in the /usr/local/tomcat2/webapps/ROOT directory:

<html>

<body bgcolor=”blue”>

<center>

<%= request.getSession().getId() %>

<h1>Tomcat 2</h1>

</body>

</html>

4.2.3 Start Tomcat1, Tomcat2 and Apache

Set the JAVA_HOME environment variable to the location where JDK1.4 installed

export JAVA_HOME=/usr/local/jdk1.4.x

For starting tomcat1 worker, set the Tomcat environment variable CATALINA_HOME to the tomcat1 worker.

export CATALINA_HOME=/usr/local/tomcat1

Run the following command: –

/usr/local/tomcat/bin/startup.sh

This starts up the first Tomcat worker namely tomcat1.

For starting tomcat2 worker, set the Tomcat environment variable CATALINA_HOME to the tomcat2 worker.

export CATALINA_HOME=/usr/local/tomcat2

Run the following command: –

/usr/local/tomcat/bin/startup.sh

This starts up the second Tomcat worker namely tomcat2.

To start Apache, run the following command:

/usr/local/apache2/bin/apachectl start

4.2.4 Test your Installation

Now is the time to test your setup. First, verify that Apache serves static content.

Click on: http://localhost/. You should see the default Apache index.html page.

Now test that tomcat (either Tomcat 1 or Tomcat 2) is serving Java Server Pages.

Click on: http://localhost/index.jsp

If you get a red page, the page was served by the tomcat1 server, and if you get a blue page, it was served by the tomcat2 server.

Now test that session affinity – also known as sticky sessions – works within the load balancer. Hit the reload button of your web browser several times and verify that the index.jsp page you get is always received from the same tomcat server.

4.3 Configuring Private JVMs

For configuring Apache/Tomcat for private Tomcat instances, you can add one of the following in the file mod_jk.conf in /usr/local/tomcat/jk/apache2

4.3.1 Name-based (1 IP address or NIC)

NameVirtualHost *

<VirtualHost *>

ServerName localhost1

JkMount /*.jsp tomcat1

JkMount /servlet/* tomcat1

JkMount / loadbalancer

JkMount /* loadbalancer

</VirtualHost>

 

<VirtualHost *>

ServerName localhost2

JkMount /*.jsp tomcat2

JkMount /servlet/* tomcat2

JkMount / loadbalancer

JkMount /* loadbalancer

</VirtualHost>

4.3.2 IP-based (different IP for each site)

# First Virtual Host.

#

Listen 192.168.0.1:80

<VirtualHost 192.168.0.1:80>

ServerName localhost

JkMount /*.jsp tomcat1

JkMount /servlet/* tomcat1

JkMount / loadbalancer

JkMount /* loadbalancer

 

</VirtualHost>

 

# Second Virtual Host.

#

<VirtualHost 192.168.0.2:80>

ServerName localhost2

JkMount /*.jsp tomcat2

JkMount /servlet/* tomcat2

JkMount / loadbalancer

JkMount /* loadbalancer

</VirtualHost>

Where the serverNames are fully-qualified host names in a DNS Server.

NOTE: When using SSL with multiple Virtual Hosts, you must use an ip-based configuration. This is because SSL requires you to configure a specific port (443), whereas name-based specifies all ports (*). You might get the following error if you try to mix name-based virtual hosts with SSL.

[error] VirtualHost _default_: 443 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results.

4.4 Workflow Description

The workflow description for the above configuration is given below: –

  • Tomcat workers are configured to AJP3 connectors with different ports.
  • The JK module of Apache server listens to all the connected AJP3 connectors.
  • Once Apache server is started, the entire tomcat workers are registered and the load balancing configurations are also registered.
  • For any given request matching the URI specified in mod_jk.conf file, Apache server receives the request.
  • The received request is then checked against the deployed application in each of worker’s webapps directory through the AJP3 connector and the request is sent to the first worker matching the request URI and which is free according to the load-balancing configuration.
  • The response takes the same route.

5). Benefits

  • Scalability is very easy to achieve. Creating a copy of a worker into a new directory and starting the same by setting the CATALINA_HOME directory.

Thus, if an application cannot support a fixed number of concurrent users, the number can be increased by deploying the same application in as many Tomcat workers as needed.

  • Using the load balancing facility of Apache JK module. If the systems in which Tomcat workers are created have different CPU and memory configuration, then the load balancing facility can be used to make the Tomcat workers residing on a high-end system to process more number of requests than the other workers.
  • Automatic restart of any failed tomcat worker by Apache server. The JK module of Apache monitors each Tomcat worker and if any of the worker instance crashes, Apache server restarts the Tomcat worker automatically, thereby ensuring maximum availability at any point of point.
  • Low cost advantage. Both Apache and Tomcat are freeware.
  • Low cost vendor specific support can be obtained. Specific vendors like HP are providing an integrated version of the cluster and also provide support for the same at a minimum cost.
  • Use of the speed of Apache server for processing static content.
  • Use of the speed of Tomcat for processing JSP and servlet files for low requests

6). Finally

In this era of outsourcing where customers want the same level of throughput, stability and scalability at a low cost, the clustering mechanism of Apache and Tomcat servers proves to be a winning combination. By leveraging the advantages of both these servers through the use of JK integration module, an architect’s dream product seems to be in the making. Though this combination does not provide ease of development, it still proves to be better than other commercially available servers in the critical parameters of cost, stability and scalability from the customer’s point of view. Thus the clustering of Apache with Tomcat gives us a product which is costless, faster, more stable and easily scalable when compared to many other commercially available servers.

ClamAV Virus Scanning

Thankfully Linux isn’t a platform which has a significant problem with Viruses, however it is always better to be safe than sorry. Luckily ClamAV is an excellent free anti-virus solution for Linux servers. However, at least on RedHat Enterprise 5 (RHEL5) the default install doesn’t offer any automated scanning and alerting. So here is what I’ve done:

The following steps assume you are using RHEL5, but should apply to other Linux distributions as well.

First, you’ll want to install ClamAV:

yum install clamav clamav-db clamd
/etc/init.d/clamd start

On RHEL5 at least this automatically sets up a daily cron job that uses freshclam to update the virus definitions, so that’s good.

Next I recommend removing the test virus files, although you can save this until after you test the rest of the setup:

rm -rf /usr/share/doc/clamav-0.95.3/test/

Now we want to setup our automation. I have a daily cron job that scans the entire server which can take several minutes, and then an hourly cron job that only scans files which were created or modified within the last hour. This should provide rapid notification of any infection without bogging your server down for 5 minutes every hour. The hourly scans run in a couple of seconds.

Each scanning script then checks the scan logs to see if there were any infected files found, and if so immediately sends you a notification e-mail (you could set this address to your mobile phone’s SMS account if you wanted).

The Daily Scan:

emacs /etc/cron.daily/clamscan_daily

Paste in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
 
# email subject
SUBJECT="VIRUS DETECTED ON `hostname`!!!"
# Email To ?
EMAIL="me@domain.com"
# Log location
LOG=/var/log/clamav/scan.log
 
check_scan () {
 
    # Check the last set of results. If there are any "Infected" counts that aren't zero, we have a problem.
    if [ `tail -n 12 ${LOG}  | grep Infected | grep -v 0 | wc -l` != 0 ]
    then
        EMAILMESSAGE=`mktemp /tmp/virus-alert.XXXXX`
        echo "To: ${EMAIL}" >>  ${EMAILMESSAGE}
        echo "From: alert@domain.com" >>  ${EMAILMESSAGE}
        echo "Subject: ${SUBJECT}" >>  ${EMAILMESSAGE}
        echo "Importance: High" >> ${EMAILMESSAGE}
        echo "X-Priority: 1" >> ${EMAILMESSAGE}
        echo "`tail -n 50 ${LOG}`" >> ${EMAILMESSAGE}
        sendmail -t < ${EMAILMESSAGE}
    fi
 
}
 
clamscan -r / --exclude-dir=/sys/ --quiet --infected --log=${LOG}
 
check_scan
chmod +x /etc/cron.daily/clamscan_daily

The Hourly Scan:

emacs /etc/cron.hourly/clamscan_hourly

Paste in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
 
# email subject
SUBJECT="VIRUS DETECTED ON `hostname`!!!"
# Email To ?
EMAIL="me@domain.com"
# Log location
LOG=/var/log/clamav/scan.log
 
check_scan () {
 
    # Check the last set of results. If there are any "Infected" counts that aren't zero, we have a problem.
    if [ `tail -n 12 ${LOG}  | grep Infected | grep -v 0 | wc -l` != 0 ]
    then
        EMAILMESSAGE=`mktemp /tmp/virus-alert.XXXXX`
        echo "To: ${EMAIL}" >>  ${EMAILMESSAGE}
        echo "From: alert@domain.com" >>  ${EMAILMESSAGE}
        echo "Subject: ${SUBJECT}" >>  ${EMAILMESSAGE}
        echo "Importance: High" >> ${EMAILMESSAGE}
        echo "X-Priority: 1" >> ${EMAILMESSAGE}
        echo "`tail -n 50 ${LOG}`" >> ${EMAILMESSAGE}
        sendmail -t < ${EMAILMESSAGE}
    fi
 
}
 
find / -not -wholename '/sys/*' -and -not -wholename '/proc/*' -mmin -61 -type f -print0 | xargs -0 -r clamscan --exclude-dir=/proc/ --exclude-dir=/sys/ --quiet --infected --log=${LOG}
check_scan
 
find / -not -wholename '/sys/*' -and -not -wholename '/proc/*' -cmin -61 -type f -print0 | xargs -0 -r clamscan --exclude-dir=/proc/ --exclude-dir=/sys/ --quiet --infected --log=${LOG}
check_scan
chmod +x /etc/cron.hourly/clamscan_hourly

Protected System

You should now have a well protected system with low impact to system performance and rapid alerting. Anti-Virus is only one piece of protecting a server, but hopefully this makes it easy to implement for everyone.

Jboss Mod cluster

The problem I had was that I just want to enable clustering for given VirtualHost section and not for the whole Web server. Current configuration was quite simple, as you can find out on mod_cluster’s web page. On the JBoss AS side you must uncomment one line or so and provide list with mod_cluster enabled web servers.. But as I said, such configuration enable clustering for the entire web server. I didn’t want that, as I want to create another Virtual Host to serve static content.

So, the first step was to read the documentation, but it didn’t answer my questions. I was trying many different configurations and what I achieved was a separation of Virtual Hosts – I could define the different clusters for different Virtual Hosts, but still wasn’t able to serve static content :P

The answer was simple, just disable creation of balancer for all Virtual hosts with this directive:

CreateBalancers 1

The second thing was to enable use of aliases

UseAlias 1
ServerAdvertise Off

Also on JBoss AS I had to define the Alias:

<Host name="localhost">
<Alias>my.domain.com</Alias>
...

The rest was easy, just I have had to enable use of Virtual Hosts on given IP address, specify the web server name and define the Virtual Hosts. After restart everything seemed to work perfectly. I had static pages under one domain name and an application under second. The only problem was that I wasn’t able to login to the application. Why? Simply, my session wasn’t a Sticky Session. And not because JBoss server didn’t support it. Much simpler. My session ID wasn’t passed to the JBoss server and back to the Apache HTTPD :D

To solve that I just had to add ProxyPass and ProxyPassReverse directive:

ProxyPass / balancer://mycluster/ stickysession=JSESSIONID|jsessionid nofailover=On
ProxyPassReverse / balancer://mycluster/ stickysession=JSESSIONID|jsessionid

And that was the end, everything was working smoothly. But the customer decide not to use the same server for load balancing and serving static pages. So all my work was useless, except experience I’ve got

Anyway it’s a very elastic configuration, as you can add another JBoss servers and attach them to the cloud in a minute.

The whole configuration just for future reference:

LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_ajp_module /usr/lib/apache2/modules/mod_proxy_ajp.so
LoadModule slotmem_module /usr/lib/apache2/modules/mod_slotmem.so
LoadModule manager_module /usr/lib/apache2/modules/mod_manager.so
LoadModule proxy_cluster_module /usr/lib/apache2/modules/mod_proxy_cluster.so
LoadModule advertise_module /usr/lib/apache2/modules/mod_advertise.so
LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

ServerName www.domain.com
NameVirtualHost 10.10.10.10:80
DocumentRoot /var/www

CreateBalancers 1
ServerAdvertise Off
UseAlias 1

<VirtualHost 10.10.10.10:80>
    DocumentRoot /var/www
    ServerName www.domain.com
    ServerAlias domain.com
</VirtualHost>

<VirtualHost 10.10.10.10:80>
    ServerName my.domain.com
    ProxyPass / balancer://mycluster/ stickysession=JSESSIONID|jsessionid nofailover=On
    ProxyPassReverse / balancer://mycluster/ stickysession=JSESSIONID|jsessionid
    <Location /status>
        SetHandler mod_cluster-manager
        Order deny,allow
        Deny from all
        Allow from 127.0.0.1
        #Allow from all
    </Location>

    KeepAliveTimeout 60
    MaxKeepAliveRequests 0

</VirtualHost>