Home/Server & Website Managed Operations/Configuring Tomcat 6 on Arch Linux for Multi-Site, SSL, and High-Performance NIO/APR
Server & Website Managed Operations

Configuring Tomcat 6 on Arch Linux for Multi-Site, SSL, and High-Performance NIO/APR

Since Tomcat is Java-based, its configuration methods are largely similar across various Linux distributions. However, as I found few articles on setting up Tomcat in an Arch Linux environment, I decided to document my practical experience here. This article assumes you are not very familiar with Tomcat and focuses primarily on its configuration.

1. Install Java JDK

The extra repository in Arch Linux contains jdk7-openjdk and openjdk6, which can be installed directly using pacman. You can choose either based on your specific needs. I installed OpenJDK 7:

$ sudo pacman -S jdk7-openjdk

2. Install Tomcat

Similarly, the extra repository already has versions 5, 6, and 7 of Tomcat available. You can choose according to your situation; here I installed Tomcat 6.

$ sudo pacman -S tomcat6

By default, Tomcat 6 is installed at /usr/share/tomcat6. Below is a list of the main directories and their functions (arrows indicate the actual location of the directory links):

  • /usr/share/tomcat6: The main program directory, also the location pointed to by the variable $CATALINA_HOME. In the case of a single Tomcat instance, it is also the location pointed to by $CATALINA_BASE.
  • conf -> /etc/tomcat6: Configuration file directory.
  • lib -> /usr/share/java/tomcat6: Shared JAR package directory. These packages are used by Tomcat and can also be referenced by web applications.
  • logs -> /var/log/tomcat6: Log directory, which is very helpful for troubleshooting and viewing access records.
  • webapps -> /var/lib/tomcat6/webapps: Default web application directory. Tomcat 6 comes with several sample programs, which will be introduced below.

Now, try starting the Tomcat service:

$ sudo /etc/rc.d/tomcat start

Depending on the installed Java runtime, there might be errors during startup. Check the value of the TOMCAT_JAVA_HOME variable in the startup script’s configuration file /etc/conf.d/tomcat6. In my installation, the Java runtime should be in /opt/java (you can see this by using $ which java), so change:

TOMCAT_JAVA_HOME=/usr/lib/jvm/java-7-openjdk
To the following:

TOMCAT_JAVA_HOME=/opt/java

Restart the Tomcat service:

$ sudo /etc/rc.d/tomcat6 restart

Generally, there should be no problems. Open any browser and enter “http://localhost:8080” in the address bar. If you see the Tomcat cat, it means the service has been installed correctly and is running normally.

3. Understand the webapps Directory

This directory is located under the Tomcat 6 installation directory, but its actual content resides in /var/lib/tomcat6/webapps. Each directory in the webapps directory corresponds to a web application. For example, the access address for the docs directory is http://localhost:8080/docs, and similarly, the access address for the manager directory is http://localhost:8080/manager. A special case is the ROOT directory, which corresponds to the root directory of the website, i.e., http://localhost:8080/.

You can visit the sample programs provided by Tomcat one by one to experience them. Among these, the manager and host-manager applications require login authentication to access. To add a login user, edit the configuration file conf/tomcat-users.xml in the Tomcat installation directory (which is actually the file /etc/tomcat6/tomcat-users.xml) and add the following lines:

<role rolename="manager-gui"/>
<role rolename="admin-script"/>
<role rolename="admin-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui,admin-script,admin-gui"/>

Then restart the Tomcat service. You can now log in and access the manager and host-manager applications using the username tomcat and password tomcat.

Each Java Web application has the following directory structure:

  • /index.html: Resources accessed directly by visitors, such as static images and CSS stylesheets.
  • /WEB-INF/: Resources that cannot be accessed directly by visitors.
  • /WEB-INF/classes: Compiled class files of the application’s Java source code.
  • /WEB-INF/web.xml: Configuration file for the application.
  • /WEB-INF/lib: Packages referenced by the application.

