Thursday, March 8, 2007

Enabling multiple localhost sites in Tomcat

I'm developing code on a Mac under Tomcat for a multi-application website which looks at the domain name to determine which app to run. It was getting damn annoying changing the database tables whenever I wanted to login to a different app. "There must be a better way to do this" he cried! ... and there is!

Rather than just having localhost pointing to your machine, you can have any name you want. eg. dev.localhost, qa.localhost, test.localhost, etc.

Step 1.
Setup the new host names in your hosts file. For me this is under /etc/hosts and I have to sudo to edit it. In there you will already have localhost setup. Add your new ones underneath and save it.

127.0.0.1 localhost
127.0.0.1 qa.localhost
127.0.0.1 dev.localhost
127.0.0.1 test.localhost


Now you should now be able to ping these and see the 127.0.0.1 IP address. In fact, you can try your URL with this server-name instead of localhost and get to your site!

Step 2.
Setup Tomcat to route these hosts to your app. This will run a seperate Tomcat instance for each application. Modify the server.xml file (in the conf folder) by adding the following XML:

<Host name="qa.localhost" appBase="webapps">
<Context path="" docBase=".">
<Host>

<Host name="dev.localhost" appBase="webapps">
<Context path="" docBase=".">
<Host>

<Host name="demo.localhost" appBase="webapps">
<Context path="" docBase=".">
<Host>


I guess if you have other web applications that sit elsewhere you can just modify the appBase path. I didn't need to do this. Note that I was using Eclipse with this setup and when I tried to debug, it started a host for each server and took ages to start; and then died with an out of memory error (this was with 7 aliases setup).

Step 3.
Try it out. Fire up Tomcat, and browse to http:/qa.localhost:8080/{blah blah} and you're away! Nice one brother!

2 comments:

nachokhan said...

Hi. I have a problem. I want to configure Tomcat tow have 2 localhosts but refering to different directories.

For expample, if I write:

"http://localhost:8080"

I want to go to webapps directory (cause there is the tomcat manager)

But if I write:

"http://localhost:8080/app1"

I want to go to the c:/sites/ directory (cause there are the applications).

How can I do that??
Thanks!!!

Jonts said...

Hi Ignacio.

Try asking at http://www.stackoverflow.com

That site is full of experts who'll be able to answer your question and explain the details!