Tomcat server deployment (optimization) and virtual host configuration


One, Tomcat server

1 Introduction

Origin of the name:
Tomcat was originally developed by Sun’s software architect James Duncan Davidson. Later, he helped turn it into an open source project and contributed to the Apache Software Foundation by Sun.
As most open source projects O'Reilly will produce one This book is related to this book, and the cover is designed as a sketch of a certain animal, so he hopes to name this project after an animal
because he hopes that this animal can take care of itself, and finally, he named it Tomcat (English Male cats or other male cats)
and O’Reilly’s book on Tomcat’s cover is also designed as a male cat, and Tomcat’s logo and mascot are also designed as a male cat.
mark
Actually, Tomcat was the first It was not called this name during the development. The name of the early Tomcat project was Catalina, so when we install Tomcat, we will find that there are many catalogs and files related to Catalina under the installation path, and these files are usually used or configured by Toncat Important documents

2. Application scenarios

  • Tomcat server is a free and open source web application server, which is a lightweight application server. It is commonly used in small and medium-sized systems and where there are not many concurrent users. It is the first choice for developing and debugging JSP programs.
  • Generally speaking, although Tomcat is the same as Apache or Nginx Web servers, it has the function of processing HTML pages, but because its ability to handle static HTML is far less than Apache or Nginx, Tomcat is usually used as a Servlet and JSP container, running separately rear end

Some supplement

Java Servlet:

  1. A program running on a Web server or application server, which acts as an intermediate layer between the request from a Web browser or other HTTP client and the database or application on the HTTP server
  2. Using Servlet, you can collect user input from web forms, present records from databases or other sources, and dynamically create web pages
  3. Similar to CGI (Common Gateway Interface) function

JSP(Java Server Pages):

  1. A Dynamic Web Development Technology
  2. It uses JSP tags to insert Java code in HTML pages, and the signature usually starts with <% and ends with %>
  3. JSP is a Java servlet, mainly used to implement the user interface part of a Java web application
  4. JSP obtains user input data through web forms, accesses databases and other data sources, and then dynamically creates web pages

3. Components

Tomcat consists of a series of components, of which there are three core components

name Features
Web container Complete the function of the Web server
Servlet container The name is catalina, used to process Servlet code
JSP container Used to translate JSP dynamic web pages into Servlet code

Two, Tomcat deployment steps

1. Environment

The following is the native environment:

  • Windows 10 Professional Workstation Edition
  • VMware 16 Pro(16.0.1.0)
  • CentOS 7
  • Local YUM source
  • The network card is configured to obtain an IP address statically
  • The network adapter is in NAT mode
  • The IP address is 192.168.126.15
  • apache-tomcat-9.0.16
  • jdk-8u201-linux-x64

2. Preparation

  1. Turn off the firewall and force control access to the system after startup
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
  1. JDK must be installed before installing Tomcat
  • The full name of JDK is (Java Development Kit), which is a Java language software development kit provided by Sun for free
  • It contains the Java Virtual Machine (JVM), the compiled Java source program can be compiled to form Java bytecode
  • As long as the JDK is installed, the JVM can be used to interpret these bytecode files, thus ensuring the cross-platform nature of Java
  • In terms of platform compatibility, JDK, as a Java virtual machine that interprets bytecode files and calls operating system APIs to implement corresponding functions, is closely related to the type of operating system and the number of platforms, so there are different types of versions.
  • And Tomcat also has the above features, so you need to download JDK and Tomcat in advance

Software package portal : https://pan.baidu.com/s/1Xl95R5OW4c6oozF4l4zfyA (Extraction code: 12do)

After downloading, use Xshell to directly drag the two software packages to the /opt directory
mark

3. Install JDK, configure Java environment

  1. Install directly using rpm
cd /opt
rpm -qpl jdk-8u201-linux-x64.rpm
#查看指定文件的文件列表
rpm -ivh jdk-8u201-linux-x64.rpm
#安装
java -version
#显示java运行环境版本

mark
mark

  1. Create a script to set JDK environment variables
vim /etc/profile.d/java.sh

export JAVA_HOME=/usr/java/jdk1.8.0_201-amd64
#输出定义java的工作目录
export CLASSPATH=.:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar
#输出指定java所需的类文件
export PATH=$JAVA_HOME/bin:$PATH
#输出重新定义环境变量,$PATH一定要放在$JAVA_HOME的后面,让系统先读取到工作目录中的版本信息!


source /etc/profile.d/java.sh
#执行脚本
java -version
#再次查看,检查是否执行成功

mark
mark

supplement Description
CLASSPATH When compiling and running a Java program, JRE will search for the required class (.class) file in the path specified by the variable
dj.jar It is about the class library of the operating environment, mainly the swing package
tools.jar Mainly some libraries of jdk tools, including javac, java, javap, javadoc, etc.
JDK java development kit (java development tool)
JRE java runtime environment (java runtime environment)
JVM java virtuak machine (java virtual machine), so that java programs can run class files on multiple platforms
  1. Write a simple java file to verify again
vim zxc.java

public class zxc {
    
    
        public static void main(String[] args){
    
    
        System.out.println("Hello world!");
        }
}


javac zxc.java
#进行编译
java zxc
#执行

mark
mark

4. Install and configure Tomcat

  1. Unzip the package
cd /opt
tar zxvf apache-tomcat-9.0.16.tar.gz
  1. Generate a folder after decompression, move the folder to /usr/local/, and rename it to tomcat
mv apache-tomcat-9.0.16 /usr/local/tomcat
  1. Start Tomcat
/usr/local/tomcat/bin/startup.sh

mark
4. Tomcat runs on port 8080 by default, you can run the netstat command to view the information monitored on port 8080

[root@localhost opt]# netstat -natp | grep 8080
tcp6       0      0 :::8080                 :::*                    LISTEN      16690/java
  1. Open the browser to access the test http://192.168.126.15:8080/
    mark

  2. If you want to close Tomcat, you can run the following command

/usr/local/tomcat/bin/shutdown.sh

5. Description of main catalog

Tomcat's home directory is /usr/localtomcat

mark

table of Contents Description
bin Stores script files for starting and shutting down Tomcat on Windows or Linux platforms
conf Store various global configuration files of the Tomcat server, the most important of which are server.xml and web.xml
lib Store the library files (JARS) needed for Tomcat operation, generally do not make any changes, unless you connect to a third-party service, such as redis, then you need to add the corresponding jar package
logs Store the LOG file (log) during Tomcat execution
temp Store files generated when Tomcat is running
webapps Tomcat’s main Web publishing directory (including application examples) is a directory for storing project resources
work Tomcat working directory, storing class files generated after jsp compilation, generally used when clearing Tomcat cache

Three, Tomcat virtual host configuration

  • Many times the company has multiple projects to run, so it is certainly impossible to run multiple Tomcat services on one server, which will consume too much system resources
  • At this point, you need to use the Tomcat virtual host
  • For example, two new domain names, www.xcf.com and www.zxc.com are now added, and I hope to access different project contents through these two domain names

1. Create directories and files

mkdir /usr/local/tomcat/webapps/xcf
mkdir /usr/local/tomcat/webapps/zxc

#在目录下创建默认首页文件,并注入内容,用以测试

echo "Hello Xcf~" > /usr/local/tomcat/webapps/xcf/index.jsp
echo "Hello Zxc~" > /usr/local/tomcat/webapps/zxc/index.jsp

2. Modify the Tomcat main configuration file

vim /usr/local/tomcat/conf/server.xml

#在165行插入以下内容
<Host name="www.xcf.com" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<Context docBase="/usr/local/tomcat/webapps/xcf" path="" reloadable="true" />
</Host>

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

mark

supplement Description
Host name CPU name
appBase Tomcat program working directory, relative path is webapps, absolute path is /usr/local/tomcat/webapps
unpackWARs Whether to unzip the war package
autoDeploy Instruct Tomcat to allow automatic deployment if there are new web applications
xmlValidation Whether to verify the xml file to perform the validity check flag
xmlNamespaceAware Whether to enable the xml namespace, set this value and xmlValidation to true, which means that the validity check of the web.xml file is performed
appBase WEB application catalog
path Set the visited URI to the root directory of the web application
reloadable Whether to reload when the program is changed

3. Turn off Tomcat and restart

/usr/local/tomcat/bin/shutdown.sh
/usr/local/tomcat/bin/startup.sh

mark

4. Visit the browser to verify