Of course, not all of these are mandatory. You can even create a directory, say “hello”, and inside it, only create an index.html file (with any content). You can then access it via http://localhost:8080/hello/index.html. (Note: This is not a true Web application; this method is only for testing purposes.)

Below, we use Apache Maven to create the simplest Web application. Execute the following command in the user directory to create the skeleton of the Web application:

$ mvn archetype:generate

In the interactive interface:

Choose a number or apply filter: Enter 174 to create a maven-archetype-webapp type project.
Choose version: Enter 5 for version 1.0.
Define value for property ‘groupId’: Enter org.test.
Define value for property ‘artifactId’: Enter demo.
Define value for property ‘version’: Enter 1.0.
Define value for property ‘package’: Enter org.test.demo
Confirm properties configuration: Press Enter directly

The above involves Maven knowledge, which is outside the scope of this article. If you are unfamiliar with it, you can refer to the free Chinese e-book Maven in Action. By the way, Maven is one of the most commonly used tools for building and managing Java projects.

You should now see a directory named demo. Enter it and use Maven to package the project:

$ cd demo

$ mvn package

The packaging result is the file ./target/demo.war. Copy this file to the webapps directory:

$ sudo cp target/demo.war /var/lib/tomcat6/webapps/

Since Tomcat automatically deploys applications created by default, the file demo.war copied to the webapps directory will be automatically decompressed. Checking the webapps directory should reveal a new directory named demo. Now, try accessing http://localhost:8080/demo in your browser. You should see the text “Hello World!”, which is the result of running the Web application created with Maven.

Note that the war file formed after packaging a Java Web application does not necessarily need to be extracted to run. This will be discussed in the next section’s configuration.

4. Understand Tomcat’s Main Configuration File server.xml

This file is located in the conf directory under the Tomcat 6 installation directory, with actual content at /etc/tomcat6/server.xml.

As indicated by its extension, this is an XML file. Opening it reveals the following structure:

<Server port="8005" shutdown="SHUTDOWN">
	<Service name="Catalina">
        <Executor ...... />
		<Connector ...... />
		<Connector ...... />
		<Engine name="Catalina" ... >
			<Host name="localhost" ... >
				<Context ... />
			</Host>
		</Engine>
	</Service>
</Server>

It consists of a four-layer structure: Server->Service->Engine->Host->Context. From inner to outer layers:

  • Context: Represents a Web application. One Context corresponds to one Web application.
  • Host: Represents a virtual host. For example, www.dog.com corresponds to one virtual host, and api.dog.com corresponds to another. A Host is used to define a virtual host. (A “virtual host” can simply be understood as “a website”).
  • Engine: A collection of virtual hosts. For example, www.dog.com and api.dog.com can form a group of virtual hosts.
  • Service: A collection of Engines, including definitions for thread pools (Executor) and connectors (Connector).

Connector Configuration

A Connector represents a port open to the outside world. Simply put, it is an IpAddress:Port combination encountered by most network service programs, such as 192.168.0.10:8080. Of course, much more can be defined within a Connector, meaning many attributes can be added to the Connector XML node. Below are some common ones:

  • enableLookups: (default=true) Whether to allow reverse DNS resolution of the visitor’s IP address. If your application uses request.getRemoteHost() and only needs the IP address, it is recommended to disable this option to save time on reverse domain name resolution.
  • maxPostSize: (default=2097152, i.e., 2MB) Maximum allowed size for POST upload data (in bytes). For general websites, such as those allowing comments or article writing, the default 2MB is sufficient. However, if the website has image or file upload features, this needs to be adjusted based on specific circumstances.
  • protocol: The type of connector. Tomcat 6 offers the following options:
    • org.apache.coyote.http11.Http11Protocol: Abbreviated as “HTTP/1.1”. This is the default connector. Each visitor connection requires a thread, resulting in lower concurrency performance.
    • org.apache.coyote.http11.Http11NioProtocol: NIO connector. A connector based on non-blocking socket mode, offering good concurrency performance, implemented purely in Java.
    • org.apache.coyote.http11.Http11AprProtocol: APR connector. APR refers to the library used by the most widely used web server program on the internet, Apache Http Server. Tomcat recommends using this in production environments. Specific methods will be introduced below.
  • redirectPort: When a user accesses a non-HTTPS resource that requires HTTPS access, Tomcat will automatically redirect to the HTTPS port. Generally, HTTPS uses TCP port 443, so the value is usually “443”.
  • SSLEnabled: (default=false) Sets whether the current connector uses secure SSL transmission. If set to “true”, the following two attributes should also be set:
    scheme=”https” (default=http) can be set to http or https.
    secure=”true” (default=false).
  • address: The IP address bound to the connector. When a server has multiple IP addresses, you can specify which one to bind. Not setting this attribute means binding to all IP addresses of the current server.
  • compressableMimeType: (default=”text/html,text/xml,text/plain”) Specifies the types of resources to be GZIP compressed.
  • compression: (default=off) Whether to enable GZIP compression. Values can be on/off/force. After setting to on, GZIP compression will be enabled for resource types specified by the compressableMimeType attribute.
  • connectionTimeout: (default=”60000″) Time in milliseconds for the server to wait for the first line of the Request header after a visitor connects.
  • executor: Specifies the name of the thread pool used by the current connector. If specified, other settings regarding thread count, such as maxThreads, are ignored.
  • maxThreads: (default=200) Maximum number of threads that can be created.
  • port=”80″: Binds the port.
  • keepAliveTimeout: (default=connectionTimeout) Time to maintain the network connection after a visitor completes a request.

A simple Connector definition is as follows:

<Connector port="80" protocol="HTTP/1.1"
			   connectionTimeout="60000"
		   redirectPort="443" />

Executor Configuration

Executor is used to define shared thread pools. By default, each Connector creates its own thread pool. If you want multiple Connectors to share a thread pool, you can first define a thread pool, such as:

<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
		maxThreads="150" minSpareThreads="4"/>

Then modify the above Connector configuration by adding the executor attribute. The modified configuration is as follows:

<Connector executor="tomcatThreadPool"
			   port="80" protocol="HTTP/1.1"
			   connectionTimeout="60000"
			   redirectPort="443" />

Host Configuration

A Host configuration represents a virtual host. For example, the following is a simple Host configuration:

<Host name="localhost" 	appBase="webapps"
		    unpackWARs="true" autoDeploy="true">
		<Alias>dog.com</Alias>
		<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 	
			   prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
</Host>

Functions of various attributes in the Host configuration node:

  • name: Sets the domain name of the virtual host. For example, localhost represents the local machine name. In practical applications, you should fill in a specific domain name, such as www.dog.com or dog.com. Of course, if the virtual host is for internal personnel access, you can directly fill in the server’s IP address, such as 192.168.1.10.
  • autoDeploy: Whether to allow automatic deployment. The default value is true, indicating that Tomcat will automatically detect changes in files under the appBase directory and apply them to running Web applications.
  • unpackWARs: Sets whether to automatically extract war archives before running Web applications. The default value is true.
  • appBase: Sets the path for the group of Web applications. As mentioned earlier, a virtual host can consist of multiple Web applications. Therefore, the directory pointed to by appBase should be the directory prepared to store this group of Web applications, not the directory of a specific Web application itself (even if the virtual host consists of only one Web application). The value of the appBase attribute can be a relative path relative to the Tomcat installation directory or an absolute path. Note that this path must be accessible by Tomcat. Tomcat installed via the Arch Linux source runs as the tomcat user, so after creating a new appBase directory, you can use the chown command to change the ownership of the directory.

Below is an example of how to create a new virtual host www.dog.com:

