Nginx(web服务器)与Tomcat(应用服务器)搭建集群

  Nginx做为互联网最经常使用的web服务器,高性能的HTTP和反向代理使它常常做为Tomcat集群的方案。Nginx官方只支持使用HTTP协议的集成,可是若是你想使用AJP协议集成,能够使用阿里开源的nginx_ajp_module。接下来咱们使用HTTP的方式集成:html

1.准备Nginx、Tomcat一、Tomcat2nginx

  Nginx下载并启动:http://nginx.org/en/download.htmlweb

nginx默认端口80,我这里为了方便也就不修改了,直接启动apache

server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        
    }

 

 Tomcat下载并启动:https://tomcat.apache.org/download-80.cgi#8.5.43tomcat

tomcat因为是同一台机器,我这里修改了端口号,配置分别是:服务器

 

<Server port="8005" shutdown="SHUTDOWN">
<Connector port="8081" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<Server port="8006" shutdown="SHUTDOWN">

<Connector port="8082" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8444" />
<Connector port="8010" protocol="AJP/1.3" redirectPort="8444" />

修改好配置,把示列工程sample1放在tomcat1,sample2放在tomcat2里面,启动两个tomcat:负载均衡

访问http://localhost:8081/sample1/性能

访问http://localhost:8082/sample2/spa

 

2.配置Nginx,将Nginx与Tomcat一、Tomcat2集成3d

  Nginx集成能够使用HTTP方式,也能够使用AJP方式,这里使用的HTTP方式。

  2.1修改nginx的目录下conf下nginx.conf配置

在http{}下面配置

    #配置服务器1
    upstream sample1{
      server localhost:8081;
    }
    #配置服务器2
    upstream sample2{
      server localhost:8082;
    }

在server{}下配置

        #映射服务器1
        location /sample1/ {
            proxy_pass http://sample1;
        }
        #映射服务器2
        location /sample2/ {
            proxy_pass http://sample2;
        }

重启nginx,再一次访问

http://localhost/sample1/

http://localhost/sample2/

3.负载均衡配置

在http{}下面配置

#负载均衡配置服务器群组
    upstream sample1{
      #实例1
      server localhost:8081 weight=1 max_fails=3 fail_timeout=30s;
      #实例2
      server localhost:8082 weight=1 max_fails=3 fail_timeout=30s;
    }

在server{}下配置

#映射服务器集群
        location /sample1/{
          proxy_pass http://sample1;
        }

由于这里咱们配置的两个项目是不一样名称的,因此负载均和1:1时候,会有一个是没法访问。

在tomcat2里面把tomcat1里面的sample1复制过来,显示改成hello,tomcat2!

访问http://localhost/sample1/,不断刷新

相关文章
相关标签/搜索