Nginx 1.17.0 指定域名 负载均衡

相关文章:

Nginx 官方文档:HTTP Load Balancing

CentOS 1810 源码安装使用 Nginx

在 CentOS 1804 中手动安装 JDK 1.8

在CentOS 1804 中设置 Apache Tomcat 9.0.12 开机自启


前言:

本次使用 Nginx 源码构建安装 Nginx。

Nginx 安装及使用参见相关文章。

使用 tomcat 作为作为效果展示(使用 tomcat 需要安装 JDK)。


  1. tomcat 配置:
    端口相同会导致运行时端口占用异常。

    tomcat服务器名称

    shutdown port

    http port

    redirectPort port

    AJP port

    tomcat9-0(服务器 0)

    8005(默认)

    8080(默认)

    8443(默认)

    8009(默认)

    tomcat9-1(服务器 1)

    8006

    8081

    8444

    8010

    tomcat9-2(备份服务器)

    8007

    8082

    8445

    8011

    tomcat9-2 在 tomcat9-0、tomcat9-1 出现故障时启用。
     
  2. 为了区分负载均衡的效果,修改 tomcat 根目录中 webapps/ROOT/index.jsp:
    ......
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <title>tomcat9-0</title>
            <link href="favicon.ico" rel="icon" type="image/x-icon" />
            <link href="favicon.ico" rel="shortcut icon" type="image/x-icon" />
            <link href="tomcat.css" rel="stylesheet" type="text/css" />
        </head>
    
    ......
    将 title 修改为对应 tomcat 的名字。
     
  3. 端口配置:
    firewall-cmd --zone=public --add-port=80/tcp --permanent
    firewall-cmd --zone=public --add-port=8080/tcp --permanent
    firewall-cmd --zone=public --add-port=8081/tcp --permanent
    firewall-cmd --zone=public --add-port=8082/tcp --permanent
    
    firewall-cmd --reload
    firewall-cmd --list-all
    注意不要重复打开同一个端口。
     
  4. 首先直接访问各 tomcat ,查看效果:

     
  5. 配置 Nginx 负载均衡:
    vim /usr/local/nginx/conf/nginx.conf
    在 http 中增加:
        upstream tomcatBalancing {
            server 127.0.0.1:8080;
            server 127.0.0.1:8081;
            server 127.0.0.1:8082 backup;
        }
    
    修改 server:
            location / {
                proxy_pass http://tomcatBalancing;
                #root   html;
                #index  index.html index.htm;
            }
  6. 重启 Nginx,访问 Nginx:
    第一次访问:

    刷新:


    可以观察到 title 发生变化,重复刷新,title 在 tomcat9-0 与 tomcat9-1 中切换。
     
  7. 模拟故障 1:
    停止 tomcat9-0,重复访问一直是 tomcat9-1。
    停止 tomcat9-1 同理。
     
  8. 模拟故障 2:
    停止 tomcat9-0、tomcat9-1,重复访问一直是 tomcat9-2。
     
  9. 服务器权重:
    默认情况下,NGINX使用Round Robin方法根据权重在组中的服务器之间分配请求。指令的 weigth 参数 server 设置服务器的权重; 默认值为1。

    设置 tomcat9-0 权重为5:

        upstream tomcatBalancing {
            server 127.0.0.1:8080 weight=5;
            server 127.0.0.1:8081;
            server 127.0.0.1:8082 backup;
        }
    

    重启 Nginx 后,刷新查看效果。
     

  10. 启用持久性会话:
    由于负载均衡,用户访问时,一直在 服务器中 切换。
    NGINX Plus识别用户会话并将给定会话中的所有请求路由到同一上游服务器中。

发布了94 篇原创文章 · 获赞 32 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_32596527/article/details/93348894