Detailed Nginx + Tomcat reverse proxy load Balancing cluster Deployment Guide _nginx

Source: Internet
Author: User
Tags readable ssh file permissions nginx server tomcat server nginx reverse proxy nginx load balancing automake

Nginx is a server software that is also a high-performance HTTP and reverse proxy server, as well as a proxy mail server. In other words, we can publish the website on the Nginx, can realize the load balance (enhances the reply efficiency, avoids the server crashes), but also can realize the function as the mail server to send and receive the mail. And the most common is to use Nginx to achieve load balancing.

Nginx performance comparisons with other servers:

The tomcat server is oriented to the Java language and is a heavyweight server, while Nginx is a lightweight server. Apache Server stable, open source, Cross-platform, but the Apache server does not support high concurrency, Nginx can support the processing of millions TCP connections, more than 100,000 of concurrent connections, and is a good cross-platform server.
Nginx main advantages can be achieved high concurrency, simple deployment, low memory consumption, low cost, the main shortcomings of the rewrite function is not strong enough, not more than Apache module.

This article mainly explains the Nginx + Tomcat reverse proxy and the load balanced deployment, takes the popular utility as the main. There is not much relationship between each part of this article, which can be studied separately according to the requirement.

Come down and take a look at the Nginx reverse proxy process:

Nginx Load Balancing process (will automatically select a less stressful server for access):

It can be seen that load balancing is realized by the principle of reverse proxy, so it is also called the load balance of reverse proxy. So we'll deploy load balancing, and then the reverse proxy will be.

In general, the load balancing method is divided into two kinds: software implementation and hardware implementation, the efficiency of hardware implementation is very high, but the corresponding cost is very high. Software implementation is not as efficient as hardware, but costs are much lower. With Nginx server to achieve load balancing, it is through software to achieve load balancing, and nginx itself to support high concurrency. Therefore, the use of Nginx server to achieve load balance, can greatly save the cost of the enterprise, and because Nginx is the server software, its implementation efficiency is very high. The purpose of this article is also to help you use Nginx to achieve load balancing.

The core of load balancing is to set up a server cluster, and then the user first accesses the Third-party proxy server (where we choose Nginx), then the proxy server selects a server in the cluster and then introduces the request to the selected server (we choose Tomcat here).

The following figure, through the reverse proxy we achieve the following load balance, here we assume four servers public network of IP, a proxy server, three do load balanced server:

Well, the overall architecture is basically clear, and down we come to the concrete implementation:

Tip: This article we are basically using SSH for related operations, Windows can try to install Putty,mac under the direct use of the system with the terminal tool can be.

1.Linux Build Nginx Server

We build the Nginx server on the server:

1) Download Nginx

2) Upload Server Nginx installation package

$ SCP ~/downloads/nginx-1.10.2.tar.gz root@

3) Installation Nginx

$ ssh root@             //ssh Connection
# yum-y install gcc gcc-c++ autoconf automake//gcc  , gcc-c++ library file
# Yum in Stall-y pcre pcre-devel         //Installation Nginx Dependency Pack
# yum install-y zlib zlib-devel

Note:-y indicates that all yes,autoconf represent automatic configuration, Automake represents automatic compilation.

# cd/usr/local #
TAR-ZXVF nginx-1.10.2.tar.gz         /Unzip
# CD nginx-1.10.2                //switch to this directory
#./configure                  //Configuration
# make
# make install                 //Installation

Verify that the installation is complete:

# cd/usr/local
# ls                      //If the Nginx folder exists, the installation is successful

After the installation steps and directory settings above, Nginx's startup program is/usr/local/nginx/sbin/nginx, and the default profile is/usr/local/nginx/conf/ nginx.conf, but do not recommend directly edit nginx.conf, generally we have chosen to create a new profile, and then in the new configuration file to modify the port, reverse proxy path, and so on.

2.Nginx start, stop, signal control

1 start nginx Server (format: Nginx executable-C nginx configuration file):


2 Stop Nginx Server:

Stop the Nginx server to first query the Nginx main process number (master processes), assuming that the query here is 1060 (easy to use for the following demo):

# Ps-ef|grep Nginx

Next to see how to stop Nginx server, there are three ways to stop Nginx:

To stop calmly:

# ps-ef|grep Nginx  //View the Nginx main process number (master processes), assuming the query here 1060
# Kill-quit 1060

Quick STOP:

# kill-term 1060

Force stop:

# pkill-9 Nginx

3 Reboot Nginx Server:

When we modify the Nginx configuration file, we need to reboot to take effect. We also need to verify the correctness of the configuration file before rebooting, and then restart the operation:

