nginx配置反向代理与负载均衡

nginx配置反向代理

nginx通常不用来直接搭建网站,而是作为反向代理以及负载均衡存在,可以同时处理5w的并发量,并且开源免费,在并发量及其庞大的时代有着不可替代的地位。

工具

  • 系统:centos7.8
  • nginx版本:1.18.0
  • Tomcat版本:8.5.12

Tomcat

1、实例创建

ps:本文是以同一台服务器作为例子,但服务器群也是同样的操作,只是ip不同而已。

首先,前置条件是已经安装好了Tomcatnginx,现在我们创建Tomcat实例。

为了保证方便管理,我将复制的Tomcat实例放在同一个文件夹中同一管理。

mkdir /www/server/tomcats
cp -r /www/server/tomcat /www/server/tomcats/tomcat1
cp -r /www/server/tomcat /www/server/tomcats/tomcat2

此中,我创建tomcats文件夹,将我的Tomcat拷贝出两个实例放入其中。若你们有更大的需求可以创建更多的实例,一样的操作。

2、修改实例配置文件

打开配置文件:

vim /www/server/tomcats/tomcat1/conf/server.xml

修改port,总共有三个。以tomcat1为例,附上我的配置文件,大家对比着看应该能找到位置。

<?xml version="1.0" encoding="UTF-8"?>
<!--
  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.
-->
<!-- 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
 -->
<Server port="8006" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <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" />
  </GlobalNamingResources>

  <!-- 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
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8010" protocol="AJP/1.3" redirectPort="8443" />


    <!-- 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 -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- 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.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

开启防火墙

记得防火墙开启相应的端口,比如我的8080:8082。具体怎么操作防火墙,请看我的另一篇文章

在本地进行测试

IP:端口测试是否可以进行页面。

在这里插入图片描述

修改nginx

1、配置文件

找到自己的nginx配置文件nginx.conf

vim /www/server/nginx/conf/nginx.conf

进行配置(放在默认的server后面即可):

upstream ttmurphymall-portal {
   server 127.0.0.1:8080 weight=2;
   server 127.0.0.1:8081 weight=1;
  }
  
  upstream ttmurphymall-manager {
   server 127.0.0.1:8081;
  }
 server {
      listen       80;
      server_name  www.ttmurphymall.icu;

      #charset koi8-r;

      #access_log  logs/host.access.log  main;

      location / {
          proxy_pass   http://ttmurphymall-portal;
          index  index.html index.htm;
      }

      
  }
  server {
      listen       80;
      server_name  manager.ttmurphymall.icu;

      #charset koi8-r;

      #access_log  logs/host.access.log  main;

      location / {
          proxy_pass   http://ttmurphymall-manager;
          index  index.html index.htm;
      }

        
    }

其中,确保自己的域名可用,也就是可以直接用本机通过域名访问这个IP地址,域名的获取方式有很多,腾讯云或者直接搜索免费域名,如果实在不想花钱,或者说只是想本机测试用,那就使用自己骗自己的方式,设置hosts文件,详情参考我的另一篇文章

ps:127.0.0.1 == 你要访问的外网ip。

2、nginx.conf解析

  1. upstream:相当于一个指向标,或者说是个名字,提供调用跳转的。
  2. proxy_pass:跳转的目标链接。
  3. listen:监听端口,设置80。
  4. server_name:域名。
  5. weight:权重,此处就是负载均衡的做法——同一个upstream中有多个server提供同一个服务,其中的weight就是用来分配压力,比如现在的2:1,那么可以理解为三次链接中有两次给1号,一次给2号。

测试效果

测试效果就是使用域名在浏览器进行访问,出来tomcat页面就是成功。

在这里插入图片描述

在这里插入图片描述

并且注意我的页面,这就是权重的作用。

有其他交流的想法,可以加我创建的Q群:820080257

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值