11.Nginx负载均衡

时间:2019-08-30
本文章向大家介绍11.Nginx负载均衡,主要包括11.Nginx负载均衡使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、Nginx七层负载均衡

1. Nginx负载均衡概述

1.1 Nginx负载均衡概述为什么需要使用负载均衡

当我们的web服务器直接面向用户,往往要承载大量并发请求,单台服务器难以负荷,我使用多台web服务器组成的集群,前端使用nginx负载均衡,将请求分散的发送到我们的后端服务器集群中,实现负载的分发,那么会大提升系统的吞吐率、请求性能、高容灾;

Nginx负载均衡

负载
负载均衡
调度
load balance
LB

公有云

SLB 阿里云负载均衡
QLB 青云负载均衡
CLB 腾讯负载均衡
ULB ucloud的负载均衡

往往我们接触最多的是SLB(Server Load Balane)负载均衡,实现最多的䦹SLB、那么SLB它的调度节点和服务节点通常是在一个地狱里面,那么他在这个小的逻辑地域里面决定了他对部分服务的实时性、响应性是非常好的。

所以说当海量用户请求过来以后,他同样是请求调度节点,调度节点将用户的请求转发给后端对应的服务街店,服务街店处理完请求后再转发给调度节点,调度节点最后响应给用户节点,这样也能实现一个均衡的作用,那么nginx则是一个典型的SLB

1.2 负载均衡能实现的应用场景一:四层负载均衡

所谓四层负载均衡指的是OSI七层模型总得传输层,那么传输层nginx已经能智齿TCP/IP的控制,所以只需要对客户端进行TCP/IP协议的包转发就可以实现负载均衡,那么他的好处是性能非常快,只需要底层进行应用处理,而不需要进行一些复杂的逻辑。

1.3 负载均衡能实现的应用场景二:七层负载均衡

七层负载均衡它是在应用层,那么他可以完成很多应用方面的协议请求,比如说我们说的http应用的负载均衡,他可以实现http信息的改写、头信息的改写、安全应用规则控制、URL匹配规则控制,以及转发、rewrite等等的规则,所以在应用层的服务里面,我们可以做的内容就更多,那么nginx则是一个典型的七层负载均衡SLB

1.4 四层负载均衡与七层负载均衡区别

四层负载均衡数据包在底层就进行了分发,而七层负载均衡数据包则是在最顶层进行分发,由此可以看出,七层负载均衡效率没有四层负载均衡高。

但七层负载均衡更贴近于服务,如:http协议就是七层协议,我们可以用Nginx做会话保持,URL路径规则匹配、head头改写等等,这些是四层负载均衡无法实现的。


2. Nginx负载均衡配置场景

Nginx要实现负载均衡需要用到proxy_pass代理模块

Nginx负载均衡与Nginx代理不同地方在于,Nginx代理仅代理一台服务器,而Nginx负载均衡则是将客户端请求代理转发至一组upstream虚拟服务池

2.1 Nginx upstream虚拟配置语法

句法:Syntax:  upstream name {...}
默认:Default: -
语境:Context: http

#upstream例
upstream backend {
        server backend1.example.com         weight=5;
        server backend2.example.com:8080;
        server backend1.example.com:8080    backup;
}
server {
        location / {
                proxy_pass http://backend;
        }
}

2.2 环境规划

角色 外网IP(NAT) 内网IP(LAN) 主机名
LB01 eth0:10.0.0.5 eth1:172.16.1.5 lb01
web01 eth0:10.0.0.7 eth1:172.16.1.7 web01
web02 eth0:10.0.0.8 eth1:172.16.1.8 web02

2.3 web01服务器上配置nginx,并创建html文件

[root@web01 ~]# cd /etc/nginx/conf.d/
[root@web01 conf.d]# cat node.conf 
server {
        listen 80;
        server_name node.haoda.com;

        location / {
                root /node;
                index index.html;
        }
}
[root@web01 conf.d]# mkdir /node
[root@web01 conf.d]# cat /node/index.html 
Web01......
[root@web01 conf.d]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# nginx -s reload

2.4 web02服务器上配置nginx,并创建html文件

[root@web02 ~]# cd /etc/nginx/conf.d/
[root@web02 conf.d]# cat node.conf 
server {
        listen 80;
        server_name node.haoda.com;

        location / {
                root /node;
                index index.html;
        }
}
[root@web02 conf.d]# mkdir /node
[root@web02 conf.d]# cat /node/index.html 
Web02......
[root@web02 conf.d]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web02 conf.d]# nginx -s reload

2.5 配置lb负载均衡服务器

[root@lb01 ~]# cd /etc/nginx/conf.d/
[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80;
        server 172.16.1.8:80;
}
server {
        listen 80;
        server_name node.haoda.com;

        location / {
                proxy_pass http://node;
                include proxy_params;
        }
}

#网页测试

2.6 为之前的blog和zh配置lb负载

[root@lb01 conf.d]# vim proxy_haoda.com.conf
upstream node {
    server 172.16.1.7:80;
    server 172.16.1.8:80;
}
server {
        listen 80;
        server_name blog.oldboy.com;
        location / {
                proxy_pass http://node;
                include proxy_params;
        }
}

server {
        listen 80;
        server_name zh.oldboy.com;
        location / {
                proxy_pass http://node;
                include proxy_params;
        }
}

3. Nginx负载均衡调度算法

调度算法 概述
轮询 按时间顺序逐一分配到不同的后端服务器(默认)
weight 加权轮询,weight值越大,分配到的访问几率越高
ip_hash 每个请求按访问IP的hash结果分配,这样来自同一IP的固定访问一个后端服务器
url_hash 按照访问URL的hash结果来分配请求,是每个URL定向到同一个后端服务器
least_conn 最少连接数,哪台机器连接少就分到哪台机器

3.1 Nginx负载均衡[wrr]轮询具体配置

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80;
        server 172.16.1.8:80;
}

3.2 Nginx负载均衡weight加权轮询具体配置

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80 weight=5;
        server 172.16.1.8:80 weight=1;
}

3.3 Nginx负载均衡ip_hash具体配置

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        ip_hash;
        server 172.16.1.7:80;
        server 172.16.1.8:80;
}

#ip_hash和加权轮询没有必要一起使用;
#ip_hash可以解决会话登录、会话保持问题,但是也会造成负载不均衡,一台机器流量大,一台机器流量小;

4. Nginx负载均衡后端状态

后端web服务器在前端nginx负载均衡调度中的状态

状态 概述
down 当前的server暂时不参与负载均衡
backup 预留的备份服务器
max_fails 允许请求失败的次数
fail_timeout 经过max_fails失败后,服务暂停时间
max_conns 限制最大的连接数

4.1 测试down状态,测试该Server不参与负载均衡的调度

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80 down;          #不参与任何调度,一般用于停机维护
        server 172.16.1.8:80;
}

4.2 测试backup状态

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80 backup;        #其他server机器都不可用时,才会使用该server
        server 172.16.1.8:80;
}

4.3 测试max_fails、fail_timeout状态

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80 max_fails=2 fail_timeout=10s;
        server 172.16.1.8:80 max_fails=2 fail_timeout=10s;
}

5. Nginx负载均衡健康检查

在Nginx官方模块提供服务的健康状态的模块中,没有对应负载均衡后端节点的健康检查模块,但可以使用第三方模块nginx_upstream_check_module来检测后方服务的健康状态

upstream_check_module项目地址

5.1 安装依赖包

[root@lb01 ~]# yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel  patch

5.2 下载nginx源码包以及nginx_upstream_check模块第三方模块

[root@lb01 ~]# wget http://nginx.org/download/nginx-1.14.2.tar.gz
[root@lb01 ~]# wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/master.zip

5.3 解压nginx源码包以及第三方模块

[root@lb01 ~]# tar xf nginx-1.14.2.tar.gz
[root@lb01 ~]# unzip master .zip

5.4 进入nginx目录,打补丁(nginx的版本是1.14补丁就选择1.14的,p1代表在nginx目录,p0是不在nginx目录)

[root@lb01 ~]# cd nginx-1.14.2/
[root@lb01 nginx-1.14.2]# patch -p1 <../nginx_upstream_check_module-master/check_1.14.0+.patch
patching file src/http/modules/ngx_http_upstream_hash_module.c
patching file src/http/modules/ngx_http_upstream_ip_hash_module.c
patching file src/http/modules/ngx_http_upstream_least_conn_module.c
patching file src/http/ngx_http_upstream_round_robin.c
patching file src/http/ngx_http_upstream_round_robin.h
[root@lb01 nginx-1.14.2]# 

5.5 编译安装

#编译参数获取
[root@lb01 nginx-1.14.2]# nginx -V

#获取编译参数后加一个参数--add-module=/root/nginx_upstream_check_module-master
[root@lb01 nginx-1.14.2]# ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --add-module=/root/nginx_upstream_check_module-master --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

[root@lb01 nginx-1.14.2]# make && make install

5.6 在已有的负载均衡上增加健康检查的功能

[root@lb01 conf.d]# cat node_proxy.conf 
upstream node {
        server 172.16.1.7:80 weight=1;
        server 172.16.1.8:80 weight=1;
        check interval=3000 rise=2 fall=3 timeout=1000 type=tcp;
        #interval 表示检测间隔时间,单位是毫秒;
        #rise 表示请求2次正常,标记次后端的状态为up;
        #fall 表示请求3次失败,标记次后端的状态为down;
        #timeout 表示超时时间,单位为毫秒;
        #type 表示类型为 TCP
}
server {
        listen 80;
        server_name node.haoda.com;

        location / {
                proxy_pass http://node;
                include proxy_params;
        }

        location /upstream_check {
                check_status;
        }
}

5.7 通过域名访问查看

5.7.1 打开http://node.haoda.com//upstream_check检查页面

5.7.2 关闭一台后端server再次打开http://node.haoda.com//upstream_check检查页面查看


6. Nginx负载均衡会话共享

在使用负载均衡的时候会遇到会话保持的问题,可通过如下方式进行解决

1.使用nginx的ip_hash,根据客户端的IP,将请求分配到不同的服务器上
2.基于服务的Session会话共享(mysql、memcache、redis、file)

在解决负载均衡回话问题我们需要了解session和cookie的区别。
浏览器端存的是cookie,每次浏览器发请求到服务端时报文头时会自动添加cookie信息;
服务端会查询用户的cookie作为key去存储里找对应的value(session)
同一域名下的网站的cookie都是一样的,所以无论几台服务器,无论请求分配到哪一台服务器上同一用户的cookie是不变的,也就是说cookie对应的session也是唯一的,所以,这里只要保证多台业务服务器访问同意个共享服务器(mysql、memcache、redis、file)就行了

6.1 web01服务器安装PHPmyadmin

[root@web01 conf.d]# cd /code
[root@web01 code]# wget https://files.phpmyadmin.net/phpMyAdmin/4.9.0.1/phpMyAdmin-4.9.0.1-all-languages.zip
[root@web01 code]# unzip phpMyAdmin-4.9.0.1-all-languages.zip

6.2 配置PHPmyadmin连接远程数据库

[root@web01 ~]# cd phpMyAdmin-4.9.0.1-all-languages/
[root@web01 phpMyAdmin-4.9.0.1-all-languages]# cp config.sample.inc.php config.inc.php
[root@web01 phpMyAdmin-4.9.0.1-all-languages]# vim config.inc.php
#修改该条配置
$cfg['Servers'][$i]['host'] = '172.16.1.51';

6.3 配置Nginx

[root@web01 conf.d]# cat php.conf
server {
        listen 80;
        server_name php.haoda.com;
        root /code/phpMyAdmin-4.9.0.1-all-languages;

        location / {
                index index.php index.html;
}

        location ~ \.php$ {
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}
[root@web01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# nginx -s reload

#页面报错,配置授权
[root@web01 code]# chown -R www.www /var/lib/php/session    

6.4 使用浏览器访问页面,获取cookie信息

6.5 web02服务器同步web01

[root@web01 code]# scp -r phpMyAdmin-4.9.0.1-all-languages 172.16.1.8:/code/
[root@web02 code]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web02 code]# nginx -s reload
[root@web02 code]# chown -R www.www /var/lib/php/session

6.6 配置负载均衡

[root@lb01 conf.d]# cat proxy_php.conf 
upstream php {
        server 172.16.1.7:80;
        server 172.16.1.8:80;
}

server {
        listen 80;
        server_name php.haoda.com;

        location / {
                proxy_pass http://php;
                include proxy_params;
        }
}

[root@lb01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@lb01 conf.d]# nginx -s reload

6.7 准备Redis内存共享服务

6.7.1 安装redis

[root@db01 ~]# yum install -y redis

6.7.2 配置redis监听172.16.1.51网卡上

[root@db01 ~]# sed -i '/^bind/c bind 127.0.0.1 172.16.1.51' /etc/redis.conf

6.7.3 启动redis

[root@db01 redis]# systemctl start redis
[root@db01 redis]# systemctl enable redis
Created symlink from /etc/systemd/system/multi-user.target.wants/redis.service to /usr/lib/systemd/system/redis.service.
[root@db01 redis]#

6.8 php配置session连接redis

6.8.1 修改/etc/php.ini文件

[root@web01 code]# vim /etc/php.ini
session.save_handler = redis
session.save_path = "tcp://172.16.1.51:6379"
;session.save_path = "tcp://172.16.1.51:6379?auth=123" #如果redis存在密码,则使用该方式
session.auto_start = 1

6.8.2 注释php-fpm.d/www.conf里面的两条内容,否则session内容会一直写入/var/lib/php/session目录中

[root@web01 code]# vim /etc/php-fpm.d/www.conf
;php_value[session.save_handler] = files
;php_value[session.save_path]    = /var/lib/php/session

6.8.3 重启php-fpm

[root@web01 code]# systemctl restart php-fpm.service

6.8.4 web服务器同步

[root@web01 code]# scp /etc/php.ini 172.16.1.8:/etc/php.ini    
[root@web01 code]# scp /etc/php-fpm.d/www.conf 172.16.1.8:/etc/php-fpm.d/www.conf 
[root@web02 code]# systemctl restart php-fpm

6.9 浏览器查看cookie对比redis数据

[root@db01 redis]# redis-cli
127.0.0.1:6379> keys *
1) "PHPREDIS_SESSION:1365eaf0490be9315496cb7382965954"

二、Nginx四层负载均衡

1. Nginx四层负载均衡概述

1.1 什么是四层负载均衡

四层负载均衡是基于传输层协议包来封装的(如:TCP/IP),那我们前面使用到的七层是指的应用层,他的组装在四层的基础之上,无论四层还是七层都是指的OSI网络模型。

1.2 四层负载均衡应用场景

1、四层+七层来做负载均衡,四层可以保证七层的负载均衡的高可用性;如:nginx就无法保证自己的服务高可用,需要依赖LVS或者keepalive。

2、如:tcp协议的负载均衡,有些请求是TCP协议的(mysql、ssh),或者说这些请求只需要使用四层进行端口的转发就可以了,所以使用四层负载均衡。

1.3 四层+七层构建大规模集群架构使用场景

四层负载均衡总结

1、四层负载均衡仅能转发TCP/IP协议、UDP协议、通常用来转发端口,如:tcp/22、udp/53;

2、四层负载均衡可以用来解决七层负载均衡端口限制问题;(七层负载均衡最大使用65535个端口号)

3、四层负载均衡可以解决七层负载均衡高可用问题;(多台后端七层负载均衡能同事的使用)

4、四层的转发效率比七层的高得多,但仅支持tcp/ip协议,不支持http和https协议;

