Nginx之负载均衡

柳三千

文章最后更新时间:2025年06月12日

前言:

公司为节约成本,业务刚开始一般都是单机提供服务,但是随着业务量的增长,单机服务器压力逐渐增大;当单机服务器处理不过来时候,就需要对其进行性能优化;但是一台服务器再怎么优化都是有瓶颈,因此把多台服务器集中起来组成一个集群来处理请求。通俗来说,以前一个人搬1000块砖头非常累,也耗费很长时间才能办完,长此以往,身体会垮掉;现在包工头另外增加9个工人一起搬砖,也就是10个人搬1000块砖头,每个人只需要搬100块砖头,时间效率上去了,工作强度也没这么大了;这就是负载均衡的作用!

nginx代理服务器接收到客户端请求之后,nginx会把这些请求转发到后端服务器tomcat处理。

环境准备:

1、安装nginx和tomcat的,具体安装请参考:

常用的WEB服务安装

2、修改tomcat的首页:

[root@localhost ROOT]# pwd
/usr/local/apache-tomcat-10.0.20/webapps/ROOT
[root@localhost ROOT]# cat index.jsp
<body>    
    <h1>this is 192.168.140.132 !</h1>


3、确保nginx能够正常访问:

Nginx负载均衡之轮询(默认)

特性:

  • 以循环方式,将请求平均分发到每台服务器上
  • 适合服务器配置基本一样,无状态且短平快的服务使用
  • 在轮询中,如果其中一台服务器挂掉,会自动去除该服务器

配置图:

参数注释:

http {
    include       mime.types;
    default_type  application/octet-stream;
    # 定义转发规则,以及定义上游服务器,即是集群服务器的地址
    upstream tomcats {
    # 要转发到的服务器地址,如ip、 ip:端口号、 域名、 域名:端口号
    server 192.168.140.131:8080;
    server 192.168.140.132:8080;
}
    server {
        listen       80;
        server_name  localhost;
        location / {
             # 开启代理转发到后端服务器,可以是某一个地址,也可以是upstream 定义的一个集群服务器
           proxy_pass http://tomcats;
        }

效果图:

第一次刷新:

第二次刷新:

Nginx负载均衡之权重

特性:

在 upstream 中配置的server参数后追加 weight 配置,则会根据配置的权重进行请求分发;适合服务器的硬件配置差别比较大的情况。

配置方式:

http {
    include       mime.types;
    default_type  application/octet-stream;
    upstream tomcats {
        server 192.168.140.131:8080 weight=1;#该台服务器接受1/4的请求量
        server 192.168.140.132:8080 weight=3;#该台服务器接受3/4的请求量
}

最终效果:

刷新4次,

  • 有三次的请求转发到192.168.140.132:8080
  • 有一次请求量转发到192.168.140.131:8080

Nginx负载均衡之ip_hash

特性:

  • 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题
  • ip_hash不能与backup同时使用
  • 此策略适合有状态服务,比如session
  • 当有服务器需要剔除,必须手动down掉

配置方式:

upstream tomcats {
        ip_hash;
        server 192.168.140.131:8080;
        server 192.168.140.132:8080;
}

Nginx负载均衡之fair(第三方,需要单独安装模块)

特性:

按后端服务器的响应时间来分配请求,响应时间短的优先分配。

配置文件:

upstream tomcats {
        fair;
        server 192.168.140.131:8080;
        server 192.168.140.132:8080;
}
下载参考链接:https://github.com/gnosek/nginx-upstream-fair

安装第三方fair模块:

(nginx -V可以查看预编译语句,在原有的预编译语句加上–add-module=/usr/local/src/nginx-upstream-fair-master)

[root@localhost src]# unzip nginx-upstream-fair-master.zip 
[root@localhost src]# cp -a /usr/local/nginx/ /root/#备份nginx
[root@localhost src]# cd nginx-1.20.2
[root@localhost nginx-1.20.2]# ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35 --add-module=/usr/local/src/nginx-upstream-fair-master
[root@localhost nginx-1.20.2]# make

编译报错:

/usr/local/src/nginx-upstream-fair-master/ngx_http_upstream_fair_module.c:543:28: error: ‘ngx_http_upstream_srv_conf_t’ has no member named ‘default_port’
     if (us->port == 0 && us->default_port == 0) {
                            ^
/usr/local/src/nginx-upstream-fair-master/ngx_http_upstream_fair_module.c:553:51: error: ‘ngx_http_upstream_srv_conf_t’ has no member named ‘default_port’
     u.port = (in_port_t) (us->port ? us->port : us->default_port);

解决方案:

在Nginx的源码中 src/http/ngx_http_upstream.h,找到ngx_http_upstream_srv_conf_s,在模块中添加添加default_port属性

[root@localhost nginx-1.20.2]# vim src/http/ngx_http_upstream.h 
添加 in_port_t                        default_port;

继续编译:

[root@localhost nginx-1.20.2]# make
[root@localhost nginx-1.20.2]# make install

将安装目录下的objs中的nginx拷贝到sbin目录

[root@localhost nginx-1.20.2]# cd objs/
[root@localhost objs]# ls
addon  autoconf.err  Makefile  nginx  nginx.8  ngx_auto_config.h  ngx_auto_headers.h  ngx_modules.c  ngx_modules.o  src
[root@localhost nginx-1.20.2]# rm -rf /usr/local/nginx/sbin/nginx
[root@localhost objs]# cp -a nginx /usr/local/nginx/sbin/
cp: overwrite ‘/usr/local/nginx/sbin/nginx’? y

检测nginx模块

[root@localhost nginx-1.20.2]# cd /usr/local/nginx/
[root@localhost nginx]# ./sbin/nginx -V
nginx version: nginx/1.20.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35 --add-module=/usr/local/src/nginx-upstream-fair-master

Nginx负载均衡之least_conn

特性:

  • 把请求转发给连接数较少的后端服务器
  • 有些请求占用的时间很长,会导致其所在的后端负载较高; 这种情况下,least_conn这种方式就可以达到更好的负载均衡效果。
  • 此负载均衡策略适合请求处理时间长短不一造成服务器过载的情况
upstream tomcats {
        least_conn;
        server 192.168.140.131:8080;
        server 192.168.140.132:8080;
}

Nginx负载均衡之url_hash

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法

http {
    include       mime.types;
    default_type  application/octet-stream;
    upstream tomcats {
        hash $request_uri;
        server 192.168.140.131:8080;
        server 192.168.140.132:8080;
}

Nginx负载均衡之一致性哈希(第三方)

下载参考链接:https://github.com/replay/ngx_http_consistent_hash

安装一致性哈希模块

[root@localhost src]# unzip ngx_http_consistent_hash-master.zip
[root@localhost src]# cp -a /usr/local/nginx/ /root/
[root@localhost src]# cd nginx-1.20.2

原有的编译语句加上–add-module=/usr/local/src/ngx_http_consistent_hash-master的参数(nginx -V可以查看之前预编译的语句)

[root@localhost nginx-1.20.2]# ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35 --add-module=/usr/local/src/nginx-upstream-fair-master --add-module=/usr/local/src/ngx_http_consistent_hash-master
[root@localhost nginx-1.20.2]# echo $?  #检测是否编译成功
0
[root@localhost nginx-1.20.2]# pkill nginx  #关闭nginx
[root@localhost nginx-1.20.2]# rm -rf /usr/local/nginx/sbin/nginx  #删除sbin下面的nginx,删除前记得先备份
[root@localhost nginx-1.20.2]# cp -a objs/nginx /usr/local/nginx/sbin/ # 拷贝objs下的nginx到/usr/local/nginx/sbin/中
[root@localhost nginx-1.20.2]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ls
nginx  nginx.old
[root@localhost sbin]# ./nginx -V
nginx version: nginx/1.20.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35 --add-module=/usr/local/src/nginx-upstream-fair-master --add-module=/usr/local/src/ngx_http_consistent_hash-master

配置文件:

Nginx三种一致性Hash策略:

  • consistent_hash $remote_addr; 根据客户端IP进行映射(常用)
  • consistent_hash $request_uri; 根据客户端请求的uri进行映射(常用)
  • consistent_hash $args; 根据客户端请求携带的参数进行映射
http {
    include       mime.types;
    default_type  application/octet-stream;
    upstream tomcats {
        consistent_hash $remote_addr;
        server 192.168.140.131:8080;
        server 192.168.140.132:8080;
}

扩展:upstream指令参数

  • max_conns:限制一台服务器最大的连接数,默认值0,表示不做任何限制
  • slow_start:缓慢启动,慢慢加入到集群中,必须要和权重一起使用(付费版功能)
  • down:不使用此服务器
  • backup:表示此服务器为备用服务器,其他服务器宕机了,才会运行备用服务器
  • max_fails:表示失败几次,则标记server已宕机,剔除上游服务。
  • max_timeout:表示失败之后的重试时间。
max_fails=2 fail_timeout=15s

表示在15秒内请求某一server失败达到2次后,则认为该server已经挂了或者宕机了,随后15秒内不会有新的请求到达刚刚挂掉的节点上,而是会请求到正常运作的server,15秒后会再有新请求尝试连接挂掉的server,如果还是失败,重复上一过程,直到恢复

语法案例:

upstream tomcats {
        server 192.168.140.131:8080 backup;
        server 192.168.140.132:8080 max_fails=2 fail_timeout=15s;
}

最终效果:

默认访问192.168.140.132,当这台服务器宕机时候,192.168.140.131备用机就开始工作。

文章版权声明:除非注明,否则均为柳三千运维录原创文章,转载或复制请以超链接形式并注明出处。

取消
微信二维码
微信二维码
支付宝二维码