Details about nodes in the server. xml file in Tomcat

Source: Internet
Author: User
Tags generate csr openssl x509 arch linux godaddy ssl certificate

Because Tomcat is based on Java, the configuration methods in various Linux releases are similar, but I have seen few articles about tomcat in the arch Linux environment, so I tried it again in arch Linux and obtained this article. This article assumes that you are not very familiar with tomcat, and the main ink will be placed on the tomcat configuration.

1. install Java JDK

There are jdk7-openjdk and openjdk6 in the extra source of arch Linux, you can directly use Pacman installation, as to which one can be selected depends on the specific situation. I installed openjdk 7:

$ sudo pacman -S jdk7-openjdk
2. install Tomcat

Similarly, the extra source already has Tomcat versions 5, 6, and 7, which can be determined based on the actual situation. I have installed Tomcat 6 here.

$ sudo pacman -S tomcat6

By default, the installation path of Tomcat 6 is/usr/share/tomcat6. The main directory functions are listed here (the arrow indicates the actual location of the Directory link ):

  • /Usr/share/tomcat6: The main directory of the program. It is also the position pointed to by the variable $ catalina_home. In the case of a single Tomcat instance, it is also the position pointed to by the variable $ catalina_base.
  • Conf->/etc/tomcat6: configuration file directory.
  • Lib->/usr/share/Java/tomcat6: Shared jar package directory. These packages are used by Tomcat and referenced by web applications.
  • Logs->/var/log/tomcat6: log directory, which is helpful for finding errors and viewing access records.
  • Webapps->/var/lib/tomcat6/webapps: the default web application directory. Tomcat 6 contains several sample programs, which are described below.

Now you can try to start the Tomcat service:

$ sudo /etc/rc.d/tomcat start

