Tomcat deployment and optimization

1, Introduction

Tomcat server is a free open source Web application server, which is a lightweight application server,
It is widely used in small and medium-sized systems and not many concurrent access users. It is the first choice for developing and debugging JSP programs.
For a beginner, you can think that when you configure Apache server on a machine, you can
It is used to respond to the access request of HTML (an application under the standard General Markup Language) page.
In fact, Tomcat is an extension of Apache server, but it runs independently at runtime, so when you run tomcat,
It actually runs as a separate process from Apache

The trick is that when configured correctly, Apache serves HTML pages, while Tomcat actually runs JSP pages and servlets.
In addition, like IIS and other Web servers, Tomcat has the function of processing HTML pages,
In addition, it is also a Servlet and JSP container. The independent Servlet container is the default mode of Tomcat.
However, Tomcat does not handle static HTML as well as the Apache server.

2, Tomcat installation

1. Install JDK package

[root@localhost opt]# rpm -ivh jdk-8u201-linux-x64.rpm

2. Add environment variables

[root@localhost java]# vim /etc/profile

Add on last line

export JAVA_HOME=/usr/java/jdk1.8.0_201-amd64
export CLASSPATH=$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar
export PATH=$JAVA_HOME/bin:$PATH

Save exit and refresh file

[root@localhost java]# source /etc/profile

3. Unzip the Apache package

[root@localhost opt]# tar -zxf apache-tomcat-9.0.16.tar.gz 
[root@localhost opt]# cp -r apache-tomcat-9.0.16 /usr/local/tomcat

4. Check Tomcat

[root@localhost opt]# cd /usr/local/tomcat/bin/
[root@localhost bin]# ls
bootstrap.jar       commons-daemon-native.tar.gz  makebase.sh       tomcat-juli.jar
catalina.bat        configtest.bat                setclasspath.bat  tomcat-native.tar.gz
catalina.sh         configtest.sh                 setclasspath.sh   tool-wrapper.bat
catalina-tasks.xml  daemon.sh                     shutdown.bat      tool-wrapper.sh
ciphers.bat         digest.bat                    shutdown.sh       version.bat
ciphers.sh          digest.sh                     startup.bat       version.sh
commons-daemon.jar  makebase.bat                  startup.sh
[root@localhost bin]# ./startup.sh 
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/java/jdk1.8.0_201-amd64
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Tomcat started.
[root@localhost bin]# ./shutdown.sh 

5. Create a new user and change the Tomcat file's primary group

[root@localhost bin]# useradd -s /sbin/nologin tomcat
[root@localhost local]# cd /usr/local/
[root@localhost local]# chown tomcat:tomcat tomcat/ -R

6. Write Tomcat Service file

[root@localhost local]# vim /etc/systemd/system/tomcat.service
[root@localhost local]# systemctl daemon-reload 
[root@localhost local]# systemctl start tomcat.service
[root@localhost local]# ss -ntap |grep 8080
LISTEN     0      100         :::8080                    :::*                   users:(("java",pid=3604,fd=54))

3, Profile introduction and core components

1. Configuration file

Directory namefunction
binSave the script files for starting and closing Tomcat. Catalina. Com is commonly used sh,startup.sh,shutdown.sh three files
confStore various configuration files of Tomcat server, and the more commonly used is server xml,context.xml,tomcat-users.xml,web.xml four files.
libThe jar package for storing the Tomcat server is generally unchanged. Unless a third-party service, such as redis, is connected, the corresponding jar package needs to be added
logsStore Tomcat logs
tempStore the files generated by Tomcat runtime
webappsDirectory where project resources are stored
workTomcat working directory is generally used when clearing Tomcat cache

conf subdirectory

file nameexplain
server.xmlMaster profile
web.xmlEach webapp can only be accessed after "deployment". Its deployment mode is usually defined by web.xml and stored in the WEB-INF / directory. This file provides default deployment related configuration for all webapps. Each web application can also use a special configuration file to overwrite the global file
context.xmlIt is used to define the Context configuration that all web applications need to load. This file provides the default configuration for all webapps. Each web application can also use its own special configuration. It is usually composed of a special configuration file Context XML, which is stored in the WEB-INF / directory and overwrites the global file
tomcat-users.xmlUser authentication account and password file
catalina.policyUsed to set the security policy for tomcat when using the security option to start omcat
catalina.propertiesThe configuration of Tomcat environment variables is used to set classloader paths and some parameters related to JVM tuning
logging.propertiesTomcat log system related configuration, you can modify the log level and log path

Configuration files are case sensitive

2. Core components

nameexplain
serverServer, the process instance running Tomcat. There can be multiple service s in a server, but usually only one
serviceService is used to organize the correspondence between Engine and Connector. There is only one Engine in a service
connectorConnector, which is responsible for the connection of HTTP, HTTPS, AJP and other protocols of the client. A connector belongs to only one Engine
EngineThe Engine is used to respond to and process user requests. Multiple connectors can be bound to an Engine
HostThat is, virtual hosts can realize multiple virtual hosts, for example, using different host headers to distinguish
ContextConfigure the mapping relationship between specific URL path mapping and directory according to the application context: url = > directory

tomcat is a container in which there are three core components:
WEB, Servlet and JSP, so Tomcat is extremely lightweight, and the core components are components that support basic operation

3. Homepage file priority

Global configuration

[root@localhost conf]#vim /usr/local/tomcat/conf/web.xml
<welcome-file-list>
         <welcome-file>index.html</welcome-file>
         <welcome-file>index.htm</welcome-file>
         <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Local configuration

Copy web XML file
Change the primary group of the file

