---
title: "Nginx+Tomcat在Windows下做负载均衡"
author: "nenty"
date: "2012-07-31T11:52:07Z"
tags: []
categories: ["互联网"]
slug: "nginx-tomcat-windows"
draft: false
lastmod: "2012-07-31T11:52:07Z"
id: 1613286
url: "https://nenty.iteye.com/blog/1613286"
---

一、为什么需要对Tomcat服务器做负载均衡：

Tomcat服务器作为一个Web服务器，其并发数在300-500之间，如果有超过500的并发数便会出现Tomcat不能响应新的请求的情况，严重影响网站的运行。另外，在访问量大的情况下，Tomcat的线程数会不断增加。由于Tomcat自身对内存的占用有控制，当对内存的占用达到最大值时便会出现内存溢出，对网站的访问严重超时等现象，这时便需要重新启动Tomcat以释放占用的内存，这样做便会阻断网站运行。

所以对Tomcat做负载均衡便很有必要。目前可以和Tomcat做负载均衡的主流服务器是Apache，但是Nginx由于功能多、配置简单等优点逐渐成为很多负载均衡服务器的首选。Nginx的并发数可达到50000，所以理论上可以和Tomcat以1:100的比例来配置，这样便可以很好的解决网站并发瓶颈问题。

二、Nginx+Tomcat在Windows下负载均衡配置方法：

Nginx+Tomcat在Windows下做负载均衡相对在Linux下简单不少，因为不论是Nginx还是Tomcat只需要下载Windows下的安装包解压到某个目录下，然后就可以做配置了。

               我选择的Nginx是nginx-0.8.49这个版本，Tomcat选择的是apache-tomcat-6.0.26。

         下面就是配置过程:

         1.将nginx-0.8.49.rar压缩包直接解压到某个目录下(如D:/负载均衡/nginx)。

       2.将apache-tomcat-6.0.26.rar压缩包解压，因为是做负载均衡，所以至少要解压两个。(如分别解压到D:/负载均衡/tomcat\_1和D:/负载均衡/tomcat\_2下面)。

         3.将要发布的项目发布到两个Tomcat根目录下的webapps下，保证两个Tomcat下面的项目名称相同。

         4.修改其中一个Tomcat的配置文件，该配置文件位于Tomcat目录下的/conf/下，文件名为server.xml，修改其中的&lt;Server port="8005" shutdown="SHUTDOWN"&gt;为&lt;Server port="8006" shutdown="SHUTDOWN"&gt;，修改其中的

&lt;Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" /&gt;

为

&lt;Connector port="8088" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" /&gt;

修改后的文件如下：

**&lt;?xml version='1.0' encoding='utf-8'?&gt;**

**&lt;!--**

  **Licensed to the Apache Software Foundation (ASF) under one or more**

  **contributor license agreements.  See the NOTICE file distributed with**

  **this work for additional information regarding copyright ownership.**

  **The ASF licenses this file to You under the Apache License, Version 2.0**

  **(the "License"); you may not use this file except in compliance with**

  **the License.  You may obtain a copy of the License at**

 

      **http://www.apache.org/licenses/LICENSE-2.0**

 

  **Unless required by applicable law or agreed to in writing, software**

  **distributed under the License is distributed on an "AS IS" BASIS,**

  **WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.**

  **See the License for the specific language governing permissions and**

  **limitations under the License.**

**--&gt;**

**&lt;!-- Note:  A "Server" is not itself a "Container", so you may not**

     **define subcomponents such as "Valves" at this level.**

     **Documentation at /docs/config/server.html**

 **--&gt;**