Check the startup script configuration file/etc/CONF. the value of the tomcat_java_home variable in D/tomcat6 should be in/opt/Java during Java runtime in my installation (you can see it with $ which Java:

Tomcat_java_home =/usr/lib/JVM/java-7-openjdk can be changed to the following: tomcat_java_home =/opt/Java

Restart the Tomcat service:

$ sudo /etc/rc.d/tomcat6 restart

Generally, there should be no problem. Open any browser and enter "http: // localhost: 8080" in the address bar. If you see Tomcat cat, it indicates that the service is properly installed and runs properly.

3. Know the webapps directory

This directory is located under the installation directory of Tomcat 6, and the actual content is located in/var/lib/tomcat6/webapps. Each directory in the webapps directory corresponds to a web application. For example, the access address of the docs directory is http: // localhost: 8080/docs, And the access address of the Manager directory is http: // localhost: 8080/manager. The special one is the root directory. Its access address is the root directory of the website, that is, http: // localhost: 8080 /.

You can access the sample programs that come with Tomcat one by one. The manager and host-manager applications are configured with login authentication required for access, the method to add a login user is to edit the configuration file CONF/tomcat-users.xml under the tomcat installation directory (which is actually the file/etc/tomcat6/tomcat-users.xml), 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, that is, you can log on to and access the two applications of manager and host-manager by using the username Tomcat and password tomcat.

EachJava Web ApplicationsAll have the followingDirectory structure:

  • /Index.html resources directly accessed by visitors, such as static images and CSS style sheets.
  • /WEB-INF/resources that visitors cannot directly access.
  • /WEB-INF/classes application JAVA Source Code Compiled class file.
  • /WEB-INF/configuration file for the Web. XML application.
  • The package referenced by the/WEB-INF/lib application.

Of course, not all of them are required. You can even create a directory, such as "hello", and then create only one index.html file (whatever the content is) in it, that is, you can use http: // localhost: 8080/Hello/index.html. (Of course, this is not a web application. This method is only used for testing)

Use Apache Maven to create a simple web application. Run 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 project. Choose version: Input 5, that is, Version 1.0. Define value for property 'groupid': Enter org. Test. Define value for property 'artifactid': Enter the demo. Define value for property 'version': Type 1.0. Define value for property 'package': Enter org. Test. Demo confirm properties configuration: Press ENTER

Maven-related knowledge is not covered in this article. If you are not familiar with it, please refer to the free Chinese e-book Maven in action, maven is one of the most common tools for building and managing Java projects.

Now you should see a directory named demo. After entering it, you can use Maven to package the project:

$ cd demo $ mvn package

The packaged file is./target/demo. War. copy the file to the webapps directory:

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

Because the site created by Tomcat by default will automatically deploy the application, the file demo copied to the webapps directory just now. war will be automatically decompressed. Check the webapps directory and you will find an extra directory named demo. Now you can try to access http: // localhost: 8080/demo in the browser, we should see "Hello world!" This is the result of running the web application just created with Maven.

It should be noted that the war file generated after the Java Web application is packaged does not have to be decompressed before it can be run. This will be discussed in the configuration in the next section.

4. Understand the main configuration file server. xml of Tomcat

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

As shown in the extension of the file, this is an XML file. After opening the file, you will see 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>

That is,Server-> service-> engine-> host-> ContextThe layer-4 structure, from the layer to the outer layer:

  • Context: A web application. A context is a Web application.
  • Host: It is a virtual host. For example, www.dog.com corresponds to one virtual host, and api.dog.com corresponds to another virtual host. A host is used to define a virtual host. (A "virtual host""Can be simply understood as" a website")
  • Engine: a set of virtual hosts.. For example, www.dog.com and api.dog.com can form a set of virtual hosts.
  • Service: a set of enginesIncluding the definition of thread pool executor and connector ctor.
Connector configuration

A connector is a port opened to the outside world. A simple understanding is the combination of IPaddress: port that most network service programs will encounter. For example, 192.168.0.10: 8080 is a port, of course, the content that can be defined in connector is much richer, that is, many attributes can be added to the XML node of connector. Below are some common examples:

  • Enablelookups:( Default = true) whether to allowReverse resolution of the visitor's IP addressWhen your application uses request. getremotehost (), if you only need an IP address, we recommend that you disable this option to save time for Reverse Domain name resolution.
  • Maxpostsize:( Default = 2097152 (2 MB)Maximum size of data uploaded by post(Unit: byte). For general websites, for example, websites that write comments and write articles, the default 2 Mb is enough. However, if the website has the image or even file upload function, it depends on the specific situation.
  • Protocol: connector typeTomcat 6 has the following options:
    • Org. Apache. Coyote. http11.http11protocol: abbreviated as "HTTP/1.1". This is the default connector. A guest network connection requires a thread and has low concurrency performance.
    • Org. Apache. Coyote. http11.http11nioprotocol: NiO connector, a connector consisting of a non-blocking Socket working mode, with good concurrency and pure Java implementation.
    • Org. apache. coyote. http11.http11aprprotocol: APR connector. The so-called APR is the library used by Apache HTTP Server, the Web service program used by the most servers on the network. Tomcat is recommended for use in the production environment. The specific method is described below.
  • Redirectport: When a user accesses a non-HTTPS resource and the resource requires HTTPS access, Tomcat will automatically redirect to the HTTPS port. Generally, https uses TCP port 443, so the value is generally"443″.
  • Sslenabled :( default = false ),Sets whether the current connector uses secure SSL transmission. If it is set to "true", the following two attributes should be set at the same time: Scheme = "HTTPS" (default = http) it can be set to HTTP or HTTPS. Secure = "true" (default = false ).
  • Adress: IP address bound to the connectorWhen a server has multiple IP addresses, you can specify one of them to be bound,Not set by defaultThe value of this attribute indicates binding all IP addresses of the current server.
  • Compressablemimetype :( default = "text/html, text/XML, text/plain ")Specifies the type of resources that require gzip compression.
  • Compression :( default = OFF) Whether to enable gzip CompressionYou can set the value to On/Off/force. After the value is set to on, Gzip compression is enabled for the resource type specified in the compressablemimetype attribute.
  • Connectiontimeout:( Default = "60000") when the visitor's network is connected, the serverThe time when the first request header appears.. The Unit is milliseconds.
  • Executor: Specifies the name of the thread pool used by the current connector. If it is specified, other settings for the number of threads are ignored, such as maxthreads.
  • Maxthreads(Default = 200) the maximum number of threads that can be created.
  • Port = "80": Port bound.
  • Keepalivetimeout(Default = connectiontimeout) indicates the time when a visitor maintains the network connection after completing 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 the shared thread pool. By default, each ctor generates its own thread pool. If you want multiple ctor ERs to share one thread pool, you can first define a thread pool, for example:

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

Modify the connector configuration and add 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 is 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>

The role of each attribute of the host configuration node:

  • Name: Set the virtual host domain name. For example, localhost indicates the name of the local host. In actual applications, enter a specific domain name, such as www.dog.com or dog.com. If the virtual host is accessed by internal personnel, you can also enter the IP address of the server, for example, 192.168.1.10.
  • Autodeploy: Whether automatic deployment is allowed. The default value is true, indicating that Tomcat will automatically detect file changes under the appbase directory and apply them to running Web applications.
  • Unpackwars: Set whether to automatically expand the war package and run the web application. The default value is true.
  • Appbase: Set the path of the Web application group. As mentioned above, a virtual host can be composed of multiple web applications. Therefore, the directory to which appbase points should be the directory used to store this group of Web applications, instead of the specific directory of a Web application (even if the VM is composed of only one web application ). The value of the appbase attribute can be relative to the tomcat installation directory or an absolute path. Note that the path must be accessed by Tomcat, tomcat installed from the arch Linux source is run by the Tomcat user. Therefore, after creating a new appbase directory, you can use the CHOWN command to change the directory owner.

The following example shows how to create a new virtual host www.dog.com:

Under/var/lib/tomcat6, you can see the default webapps directory created during tomcat installation, to facilitate the management of the VM file we will create, we will also create it in/var/lib/tomcat6:

$ sudo mkdir dog

Then, create the root directory in the dog directory, and then create the file index.html in the root directory (whatever the content is ).

Change the directory owner and all groups to Tomcat:

$ sudo chown -R tomcat:tomcat dog

Then add the following host nodes under the host node of server. xml:

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

Restart Tomcat service can access this new virtual host through the address http://www.dog.com in the browser, of course, you must first add www.dog.com to 127.0.0.1 resolution records in the/etc/hosts file, as follows:

127.0.0.1    www.dog.com

Sometimes a VM may bind multiple domain names, such as www.dog.com and dog.com. You can add alias to the host configuration node, for example:

<Alias>dog.com</Alias>

In addition, the <valve classname =... /> Configure the storage location and file name of access logs for the visitor.

Engine configuration

The default engine node is as follows:

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

This should not be described in detail. defaulthost is used to specify the default Virtual Host Name of Tomcat when a visitor does not have a corresponding virtual host. Consider the following situations:

Assume that all three domain names are resolved to your server through DNS, such as dog.com, www.dog.com, and api.dog.com. Currently, you have only configured the virtual hosts dog.com and www.dog.com, when a visitor accesses your server through api.dog.com, Tomcat returns the running result of one of the virtual hosts Based on the defaulthost settings. In actual application, defaulthost should be set as your main domain name, such as www.dog.com.

5. Configure multiple sites: set multiple host nodes

Sometimes we need to run multiple sites on one server, which can be easily achieved through tomcat. Let's assume that we want to build www.dog.com and www.cat.com.

First, make sure that the DNS of your two domain names can be correctly resolved to your server, because we are doing experiments here, so you can add domain name resolution on the local machine. Modify the/etc/hosts file and add the following two lines:

127.0.0.1    www.cat.com127.0.0.1    www.dog.com

Create two directories named cat and dog in the/var/lib/tomcat6 directory, and create the directory named root in each directory, and create the file index.html in the root file (the content is casual ). Then, change the owner and all groups of the cat and dog directories to Tomcat. For more information about the methods, see the previous section.

Now, edit the Tomcat master configuration file 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>

In the host node, you can add the required attributes or alias and value subnodes according to the instructions in the previous section. Restart the Tomcat service and now you should be able to browse both sites in your browser via http://www.dog.com and http://www.cat.com.

6. Use NiO Connector

The default connector has poor concurrency performance. It doesn't matter if the site's concurrent access volume is small, or you may not be able to understand this in the company's Intranet (because each request on the Intranet may be completed within one second). After the environment is changed to the Internet, it is possible that each customer's request will be transmitted in seconds or even tens of seconds on the network, which will lead to the phenomenon that "many visitors are connected at the same time, when all threads of the Tomcat Connector are occupied, the later (visitor) will be stuck out of the door. Therefore, we 'd better change the default connector to NiO connector (Non Blocking Java connector) in the actual environment ). The method is simple. You only need to change the Protocol attribute value of the connector node to org. Apache. Coyote. http11.http11nioprotocol. For example, the original method is as follows:

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

To:

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

Restart the Tomcat server.

7. Add an SSL Certificate for the website

Sometimes websites may involve important business data. It is best to transmit these pages over the Internet through HTTPS to prevent important information from being stolen by intermediate links.

For details, refer to my previous article "add a Godaddy SSL certificate to your website". This article describes how to apply for a signed SSL Certificate and how to modify tomcat configuration. If you just want to test how to add https for a website, or simply Use https on a company's internal website, you can use a simple method: Use a self-Signed SSL certificate. A self-Signed SSL certificate is a self-generated certificate that has not been signed by a third-party certificate provider. Therefore, when you browse such a website, the browser will prompt a certificate error, however, visitors can continue browsing the website content.

Let's assume that we want to add an SSL Certificate for www.dog.com in the previous section. First, use the built-in keytool of Java to generate a keystore file (a file format used to store certificates). Execute the following command in your own directory:

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

Then it will prompt you to set a password and enter the DN information:

Enter keystore password: set a password to protect your keystore file. For example, 123456re-enter new password: Repeat the password above. What is your first and last name? [UNKNOWN]: www.dog.com (the domain name) What is the name of your organizational unit? [UNKNOWN]: networking organization unit name (casually) What is the name of your organization? [UNKNOWN]: dog.com Organization Name (casually) What is the name of your city or locality? [UNKNOWN]: The city where Shenzhen is located (casually) What is the name of your state or province? [UNKNOWN]: the province where Guangdong is located (whatever) What is the two-letter country code for this unit? [UNKNOWN]: Is Cn = www.dog.com, ou = networking, O = dog.com, L = Shenzhen, St = Guangdong, c = cn correct? [No]: If yes and above are correct, enter yesenter key password for (return if same as keystore password): Press enter directly.

A tomcat. keystore file is generated in the current directory. Copy this file to the root directory of the dog website application (/var/lib/tomcat6/dog ):

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

Modify the Tomcat master configuration file server. xml and add the following new ctor 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 replace the Protocol attribute value with http11nioprotocol, that is:

<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 and access the https://www.dog.com in the browser, the browser may prompt a certificate error, ignore it (for Firefox, you also need to click the "add exception" button to ignore) you can see that the web page is already viewed through HTTPS.

8. Use APR high-performance connectors

APR is Apache Portable Runtime, which provides high-performance features of Apache HTTP. The features of common connectors, NiO, and APR are relatively simple (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

The latter is recommended in the Tomcat document between NiO and APR. Since I have no actual environment (that is, a large number of accesses from the internet) for detailed testing and comparison, I am not quite sure about the differences between the two. The following describes how to use APR:

First install the local library of APR for Tomcat and OpenSSL (if you need to use the SSL certificate and the system has not been installed), the local source of arch Linux already exists, so the installation method is simple:

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

Modify the Tomcat main configuration file server. xml and change the attribute value of connector protocol 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: it is also possible to retain the Protocol = "HTTP/1.1" attribute value)

Then restart the Tomcat service. How do I know whether to use the APR connector? You only need to check the Tomcat log file. The default log file is/var/log/tomcat6/Catalina. Err:

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

If the following red text is displayed at the end of the log after the Tomcat service is restarted, the APR connector is successfully used.

Feb 19,201 2 9:44:05 am org. Apache. Coyote. http11.Http11aprprotocolStart info: Starting coyote HTTP/1.1 on http-80 Feb 19,201 2 9:44:05 am org. Apache. Coyote. http11.Http11aprprotocolStart info: Starting coyote HTTP/1.1 on http-443 Feb 19,201 2 9:44:05 am org. Apache. Catalina. startup. Catalina start info: server startup in 1281 MS

If you use the APR connector and need to add an SSL Certificate (that is, the HTTPS access function is required), you need to use the OpenSSL method to generate an encryption private key and modify the corresponding ctor configuration, the example in section 7th above is to add an SSL Certificate for the www.dog.com site.

Use OpenSSL to generate the private key and self-signature. Run the following command in your own 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 7th above, you are required to enter the DN information in the middle. After the information is completed, 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

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 the Tomcat service is restarted.

Last

This article describes how to install Tomcat 6 in arch Linux, modify the main configuration file, set up multiple sites, add SSL certificates, and use high-performance NiO and APR connectors.

Details about nodes in the server. xml file in Tomcat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.