You can see the webapps directory created by default when installing Tomcat under the directory /var/lib/tomcat6. For convenience, we will also create the document root for the virtual host we are about to create in /var/lib/tomcat6:

$ sudo mkdir dog

Then create a directory named ROOT inside the dog directory, and create a file named index.html inside ROOT (with any content).

Now change the owner and group of the directory to tomcat:

$ sudo chown -R tomcat:tomcat dog

Then add the following Host node under the Host node in server.xml:

<Host name="www.dog.com" 	appBase="/var/lib/tomcat6/dog">
</Host>

Restart the Tomcat service, and you can now access this newly created virtual host via http://www.dog.com in your browser. Of course, you must first add a resolution record from www.dog.com to 127.0.0.1 in the /etc/hosts file, as follows:

127.0.0.1    www.dog.com

Sometimes a virtual host may bind multiple domain names simultaneously, such as www.dog.com and dog.com. In this case, you can achieve this by adding an Alias in the Host configuration node, for example:

<Alias>dog.com</Alias>

Additionally, the <Valve className=… /> configuration in the above example sets the storage location and filename for visitor access logs.

Engine Configuration

The default Engine node is as follows:

<Engine name="Catalina" defaultHost="localhost">
</Engine>

This should not need further elaboration. The defaultHost is used to specify the name of the virtual host that Tomcat selects by default when there is no corresponding virtual host. Consider the following scenario:

Suppose three domains are DNS-resolved to your server, such as dog.com, www.dog.com, and api.dog.com. Currently, you have only configured virtual hosts for dog.com and www.dog.com. When a visitor accesses your server via api.dog.com, Tomcat will return the result of one of the virtual hosts based on the defaultHost setting. In practical applications, defaultHost should be set to your primary domain name, such as www.dog.com.

5. Multi-Site Configuration

Sometimes we need to run multiple sites on one server. This is easily achieved through Tomcat. Below, let’s assume we want to set up two sites: www.dog.com and www.cat.com.

First, ensure that the DNS for your two domains resolves correctly to your server. Since this is an experiment, we can add domain resolution locally. Modify the /etc/hosts file and add the following two lines:

127.0.0.1	www.cat.com
127.0.0.1	www.dog.com

Then, create two directories named cat and dog in the /var/lib/tomcat6 directory. Inside each directory, create a directory named ROOT, and inside ROOT, create a file named index.html (with any content). Then change the owner and group of the cat and dog directories to tomcat. Refer to the previous section for the method; details are omitted here.

Now edit the main configuration file of Tomcat, server.xml, and add the following two new Host nodes under the default Host node:

<Host name="www.dog.com" appBase="/var/lib/tomcat6/dog" autoDeploy="true" unpackWARs="true">
</Host>
<Host name="www.cat.com" appBase="/var/lib/tomcat6/cat" autoDeploy="true" unpackWARs="true">
</Host>

Inside the Host nodes, you can add the attributes, Alias, and Valve sub-nodes you need according to the instructions in the previous section. Restart the Tomcat service. You should now be able to browse these two sites via http://www.dog.com and http://www.cat.com respectively in your browser.

6. Using the NIO Connector

The default connector has poor concurrency performance. If the website’s concurrent traffic is not high, it doesn’t matter, or this might not be noticeable on an intranet (because requests on the intranet might complete within 1 second). However, when the environment switches to the Internet, each client request might take several seconds or even tens of seconds to transmit due to network latency. This leads to the phenomenon of “many visitors connecting simultaneously.” When all threads of the Tomcat connector are occupied, subsequent visitors will be blocked. Therefore, it is best to change the default connector to the NIO connector (non-blocking Java connector) in a real environment. The method is simple: just change the protocol attribute value of the Connector node to “org.apache.coyote.http11.Http11NioProtocol”. For example, originally it was:

<Connector port="80" protocol="HTTP/1.1"
		   redirectPort="443" />