#/usr/local/nginx/sbin/nginx-t-c/usr/local/nginx/conf/nginx.conf   //Validation
#/usr/local/nginx/sbin/nginx-s Reload                  //reboot

4) Smooth Upgrade Nginx server

Smooth upgrades do not stop running processes, which continue to process requests, but do not accept new requests, stopping after the old processes have processed the requests that are still being processed. During this smooth upgrade process, the newly opened process is processed. This is the smooth upgrade.

#/usr/local/nginx/sbin/nginx-v       //view current version

The following is a smooth upgrade:

# cd/usr/local #
TAR-ZXVF nginx-1.11.6.tar.gz       /Unzip new version Nginx
# CD nginx-1.11.6              //switch to this directory
#./ Configure                //configuration
# make
# cd/usr/local/nginx/sbin          //Open old version nginx executable file location
# CP Nginx Nginx.old         //Backup old version Nginx executables to prevent upgrade errors and unrecoverable
# Cp-rfp/usr/local/nginx-1.11.6/objs/nginx/usr/local/nginx/sbin   / /Copy new version executable file to old version
# rm-f/usr/local/nginx-1.11.6.tar.gz    //Aftermath Work Delete compressed file
# rm-rf/usr/local/nginx-1.11.6       //Delete folder

At this point, the Nginx server smooth upgrade was successful.

Implementation of load Balancing in 3.Nginx

We still connect SSH first, then do the following (generally do not recommend to modify the default main profile nginx.conf, so we create a new load balancing profile fzjh.conf, to ensure that the server security, such as the following):

# cd/usr/local/nginx/conf #
Touch fzjh.conf
# VI fzjh.conf  //VI editor to open the file, and then press the keyboard I

Note: In the VI editor, the keyboard presses I into the insert state, pressing ESC to exit the insert state.

Then enter the following configuration code (the annotation section opens on demand):

 #设置低权限用户, the user nobody set up for security;

#工作衍生进程数 worker_processes 4;
#设置错误文件存放路径 #error_log Logs/error.log;
#error_log Logs/error.log Notice;

#error_log Logs/error.log Info;

#设置pid存放路径 (PID is an important document in the control system) #pid Logs/;

#设置最大连接数 events{worker_connections 1024;} http{#主要是用于设置一组可以在proxy_pass和fastcgi_pass指令中使用额代理服务器, the default load balancing method is polling upstream tomcat_client {#设置同一个cookie的两次/multiple requests, requesting
    is the same server ip_hash;
    #weight权重, the default 1, the greater the probability of greater access, backup standby server, the server after all crashes, start the server weight=5;
    Server weight=5;
  Server weight=5 backup;

  #开启gzip压缩, when opened, the access page will automatically compress #gzip on;
    #指定服务器的名称和参数 server {Listen 80;


    #设置字符 #charset Koi8-r;
      #location/Refer to the root directory to do load Balancing location/{Proxy_pass http://tomcat_client;
      Proxy_redirect default;
      #设置代理 Proxy_set_header Host $host;
    Proxy_set_header X-real-ip $remote _addr; }

Press ESC when the input is complete, and then enter:

: wq!

You can save and exit the load-balanced configuration file, and down we load our profile:

#/usr/local/nginx/sbin/nginx                      /start nginx
#/usr/local/nginx/sbin/nginx-c/usr/local/nginx/conf/fzjh.conf    //Load configuration file

If there is a port footprint, you can use the following command to kill the Nginx program:

# killall-9 Nginx

At this point, the Nginx server is deployed. Let's start by deploying the three servers that actually provide the data under load balancing.

Install JDK under 4.Linux

We installed the JDK in the, and servers, for example,

1) Download JDK

2) Upload Server JDK installation package

$ SCP ~/downloads/jdk-8u112-linux-x64.tar.gz root@

3) Install JDK

$ ssh root@         //ssh Connection
# cd/usr/local #
TAR-ZXVF jdk-8u112-linux-x64.tar.gz//Decompression
# MV jdk1.8 .0_112/JDK         ///rename jdk1.8.0_112 to JDK
# vi/etc/profile            //Open file with VI Editor, then press keyboard I

Down we move the cursor to the last side, two carriage return wraps, and then add the following code to configure Java environment variables:

Java_home= "/USR/LOCAL/JDK"
class_path= "$JAVA _home/lib: $JAVA _home/jre/lib"
path= ".: $PATH: $JAVA _home/ Bin "
catalina_home="/usr/local/tomcat "
export java_home catalina_home

Press ESC when the input is complete, and then enter:

: wq!

You can save it and exit it. At this point we want it to take effect immediately, you need to continue to enter the command:

# Source/etc/profile

The profile file is updated at this time, the environment variable is configured successfully. Let's verify that the JDK is installed successfully:

# java-version

If you return to the Java version number, the installation succeeds.

5.Linux to build Tomcat server

We build Tomcat servers in the,, and servers, for example

1) Download Tomcat

2) Upload Server Tomcat installation package

$ SCP ~/downloads/apache-tomcat-8.5.9.tar.gz root@

3) Install Tomcat

$ ssh root@         //ssh Connection
# cd/usr/local #
TAR-ZXVF apache-tomcat-8.5.9.tar.gz//decompression
# MV Apache-tomcat-8.5.9/tomcat    //rename apache-tomcat-8.5.9 to Tomcat

4 Set the Tomcat Web file directory

The path to the Tomcat Default Web page file is/usr/local/tomcat/webapps/root, but generally we don't store it here, we create a new Data/wwwroot directory in the Linux root directory:

# Mkdir/data             //New Catalog
# mkdir/data/www #
Mkdir/data/www/root #
cd/usr/local/tomcat/conf #
VI Server.xml            ///VI editor to open server.xml configuration file, open the keyboard press I

We found the appbase= "WebApps" under the host node and changed it to: appbase= "/data/www"

Press ESC when the input is complete, and then enter:

: wq!

You can save and exit the configuration file, and then restart Tomcat to take effect, when Tomcat's Web file directory becomes/data/www/root.

Configure the Tomcat environment variable, we have configured the JDK, we can look back.

6.Tomcat Start and stop

1 Start Tomcat Server


2 Stop Tomcat Server:


To this end, the Nginx + Tomcat load Balancing cluster has been deployed. However, with the server, there must be no database, below to expand the Linux installation of the MySQL database method.

Install MySQL database under 7.Linux

We re- the MySQL database on this server:

1) Download MySQL database

2 upload MySQL Database installation package

$ SCP ~/downloads/mysql-5.1.51.tar.gz root@

3) Install MySQL

$ ssh root@ connection # groupadd MySQL/set up MySQL group # useradd mysql-g mysql//Add user Mys QL to MySQL group # yum list|grep ncurses # yum-y Install ncurses-devel # yum Install ncurses-devel # cd/usr/local # TAR-ZX VF mysql-5.1.51.tar.gz//Decompression # CD mysql-5.1.51 #./configure--prefix=/usr/local/mysql--with-mysqld-ldflags=-all-sta Tic--with-client-ldflags=-all-static--with-readline--with-sll//configuration, set installation path, set up MySQL without shared library, set compile client without shared library, Set up to install the TAR package in a RMP manner, set the RMP to install OPENSLL # make install//install, wait longer in make[4, minutes to more than 10 minutes, all normal #/usr/loc al/mysql/bin/mysql_install_db--user//To initialize the installed MySQL # CP./support-files/mysql.server/etc/init.d/mysql//            Copy the MySQL boot service to the system and rename it to MySQL # CP./support-files/my-medium.cnf/etc/my.cnf//Copy rule file # chmod 755/etc/init.d/mysql Change file permissions//file permissions are made up of three digits, first: The permissions of the file owner, second: The file owner of the same group of people's permissions, third: File owners are not the same group of permissions//7: Readable writable executable, 5: Readable executable # cd/usr/local/mysql # C                  Hown-r MySQL. Will/usr/local/mysql owner changed to MySQL # chgrp-r MySQL. /usr/local/mysql to MySQL group # ps-ef|grep MySQL # kill-9 3632///MySQL All process numbers are killed in turn, this is assumed to be 3632 #/usr/local/mysql /bin/mysql_install_db--user=mysql//re-initialize # service MySQL start/start MySQL #/usr/local/mysql/bin/mys

 qladmin-u root password ' 123456 '//set MySQL password

To this MySQL installation succeeded, down we test:

#/usr/local/mysql/bin/mysql-u Root-p

If you enter the password, you can log in to MySQL, then the test is successful. Below we set MySQL allow to open remote connection:

#/usr/local/mysql/bin/mysql-u Root-p

mysql> GRANT all privileges on *.* to ' root ' @ '% ' identified by ' 123456 ' H GRANT OPTION;
Create user for remote connection (root: username,%: All computers can connect, also can set an IP address to run the connection, 123456: password)

mysql> flush privileges;      Take effect immediately

Here we look at the database users:

Mysql> SELECT DISTINCT CONCAT (' User: ', user, ' @ ', ', host, '; ') as query from Mysql.user;
Mysql> \q              //Logout

Find a computer to test, use navicat telnet mysql, login success.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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: 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.