How to create virtual hosts in Tomcat

Home > Search > How-to
  by

By default, Tomcat is configured with a single host named localhost, which allows Tomcat to send resources to clients from the host named localhost

 

Virtual hosts allows you to configure Tomcat to serve resources to clients from different hostnames.

 

The cataline_home/conf/server.xml file has the host named localhost, which is the defaultHost. The appBase of localhost is webapps, which means that requests to localhost will serve files at and below the catalina_home/webapps/ directory. By default, the cataline_home/webapps/ROOT/index.jsp file will be served.

<Engine name="Catalina" defaultHost="localhost">
. . .
  <Host name="localhost" appBase="webapps"
        unpackWARs="true" autoDeploy="true">
  . . .
  </Host>

 

Additional virtual hosts can be added. As an example, if your domain name is example.com, one possible sub-domain is stage.example.com. In this scenario, a virtual host named stage.example.com can be added, so that there are now two hosts.

<Engine name="Catalina" defaultHost="localhost">
. . .
  <Host name="localhost" appBase="webapps"
        unpackWARs="true" autoDeploy="true">
  . . .
  </Host>

  <Host name="stage.example.com" appBase="stage"
        unpackWARs="true" autoDeploy="true">
  </Host>

 

After adding the additional virtual host, restart the server.

~]# cataline_home/bin/shutdown.sh
~]# cataline_home/bin/startup.sh

 

Ensure Tomcat has initialized.

~]# cataline_home/bin/configtest.sh
. . .
Jun 11, 2017 6:59:31 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1395 ms

 


DNS

Configure your DNS server to resolve stage.example.com to the IP address of your TC Server.

 


Deploy Application

Since stage.example.com appBase is stage, create the stage directory and the ROOT directory.

~]# mkdir catalina_home/stage
~]# mkdir catalina_home/stage/ROOT

 

Add index.jsp to cataline_home/stage/ROOT, and then add some text such as Hello World to the index.jsp file.

~]# touch catalina_home/stage/ROOT/index.jsp

 

You should also be able to navigate to http://stage.example.com:8080 and the index.jsp file should be served.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments