专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 Nginx使用upstream模块实现7层负载均衡

Nginx使用upstream模块实现7层负载均衡

更新时间:2021-12-17 12:00:36 来源:动力节点 浏览1264次

简介

Nginx在生产环境中很多情况下是被用来当一个反代服务器,例如http反代,把http的访问压力分摊到后端的服务器集群上,而Nginx作为http反代,通常用到的模块是:ngx_http_proxy_module或ngx_http_fastcgi_module来实现反向代理,以上2个模块的反代指令所反代的仅仅只一台服务器,并不能在该添加多个服务器,所以,这时候就需要借助ngx_http_upstream模块定义一组服务器集群,然后在反代指令上,反代所指的不再是具体服务器,而是指向所定义的集群上。Nginx不单单能实现7层负载均衡,前面说的就是Nginx的7层负载均衡;还能实现4层的负载均衡,只不过Nginx需要监听在套接字上,而且定义服务器组时,不再是使用ngx_http_upstream而是使用ngx_stream_upstream模块,但是不论哪种负载均衡,他们的指令和实现方式都是类似的。

7层负载均衡实验

ngx_http_upstream module

该模块用于定义后端的服务器集群,或者叫服务器组或服务器池,后端的服务器,我们称为上游服务器upstramserver;结和proxy_pass,可以把请求转发到集群中的某一台服务器上。

服务集群中有多台服务器,集群中的服务器调度方法是由调度算法决定的,默认是加权轮询算法,每台服务器的权重默认是1,还可以使用hash KEY的方法实现KEY与后端服务器的对称绑定。

http_upstream

upsteam需要配置在http上下文中,它自己也引入一个新的上下文,作用:用于指定一组服务器集群。

配置upstream

        upstream static {
                server 10.1.1.11 weight=2;
                server 10.1.1.12;
        }
        upstream dynamic {
                server 10.1.1.12:9000;
                server 10.1.1.13:9000 weight=2;
        }

配置反向代理

server {
        listen 80;
        server_name www.ilinux.io;
        index  index.php index.html;
        location / {
        proxy_pass http://static;
        }
        location ~* \.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass dynamic;
        fastcgi_param SCRIPT_FILENAME /data/web/html$fastcgi_script_name;
        }
        location  ~* ^/(status|ping)$ {
        fastcgi_pass dynamic:9000;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        }
}

客户端测试静态调度

[root@client ~]# for i in {1..100};do curl http://www.ilinux.io/test.html ;done

This page come from NODE1

This Page from node2

This page come from NODE1

This page come from NODE1

This page come from NODE1

This Page from node2

This page come from NODE1

This page come from NODE1

This Page from node2

客户端测试动态资源

前面指定了动态资源的脚本路径,所以在2台运行Php服务的服务器新建脚本根目录和脚本文件。

创建目录和创建测试Php脚本文件

[root@node2 html]# mkdir -pv /data/web/html
[root@node2 html]# vim test.php
<?php
echo 'node2';
echo PHP_EOL;
同样的内容传送到node3
[root@node2 html]# scp test.php root@10.1.1.13:/data/web/html/test.php

测试:

[root@client ~]# for i  in {1..10};do curl http://www.ilinux.io/test.php ;done 
node3
node3
node3
node3
node2
node2
node3
node3
node3
node3
[root@client ~]# 

server指令的一些常用选项

weighr=number #指定权重
max_conns=number #限制和后端服务器的最大连接数量,默认为0不限制,设置该值能达到过载保护效果。
max_fails=number #最大的失效次数,如果达到该次数,则认为该服务器不可用,默认为1
fail_timeout=time #超时时间,和上面的搭配使用
backup #当后端所有服务器都挂了,就反代到backup上
down #此服务器不可用,用于停机

以上就是关于“Nginx使用upstream模块实现7层负载均衡”的介绍,大家如果想了解更多相关知识,可以关注一下动力节点的Java视频,里面的内容细致全面,通俗易懂,适合小白学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>