5、通常大并发场景通常会选择使用在七层负载前面增加四层负载均衡。


2. Nginx四层负载均衡场景实践

Nginx如何配置四层负载均衡

1、通过访问负载均衡的5555端口,实际是后端的web01的22端口在提供服务;

2、通过访问负载均衡的6666端口,实际是后端的mysql的3306端口在提供服务。

2.1 Nginx四层负载均衡场景实践

2.1.1 在lb02上配置yum源

[root@lb02 ~]# cat /etc/yum.repos.d/nginx.repo 
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
[root@lb02 ~]# 

2.1.2 在lb02上安装nginx

[root@lb02 yum.repos.d]# yum install -y nginx

2.1.3 在lb02上同步lb01的所有nginx相关配置

[root@lb02 ~]# scp -r root@172.16.1.5:/etc/nginx /etc/

2.1.4 启动nginx

[root@lb02 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@lb02 conf.d]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@lb02 conf.d]# nginx

2.1.5 创建存放四层负载均衡配置的目录

[root@lb02 ~]# vim /etc/nginx/nginx.conf
events {
        ....
}
include /etc/nginx/conf.c/*.conf;
http {
        .....
}

[root@lb02 ~]# mkdir /etc/nginx/conf.c

2.1.6 配置四层负载均衡

[root@web03 conf.c]# cat lb_domain.conf 
stream {
    upstream lb {
            server 172.16.1.5:80 weight=5 max_fails=3 fail_timeout=30s;
            server 172.16.1.6:80 weight=5 max_fails=3 fail_timeout=30s;
    }

    server {
            listen 80;
            proxy_connect_timeout 3s;
            proxy_timeout 3s;
            proxy_pass lb;
    }
}
[root@web03 conf.c]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web03 conf.c]# nginx -s reload

#配置本机hosts解析后浏览器访问并查看nginx日志

2.1.7 四层负载均衡开启日志

#四层负载均衡是没有access的日志的,因为在nginx.conf的配置中,access的日志格式是配置在http下的,而四层复杂均衡配置实在http以外的;

#如果需要日志则需要配置在stream下面
[root@web03 conf.c]# cat lb_domain.conf 
stream {
    log_format  proxy '$remote_addr $remote_port - [$time_local] $status $protocol '
                  '"$upstream_addr" "$upstream_bytes_sent" "$upstream_connect_time"' ;
    access_log /var/log/nginx/proxy.log proxy;
    upstream lb {
            server 172.16.1.5:80 weight=5 max_fails=3 fail_timeout=30s;
            server 172.16.1.6:80 weight=5 max_fails=3 fail_timeout=30s;
    }

    server {
            listen 80;
            proxy_connect_timeout 3s;
            proxy_timeout 3s;
            proxy_pass lb;
    }
}

2.2 Nginx四层负载均衡端口转发

2.2.1 使用nginx四层负载均衡实现tcp的转发

请求负载均衡 5555    --->     172.16.1.7:22;
请求负载均衡 6666    --->     172.16.1.51:3306;

2.2.2 配置nginx四层负载均衡实现tcp的转发

[root@lb4-01 ~]# cat /etc/nginx/conf.c/lb_domain.conf 
stream {
    log_format  proxy '$remote_addr $remote_port - [$time_local] $status $protocol '
                      '"$upstream_addr" "$upstream_bytes_sent" "$upstream_connect_time"' ;
    access_log /var/log/nginx/proxy.log proxy;

#定义转发ssh的22端口
    upstream ssh_7 {
            server 10.0.0.7:22;
    }
#定义转发mysql的3306端口
    upstream mysql_51 {
            server 10.0.0.51:3306;
    }
    server {
            listen 5555;
            proxy_connect_timeout 3s;
            proxy_timeout 300s;
            proxy_pass ssh_7;
    }

    server {
            listen 6666;
            proxy_connect_timeout 3s;
            proxy_timeout 3s;
            proxy_pass mysql_51;
    }
}

原文地址:https://www.cnblogs.com/chenmiao531759321/p/11436161.html