Modify it to:

<Connector port="80" protocol="org.apache.coyote.http11.Http11NioProtocol"
		   redirectPort="443" />

Then restart the Tomcat server.

7. Adding SSL Certificates to Websites

Sometimes websites involve important business data. It is best to transmit these pages over the internet using HTTPS to prevent important information from being intercepted by intermediaries.

For detailed methods, you can refer to my previous article “Adding GoDaddy SSL Certificate to Your Website,” which introduces how to apply for signed SSL certificates and how to modify Tomcat configurations. If you just want to experiment with adding HTTPS functionality to your website or use HTTPS on an internal company website, you can use a simple method: using a self-signed SSL certificate. A self-signed SSL certificate is one generated by yourself. This certificate is not signed and certified by a third-party certificate authority, so browsers will prompt certificate errors when visiting such websites. However, visitors can still continue to browse the website content.

Below, let’s assume we want to add an SSL certificate to the www.awsok.com site from the previous section. First, use the keytool tool bundled with Java to generate a keystore file (a file format for storing certificates). Execute the following command in your home directory:

$ keytool -keysize 2048 -genkey -alias tomcat -keyalg RSA -keystore tomcat.keystore

It will then prompt you to set a password and enter DN information:

Enter keystore password:  Set a password to protect your keystore file, e.g., 123456
Re-enter new password: Re-enter the above password
What is your first and last name?
  [Unknown]:  www.awsok.com (this is the domain name)
What is the name of your organizational unit?
  [Unknown]:  Networking Organizational Unit Name (any)
What is the name of your organization?
  [Unknown]:  awsok.com Organization Name (any)
What is the name of your City or Locality?
  [Unknown]:  Shenzhen City (any)
What is the name of your State or Province?
  [Unknown]:  Guangdong Province (any)
What is the two-letter country code for this unit?
  [Unknown]:  CN Two-letter Country Code (any)
Is CN=www.awsok.com, OU=Networking, O=awsok.com, L=Shenzhen, ST=Guangdong, C=CN correct?
  [no]:  yes Enter yes if the above information is correct

Enter key password for
    (RETURN if same as keystore password): Press Enter directly for this step

After completion, a tomcat.keystore file will be generated in the current directory. Copy this file to the root directory of the dog website application (i.e., /var/lib/tomcat6/dog):

$ sudo cp tomcat.keystore /var/lib/tomcat6/dog

Then modify the main configuration file of Tomcat, server.xml, and add the following new Connector node under the default Connector node:

<Connector port="443" protocol="HTTP/1.1″
    SSLEnabled="true"
    scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS"
    keystoreFile="/var/lib/tomcat6/dog/tomcat.keystore"
    keystorePass="123456" />

If you are using the NIO connector, you should change the protocol attribute value to Http11NioProtocol, i.e.:

<Connector port="443" protocol="Http11NioProtocol″
	SSLEnabled="true"
	scheme="https" secure="true"
	clientAuth="false" sslProtocol="TLS"
	keystoreFile="/var/lib/tomcat6/dog/tomcat.keystore"
	keystorePass="123456" />

Restart the Tomcat service. Access https://www.dog.com with your browser. The browser may prompt a certificate error; ignore it (for Firefox, you need to click the “Add Exception” button to ignore it). You will then see that the webpage is being browsed via HTTPS.

8. Using the High-Performance APR Connector

APR stands for Apache Portable Runtime, providing high-performance features for Apache Http. Below is a simple comparison of the characteristics of the standard connector, NIO, and APR (excerpted from here):

				Java Blocking Connector		Java Nio Blocking Connector		APR Connector
	Classname			Http11Protocol				Http11NioProtocol		Http11AprProtocol
	Tomcat Version		3.x 4.x 5.x 6.x				6.x					5.5.x 6.x
	Support Polling			NO						YES						YES
	Polling Size			N/A					Unlimited - Restricted by mem		Unlimited - Configurable
	Read HTTP Request	Blocking				Non Blocking					Blocking
	Read HTTP Body		Blocking				Sim Blocking					Blocking
	Write HTTP Response	Blocking				Sim Blocking					Blocking
	SSL Support			Java SSL					Java SSL					OpenSSL
	SSL Handshake		Blocking				Non blocking					Blocking
	Max Connections		maxThreads				See polling size				See polling size