[root@localhost blog]#chown tomcat:tomcat WEB-INF/ -R

4.jar package packaging

[root@localhost webapps]# mkdir /data
[root@localhost webapps]# cd /data/
[root@localhost data]# ls
[root@localhost data]# mkdir app1/
[root@localhost data]# cd app1/
[root@localhost app1]# vim test.html
<h1> test </h1>
[root@localhost app1]# vim test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<! DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>jsp example</title>
</head>
<body>
The following content is dynamically generated strings on the server side, and finally spliced together
<%
out.println ("test jsp");
%>
%<br>
<%=request.getRequestURL()%>
</body>
</html>
[root@localhost app1]# jar cvf /opt/app1.war *
Added manifest
 Adding: test.html(input = 24) (output = 23)(Compressed 4%)
Adding: test.jsp(input = 346) (output = 298)(Compressed 13%)
[root@localhost opt]# cd /usr/local/tomcat/webapps/
[root@localhost webapps]# ls
docs  examples  host-manager  manager  ROOT
[root@localhost webapps]# cp /opt/app1.war /usr/local/tomcat/webapps/
[root@localhost webapps]# ls
app1.war  docs  examples  host-manager  manager  ROOT
[root@localhost webapps]# ls
app1  app1.war  docs  examples  host-manager  manager  ROOT

4, Virtual host configuration

Sometimes the company may have multiple projects to run, so it is certainly impossible to run multiple projects on one server
Tomcat service, which will consume too many system resources. At this point, you need to use the Tomcat virtual host. For example, now
Add two new domain names www.wwd.com com,www.accp.com hopes to access different project contents through these two domain names.

[root@localhost tomcat]# cd webapps/
[root@localhost webapps]# mkdir wwd accp
[root@localhost webapps]# echo "this wwd web" > wwd/index.html
[root@localhost webapps]# echo "this accp web" > accp/index.html
[root@localhost webapps]# cat wwd/index.html accp/index.html 
this wwd web
this accp web
[root@localhost webapps]# vim /usr/local/tomcat/conf/server.xml 
<Host name="www.wwd.com" appBase="/usr/local/tomcat/webapps"
            unpackWARs="true" autoDeploy="true" xmlValidation="false"
            xmlNamespaceAware="false">
                <Context docBase="/usr/local/tomcat/webapps/wwd"
                path="" reloadable="true" />
      </Host>

      <Host name="www.accp.com" appBase="/usr/local/tomcat/webapps"
            unpackWARs="true" autoDeploy="true" xmlValidation="false"
            xmlNamespaceAware="false">
                <Context docBase="/usr/local/tomcat/webapps/accp"
                path="" reloadable="true" />
       </Host>

5, Tomcat configuration file parameter optimization

About Tomcat main configuration file server There are many default configuration items in XML, but they can't meet business requirements,
Common optimization related parameters are as follows

[maxThreads] Tomcat uses threads to process each received request. This value represents the maximum number of threads that Tomcat can create. The default value is 200.

[minSpareThreads] the minimum number of idle threads, which is the number of initialized threads when Tomcat is started. It means that so many empty threads are opened to wait even if no one is using them. The default value is 10

[maxSpareThreads] the maximum number of spare threads. Once the created thread exceeds this value, Tomcat will close socket threads that are no longer needed. The default value is - 1 (unlimited). Generally, it is not necessary to specify

[URIEncoding] specify the URL encoding format of Tomcat container. The language encoding format is not as convenient as other Web server software configuration, and utf-8 needs to be specified respectively

[connectiontimeout] network connection timeout, unit: Ms. if it is set to 0, it means never timeout. This setting has hidden dangers. It usually defaults to 20000 milliseconds (20 seconds)

[enableLookups] whether to reverse query the domain name to return the host name of the remote host. The values are: true or false,
If it is set to false, the IP address will be returned directly. In order to improve the processing capacity, it should be set to false.

[disableUploadTimeout] whether to use the timeout mechanism when uploading. It should be set to true.

[connectionUploadTimeout] upload timeout. After all, file upload may take more time,
This is adjusted according to your own business needs, so that the Servlet has a long time to complete its execution
It takes effect only when used in conjunction with the previous parameter

[acceptCount] specifies that connection requests can be passed in when all available threads for processing requests are used
The maximum queue length. Requests exceeding this number will not be processed. The default is 100.

[compression] whether to GZIP compress the response data. off: it means to prohibit compression; on: it means to allow compression
Compression (text will be compressed), force: indicates that compression is performed in all cases. The default value is off and the data is compressed
It can effectively reduce the size of the page, generally about 1 / 3, and save bandwidth.

[compressionMinSize] indicates the minimum value of compression response. Only when the response message size is greater than this value
The message will be compressed. If the compression function is enabled, the default value is 2048

[compressableMimeType] compression type, which specifies which types of files to compress data.

[noCompressionUserAgents = "gozilla, traviata"] for the following browsers, compression is not enabled

If the dynamic and static separation of code has been carried out, the data such as static pages and pictures do not need to be processed by Tomcat, then
You don't need to configure compression in Tomcat. Because there is only one Tomcat server here, and the pressure test is the Tomcat home page, there will be pictures and static resource files, so compression is enabled here.

The above are some common configuration parameters, and there are many other parameter settings. You can continue to further optimize HTTP
The parameter attribute values of Connector and AJP Connector can be learned by referring to the detailed instructions in the official documents. Link address http://tomcat.apache.org/tomcat-9.0-doc/config/http.html

Keywords: Apache Tomcat server

Added by imperialized on Mon, 20 Dec 2021 22:05:34 +0200