#首先在主机映射文件中追加IP与对应域名
echo "192.168.126.15 www.xcf.com" >> /etc/hosts
echo "192.168.126.15 www.zxc.com" >> /etc/hosts
  • Visit http://www.xcf.com:8080
    mark
  • Visit http://www.zxc.com:8080
    mark

Fourth, Tomcat optimization

  • The default configuration under Tomcat's default installation is not suitable for the production environment. It may frequently appear suspended and needs to be restarted. Only through continuous stress testing and optimization can it run with the highest efficiency and stability.
  • Optimization mainly includes three aspects: operating system optimization (kernel parameter optimization), Tomcat configuration file parameter optimization, and Java virtual machine (JVM) tuning

1. Optimize startup speed

第一次启动查看日志会发现 Tomcat 启动很慢,默认情况下可能会需要几十秒  
可以修改jdk参数进行优化

vim /usr/java/jdk1.8.0_201-amd64/jre/lib/security/java.security

 #117行
 securerandom.source=file:/dev/urandom
#random和urandom都属于伪终端,都能提供数据流,但是后者速度更快


/usr/local/tomcat/bin/shutdown.sh 
/usr/local/tomcat/bin/startup.sh 
#重启生效

2. The commonly used optimization related parameters are as follows:

vim /usr/local/tomcat/conf/server.xml

minSpareThreads="50" 
#最小空闲线程数为50
enableLookups="false"
#不开启反查域名
disableUploadTimeout="true"
#上传时使用超时机制
acceptCount="300" 
#线程数都被占用时,可传入最大连接请求队列为300
maxThreads="500"
#可创建的最大线程数为500
processorCache="500"
#控制Tomcat内部RequestProcessor的缓存池大小,若超过500,则会创建新的RequestProcessor实例
URIEncoding="UTF-8" 
#字符集为UTF-8
compression="on"
#开启对响应的数据进行GZIP压缩
compressionMinSize="2048"
#压缩响应最小值,开启则默认2048,只有大于该值时才会对报文进行压缩
compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,image/gif,image /jpg,image/png"/>
#压缩可支持类型

mark

Option name Parameter setting
maxThreads Tomcat uses threads to process each request received. This value represents the maximum number of threads that Tomcat can create. The default value is 200
minSpareThreads The minimum number of idle threads, the number of threads initialized when Tomcat starts, means that there are so many empty threads waiting even if no one is using it. The default value is 10
maxSpareThreads The maximum number of standby threads. Once the number of threads created exceeds this value, Tomcat will shut down socket threads that are no longer needed. The default value is -1 (unlimited). Generally do not need to specify
URIEncoding 指定 Tomcat The URL encoding format and language encoding format of the container are not as easy to configure as other Web server software, and need to be specified separately
connnectionTimeout Network connection timeout, unit: milliseconds, set to 0 means never time out, this setting has hidden dangers. Usually the default is 20000 milliseconds
enableLookups Whether to reverse check the domain name to return the host name of the remote host, the value is: true or false, if it is set to false, the IP address is returned directly, in order to improve the processing capacity, it should be set to false
disableUploadTimeout Whether to use the timeout mechanism when uploading. Should be set to true
connectionUploadTimeout Upload timeout. After all, file upload may take more time. Adjust this according to your own business needs, so that the Servlet has a longer time to complete its execution. It needs to be used in conjunction with the previous parameter to take effect.
acceptCount Specify the maximum queue length for incoming connection requests when all available threads for processing requests are used. Requests exceeding this number will not be processed. The default is 100
compression Whether to perform GZIP compression on the response data, off: means compression is prohibited; on: means compression is allowed (text will be compressed), force: means compression is performed in all cases, the default value is off, which can effectively reduce pages after compressing data The size can generally be reduced by about 1/3 to save bandwidth
compressionMinSize Indicates the minimum value of the compressed response. Only when the size of the response message is larger than this value will the message be compressed. If the compression function is enabled, the default value is 2048
compressableMimeType Compression type, specify which types of files are compressed
noCompressionUserAgents = "gozilla, traviata" For the following browsers, do not enable compression

The above are some commonly used configuration parameters, and there are many other parameter settings. You can continue to optimize
the parameter attribute values ​​of HTTP Connector and AJP Connector. You can refer to the detailed description of the official document for learning.

Guess you like

Origin blog.csdn.net/weixin_51486343/article/details/112746276