Tomcat documentation recommends APR over NIO. Since I don’t have a real environment (i.e., massive visits from the internet) to test and compare them in detail, I’m not sure how much they differ. Below is how to use APR:

First, install the native libraries for APR for Tomcat and OpenSSL (if you need to use SSL certificates and the system hasn’t installed them yet). Both are already present in the local repository of Arch Linux, so the installation method is simple:

$ sudo pacman -S tomcat-native
$ sudo pacman -S openssl

Then modify the main configuration file of Tomcat, server.xml, and change the protocol attribute value of the Connector to “org.apache.coyote.http11.Http11AprProtocol”. The modified configuration is roughly as follows:

<Connector port="80" protocol="org.apache.coyote.http11.Http11AprProtocol"
		   redirectPort="443" />

(Note: Keeping the protocol=”HTTP/1.1″ attribute value is also acceptable)

Then restart the Tomcat service. How do you know if the APR connector is being used? Just check Tomcat’s log files. The default log file is: /var/log/tomcat6/catalina.err:

$ sudo tail /var/log/tomcat6/catalina.err

If you see the red text content below at the end of the log after restarting the Tomcat service, it means the APR connector has been successfully enabled.

Feb 19, 2012 9:44:05 AM org.apache.coyote.http11.Http11AprProtocol start
INFO: Starting Coyote HTTP/1.1 on http-80
Feb 19, 2012 9:44:05 AM org.apache.coyote.http11.Http11AprProtocol start
INFO: Starting Coyote HTTP/1.1 on http-443
Feb 19, 2012 9:44:05 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1281 ms

If you use the APR connector and also need to add an SSL certificate (i.e., need HTTPS access functionality), you need to use OpenSSL to generate an encrypted private key and modify the corresponding Connector configuration. Still using the example from Section 7 above, adding an SSL certificate to the www.dog.com site:

First, generate the private key and self-sign it using OpenSSL. Execute the following commands in your home directory:

# Generate private key
$ openssl genrsa -out ca.key 1024 

# Generate CSR
$ openssl req -new -key ca.key -out ca.csr

# Generate Self Signed Key
$ openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt

Similar to Section 7 above, you will be prompted to enter DN information midway. After completion, copy the ca.crt and ca.key files to the root directory of the dog site application:

$ sudo cp ca.crt /var/lib/tomcat6/dog
$ sudo cp ca.key /var/lib/tomcat6/dog

Then modify the Connector node as follows:

<Connector port="443" SSLEnabled="true"
		   scheme="https" secure="true"
		   SSLCertificateFile="/var/lib/tomcat6/dog/ca.crt"
		   SSLCertificateKeyFile="/var/lib/tomcat6/dog/ca.key"/>

It takes effect after restarting the Tomcat service.

Conclusion

This article briefly describes the methods and steps for installing Tomcat 6, modifying the main configuration file, setting up multi-sites, adding SSL certificates, and using high-performance NIO and APR connectors in an Arch Linux environment. Due to the large amount of content and my limited preliminary testing, I am unsure if there are any errors or what advice to give. Therefore, I strongly recommend reading the official Tomcat documentation in detail.

FREE CHECKUP

Free server checkup

We will send a problem checklist and remediation advice within one business day — no obligation to engage.

135 410 16684
Weekdays Mon – Fri 10:00 – 22:00 (UTC+8) · 7×24 emergency response
Call now
CONTACT

Contact Us

How can we help?

* Required