Home Operation and Maintenance Nginx How Nginx and Tomcat achieve dynamic and static separation and load balancing

How Nginx and Tomcat achieve dynamic and static separation and load balancing

May 18, 2023 pm 05:10 PM
nginx tomcat

one. Introduction to nginx:

nginx is a high-performance http and reverse proxy server with high stability and supports hot deployment and easy module expansion. When encountering a peak of access, or someone maliciously initiates a slow connection, it is also likely to cause the server's physical memory to be exhausted and frequently exchanged, resulting in loss of response. The server can only be restarted. nginx adopts a phased resource allocation technology to process static files and Cache-free reverse proxy acceleration achieves load balancing and fault tolerance, and can withstand high concurrency processing in such high-concurrency access situations.

two. nginx installation and configuration

The first step: download the nginx installation package

The second step: install nginx on linux

#tar zxvf nginx-1.7.8.tar.gz //解压

#cd nginx-1.7.8

#./configure --with-http_stub_status_module --with-http_ssl_module//启动server状态页和https模块
Copy after login

will report a missing pcre library error, As shown in the picture:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

At this time, first perform the third step to install pcre, and then execute it in 3, and that’s it

4 .make && make install //Compile and install

5. Test whether the installation configuration is correct. nginx is installed in /usr/local/nginx

#/usr/local/nginx/sbin/ nginx -t, as shown in the picture:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

Step 3: Install pcre on linux

#tar zxvf pcre-8.10.tar.gz //解压

cd pcre-8.10

./configure

make && make install//编译并安装
Copy after login

Three. nginx tomcat implements dynamic and static separation

Dynamic and static separation means that nginx processes the static pages (html pages) or pictures requested by the client, and tomcat processes the dynamic pages (jsp pages) requested by the client, because nginx processes The efficiency of static pages is higher than tomcat.

Step one: We need to configure the nginx file

#vi /usr/local/nginx/conf/nginx.conf

 #user nobody; 
worker_processes 1; 
error_log logs/error.log; 
pid    logs/nginx.pid; 
 
events { 
  use epoll; 
  worker_connections 1024; 
} 
 
 
http { 
  include    mime.types; 
  default_type application/octet-stream; 
  log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 
           '$status $body_bytes_sent "$http_referer" ' 
           '"$http_user_agent" "$http_x_forwarded_for"'; 
 
  access_log logs/access.log main; 
  sendfile    on; 
keepalive_timeout 65; 
gzip on;  
gzip_min_length 1k;  
gzip_buffers   4 16k;  
gzip_http_version 1.0;  
gzip_comp_level 2;  
gzip_types text/plain application/x-javascript text/css application/xml;  
gzip_vary on;  
  server { 
    listen    80 default; 
    server_name localhost; 
    <span style="color:#ff0000;"> location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ //由nginx处理静态页面</span> 
       {  
         root  /usr/tomcat/apache-tomcat-8081/webapps/root;  
          expires   30d; //缓存到客户端30天 
        }  
    error_page 404       /404.html; 
 
    #redirect server error pages to the static page /50x.html 
     
    error_page  500 502 503 504 /50x.html; 
    location = /50x.html { 
      root  html; 
    } 
     <span style="color:#ff0000;"> location ~ \.(jsp|do)$ {//所有jsp的动态请求都交给tomcat处理 </span> 
      <span style="color:#ff0000;"> proxy_pass http://192.168.74.129:8081; //来自jsp或者do的后缀的请求交给tomcat处理</span> 
      proxy_redirect off; 
      proxy_set_header host $host;  //后端的web服务器可以通过x-forwarded-for获取用户真实ip 
      proxy_set_header x-real-ip $remote_addr; 
      proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; 
      client_max_body_size 10m;  //允许客户端请求的最大单文件字节数 
      client_body_buffer_size 128k; //缓冲区代理缓冲用户端请求的最大字节数 
       proxy_connect_timeout 90;  //nginx跟后端服务器连接超时时间 
       proxy_read_timeout 90;   //连接成功后,后端服务器响应时间 
       proxy_buffer_size 4k;   //设置代理服务器(nginx)保存用户头信息的缓冲区大小 
       proxy_buffers 6 32k;    //proxy_buffers缓冲区,网页平均在32k以下的话,这样设置 
      proxy_busy_buffers_size 64k;//高负荷下缓冲大小(proxy_buffers*2) 
      proxy_temp_file_write_size 64k; //设定缓存文件夹大小,大于这个值,将从upstream服务器传 
    } 
    
  }  
 
}
Copy after login

Step two: In Create a new index.html static page under webapps/root under tomcat, as shown in the figure:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

Step 3: Start the nginx service

#sbin/nginx As shown in the picture:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

Step 4: Our page access can display normal content, as shown in the picture:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

Step 5: Test the performance of nginx and tomcat in processing static pages under high concurrency?

Used the linux ab website stress test command to test the performance

1. Test the performance of nginx in processing static pages

ab -c 100 -n 1000

This means processing 100 requests at the same time and running the index.html file 1000 times, as shown in the figure:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

2. Test tomcat processing static pages Performance

ab -c 100 -n 1000

This means processing 100 requests at the same time and running the index.html file 1000 times, as shown in the figure:

How Nginx and Tomcat achieve dynamic and static separation and load balancing

For the same processing of static files, the static performance of nginx processing is better than that of tomcat. nginx can request 5388 times per second, while tomcat only requests 2609 times.

Summary: In the nginx configuration file, we hand over static configuration to nginx for processing, and hand over dynamic requests to tomcat, which improves performance.

Four. nginx tomcat load balancing and fault tolerance

In the case of high concurrency, in order to improve the performance of the server and reduce the concurrency pressure on a single server, we adopt cluster deployment, which can also solve the problem of avoiding single When a server hangs up and the service cannot be accessed, fault tolerance issues are dealt with.

The first step: We deployed the tomcat server here for two days, 192.168.74.129:8081 and 192.168.74.129:8082

The second step: nginx serves as the proxy server, and the client requests On the server side, load balancing is used to handle it, so that the customer service requests can be evenly distributed to the servers every day, thus reducing the pressure on the server side. Configure the nginx.conf file under nginx.

#vi /usr/local/nginx/conf/nginx.conf

 #user nobody; 
worker_processes 1; 
error_log logs/error.log; 
pid    logs/nginx.pid; 
 
events { 
  use epoll; 
  worker_connections 1024; 
} 
 
 
http { 
  include    mime.types; 
  default_type application/octet-stream; 
  log_format main &#39;$remote_addr - $remote_user [$time_local] "$request" &#39; 
           &#39;$status $body_bytes_sent "$http_referer" &#39; 
           &#39;"$http_user_agent" "$http_x_forwarded_for"&#39;; 
 
  access_log logs/access.log main; 
  sendfile    on; 
keepalive_timeout 65; 
gzip on;  
gzip_min_length 1k;  
gzip_buffers   4 16k;  
gzip_http_version 1.0;  
gzip_comp_level 2;  
gzip_types text/plain application/x-javascript text/css application/xml;  
gzip_vary on;  
<span style="color:#ff0000;">upstream localhost_server { 
    ip_hash; 
    server 192.168.74.129:8081; 
    server 192.168.74.129:8082; 
  }</span> 
 
  server { 
    listen    80 default; 
    server_name localhost; 
    <span style="color:#ff0000;"> location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ //由nginx处理静态页面</span> 
       {  
         root  /usr/tomcat/apache-tomcat-8081/webapps/root;  
          expires   30d; //缓存到客户端30天 
        }  
    error_page 404       /404.html; 
 
    #redirect server error pages to the static page /50x.html 
     
    error_page  500 502 503 504 /50x.html; 
    location = /50x.html { 
      root  html; 
    } 
     <span style="color:#ff0000;">location ~ \.(jsp|do)$ {//所有jsp的动态请求都交给tomcat处理 </span> 
      <span style="color:#ff0000;">proxy_pass http://localhost_server; //来自jsp或者do的后缀的请求交给tomcat处理</span> 
      proxy_redirect off; 
      proxy_set_header host $host;  //后端的web服务器可以通过x-forwarded-for获取用户真实ip 
      proxy_set_header x-real-ip $remote_addr; 
      proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; 
      client_max_body_size 10m;  //允许客户端请求的最大单文件字节数 
      client_body_buffer_size 128k; //缓冲区代理缓冲用户端请求的最大字节数 
       proxy_connect_timeout 90;  //nginx跟后端服务器连接超时时间 
       proxy_read_timeout 90;   //连接成功后,后端服务器响应时间 
       proxy_buffer_size 4k;   //设置代理服务器(nginx)保存用户头信息的缓冲区大小 
       proxy_buffers 6 32k;    //proxy_buffers缓冲区,网页平均在32k以下的话,这样设置 
      proxy_busy_buffers_size 64k;//高负荷下缓冲大小(proxy_buffers*2) 
      proxy_temp_file_write_size 64k; //设定缓存文件夹大小,大于这个值,将从upstream服务器传 
    } 
    
  }  
 
}
Copy after login

Explanation:

1. The server in upstream points to the server IP (domain name) and port, followed by parameters

1)weight: Set the forwarding weight of the server to a default value of 1.

2)max_fails: It is used in conjunction with fail_timeout. It means that within the fail_timeout time period, if the number of server forwarding failures exceeds the value set by max_fails, the server will not be available. The default value of max_fails is 1

3)fail_timeout: Indicates how many times the forwarding fails within this time period before the server is considered unavailable.

4)down: Indicates that this server cannot be used.

5) backup: Indicates that the ip_hash setting is invalid for this server. The request will be forwarded to the server only after all non-backup servers have failed.

2. The ip_hash setting is in the cluster server. If the same client request is forwarded to multiple servers, each server may cache the same information, which will cause a waste of resources. The ip_hash setting is used When the same client requests the same information for the second time, it will be forwarded to the server that requested the first time. But ip_hash cannot be used together with weight.

The above is the detailed content of How Nginx and Tomcat achieve dynamic and static separation and load balancing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to run nginx apache How to run nginx apache Apr 14, 2025 pm 12:33 PM

To get Nginx to run Apache, you need to: 1. Install Nginx and Apache; 2. Configure the Nginx agent; 3. Start Nginx and Apache; 4. Test the configuration to ensure that you can see Apache content after accessing the domain name. In addition, you need to pay attention to other matters such as port number matching, virtual host configuration, and SSL/TLS settings.

How to create a mirror in docker How to create a mirror in docker Apr 15, 2025 am 11:27 AM

Steps to create a Docker image: Write a Dockerfile that contains the build instructions. Build the image in the terminal, using the docker build command. Tag the image and assign names and tags using the docker tag command.

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

See all articles