**&lt;Server port="8006" shutdown="SHUTDOWN"&gt;**

 

  **&lt;!--APR library loader. Documentation at /docs/apr.html --&gt;**

  **&lt;Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /&gt;**

  **&lt;!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --&gt;**

  **&lt;Listener className="org.apache.catalina.core.JasperListener" /&gt;**

  **&lt;!-- Prevent memory leaks due to use of particular java/javax APIs--&gt;**

  **&lt;Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /&gt;**

  **&lt;!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html --&gt;**

  **&lt;Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" /&gt;**

  **&lt;Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /&gt;**

 

  **&lt;!-- Global JNDI resources**

       **Documentation at /docs/jndi-resources-howto.html**

  **--&gt;**

  **&lt;GlobalNamingResources&gt;**

    **&lt;!-- Editable user database that can also be used by**

         **UserDatabaseRealm to authenticate users**

    **--&gt;**

    **&lt;Resource name="UserDatabase" auth="Container"**

              **type="org.apache.catalina.UserDatabase"**

              **description="User database that can be updated and saved"**

              **factory="org.apache.catalina.users.MemoryUserDatabaseFactory"**

              **pathname="conf/tomcat-users.xml" /&gt;**

  **&lt;/GlobalNamingResources&gt;**

 

  **&lt;!-- A "Service" is a collection of one or more "Connectors" that share**

       **a single "Container" Note:  A "Service" is not itself a "Container",**

       **so you may not define subcomponents such as "Valves" at this level.**

       **Documentation at /docs/config/service.html**

   **--&gt;**

  **&lt;Service name="Catalina"&gt;**

 

    **&lt;!--The connectors can use a shared executor, you can define one or more named thread pools--&gt;**

    **&lt;!--**

    **&lt;Executor name="tomcatThreadPool" namePrefix="catalina-exec-"**

        **maxThreads="150" minSpareThreads="4"/&gt;**

    **--&gt;**

   

   

    **&lt;!-- A "Connector" represents an endpoint by which requests are received**

         **and responses are returned. Documentation at :**

         **Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)**

         **Java AJP  Connector: /docs/config/ajp.html**

         **APR (HTTP/AJP) Connector: /docs/apr.html**

         **Define a non-SSL HTTP/1.1 Connector on port 8080**

    **--&gt;**

    **&lt;Connector port="8088" protocol="HTTP/1.1"**

               **connectionTimeout="20000"**

               **redirectPort="8443" /&gt;**

    **&lt;!-- A "Connector" using the shared thread pool--&gt;**

    **&lt;!--**

    **&lt;Connector executor="tomcatThreadPool"**

               **port="8080" protocol="HTTP/1.1"**

               **connectionTimeout="20000"**

               **redirectPort="8443" /&gt;**

    **--&gt;**          

    **&lt;!-- Define a SSL HTTP/1.1 Connector on port 8443**

         **This connector uses the JSSE configuration, when using APR, the**

         **connector should be using the OpenSSL style configuration**

         **described in the APR documentation --&gt;**

    **&lt;!--**

    **&lt;Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"**

               **maxThreads="150" scheme="https" secure="true"**

               **clientAuth="false" sslProtocol="TLS" /&gt;**

    **--&gt;**

 

    **&lt;!-- Define an AJP 1.3 Connector on port 8009 --&gt;**

    **&lt;Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /&gt;**

 

 

    **&lt;!-- An Engine represents the entry point (within Catalina) that processes**

         **every request.  The Engine implementation for Tomcat stand alone**

         **analyzes the HTTP headers included with the request, and passes them**

         **on to the appropriate Host (virtual host).**

         **Documentation at /docs/config/engine.html --&gt;**

 

    **&lt;!-- You should set jvmRoute to support load-balancing via AJP ie :**

    **&lt;Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"&gt;**        

    **--&gt;**

    **&lt;Engine name="Catalina" defaultHost="localhost"&gt;**

 

      **&lt;!--For clustering, please take a look at documentation at:**

          **/docs/cluster-howto.html  (simple how to)**

          **/docs/config/cluster.html (reference documentation) --&gt;**

      **&lt;!--**

      **&lt;Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/&gt;**

      **--&gt;**       

 

      **&lt;!-- The request dumper valve dumps useful debugging information about**

           **the request and response data received and sent by Tomcat.**

           **Documentation at: /docs/config/valve.html --&gt;**

      **&lt;!--**

      **&lt;Valve className="org.apache.catalina.valves.RequestDumperValve"/&gt;**

      **--&gt;**

 

      **&lt;!-- This Realm uses the UserDatabase configured in the global JNDI**

           **resources under the key "UserDatabase".  Any edits**

           **that are performed against this UserDatabase are immediately**

           **available for use by the Realm.  --&gt;**

      **&lt;Realm className="org.apache.catalina.realm.UserDatabaseRealm"**

             **resourceName="UserDatabase"/&gt;**

 

      **&lt;!-- Define the default virtual host**

           **Note: XML Schema validation will not work with Xerces 2.2.**

       **--&gt;**

      **&lt;Host name="localhost"  appBase="webapps"**

            **unpackWARs="true" autoDeploy="true"**

            **xmlValidation="false" xmlNamespaceAware="false"&gt;**

 

        **&lt;!-- SingleSignOn valve, share authentication between web applications**

             **Documentation at: /docs/config/valve.html --&gt;**

        **&lt;!--**

        **&lt;Valve className="org.apache.catalina.authenticator.SingleSignOn" /&gt;**

        **--&gt;**

 

        **&lt;!-- Access log processes all example.**

             **Documentation at: /docs/config/valve.html --&gt;**

        **&lt;!--**

        **&lt;Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"** 

               **prefix="localhost\_access\_log." suffix=".txt" pattern="common" resolveHosts="false"/&gt;**

        **--&gt;**

      **&lt;/Host&gt;**

    **&lt;/Engine&gt;**

  **&lt;/Service&gt;**

**&lt;/Server&gt;**

5.修改Nginx配置文件nginx.conf，该文件位于Nginx根目录下的/conf下面。

① 在#gzip  on;后面加入下面配置:

upstream backend {

                   server localhost:8080;

                   server localhost:8088;

                   ip\_hash;

         }

         其中server localhost:8080为第一个Tomcat的启动地址，server localhost:8088为第二个Tomcat的启动地址，ip\_hash用于做session同步。

② 修改第一个server{}配置中的listen  80;改为新的端口号，因为我的本机80端口被IIS占用，因此将此处改为listen 800;。并将

location / {

            root   html;

            index  index.html index.htm;

        }

改为：

location / {

            root   html;

            index  index.html index.htm;

                            proxy\_pass                  http://backend; 

           proxy\_redirect              off;

           proxy\_set\_header            Host $host;

           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;

           proxy\_send\_timeout          90;

           proxy\_read\_timeout          90;

           proxy\_buffer\_size           4k;

           proxy\_buffers               4 32k;

           proxy\_busy\_buffers\_size     64k;

           proxy\_temp\_file\_write\_size  64k;

        }

其中proxy\_pass参数和upstream backend{}对应。

         经过上面这些步骤，负载均衡配置就完成，下面前分别启动两台tomcat，然后双击nginx根目录下的nginx.exe文件或者用start nginx启动nginx，打开浏览器，输入地址:http://localhost:800便可看到下面画面: