Apache Tomcat serving multiple webapps on different domains

apache tomcat java multipe webapps
Standard

How to serve multiple web applications on different domains through Apache Tomcat

This is a guide to setting up multiple webapps on Apache Tomcat, locally or VMWare or Amazon EC2 instance. We also talk a little about iptables and port redirection towards the end.

Requirements

  • java 1.7 (assumed installed)
  • centos 6.5 (assumed installed)
  • apache tomcat (assumed installed)

To see how to install Oracle Java Development Kit 7.0 installation, Apache Tomcat installation or Open JDK installation for Amazon EC2 Instance please check one of the previous posts.

So with Java and Apache Tomcat installed let’s dive straight in. Firstly let’s create our project directory structure under the Apache Tomcat’s webapps directory

Now we need to change the Apache Tomcat configuration file in conf/server.xml and add new hosts as per our requirements for the above three apps

Personally I prefer to store the application war in a different location and then create symlinks from the war file to ROOT.war files under Apache Tomcat. This is just a personal preference to mange application upgrades. We now create the corresponding directories to host the war file. Let’s assume the war files are stored at the following path

We will create symlinks to their respective ROOT.war files as follows

Make sure you chown the files to tomcat so that tomcat can auto-explode the war file. Please do that for each of the application war files.

One done you should have the tree as follows

Make sure you modify the file permissions on the webapps folder under Apache Tomcat.

Almost done, now you can start tomcat and tail the logs to see the result.

When you start tomcat, tomcat will listen on port 8080. For it to listen on default HTTP port you would have to play around with iptables and do port redirection from 80 (default HTTP port) to 8080 (default tomcat port). You may want to ask why not just change the default port to 80 in the tomcat configuration. You don’t want to do that because maybe you don’t want to serve your site from tomcat or run the apache tomcat as root and listen to default http port.

First and foremost make a backup of the iptables

The port redirection can be done by using the following commands. Please make sure you are using the appropriate network device names in your case. The first two lines will configure the iptables to accept incoming connections to port 80 and 8080. What this means is now your machine is accepting connections on both 80 and 8080. The next command does the port redirection from 80 to 8080.

Finally remember to save the iptables rule changes so that, they survive a reboot.

That’s it done. You can now test your domain or subdomain is serving appropriately.