Published on Sep 20 2011 in Java Tomcat

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a path under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our Java Control Panel), second step is to add virtual host in server.xml. See the below example.

Let's assume you have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory contents:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. domain1.com is the main domain (the main domain can point to a different directory such as ROOT, anyway this is only example).
  2. domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings - default mappings are enough. Use custom Java Control Panel for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml as follows:

<Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
     <Alias>www.domain1.com</Alias>
     <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
               prefix="localhost_access_log." suffix=".txt" 
               pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
     <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
</Host>
    
<Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
     <Alias>www.domain2.com</Alias>
     <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
               prefix="localhost_access_log." suffix=".txt" 
               pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
     <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
</Host>

Restart Tomcat using JCP or shell (SSH) and your are done.

Separate webapps for each virtual Host

Even better approach may be to create separate webapps directory like webapps_domain1.com in $CATALINA_HOME. WAR file uploaded to such dedicated webapps will be only deployed once and reachable under this virtual host only (it main domain and aliases). This will also save some memory comparing to the first approach where all virtual hosts use the same directory (webapps) as appBase.