nginx七层负载均衡

Nginx七层负载均衡

一、负载均衡介绍

  • 什么是负载均衡

将请求平均的分配给后端服务器
  • 为什么要使用负载均衡

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

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x50qVrYE-1623250552542)(img/image-20201202143851665.png)]

  • 负载均衡的叫法

1.负载均衡
2.负载
3.LB
4.Load Balance
  • 公有云中常见的负载均衡

1.SLB		#阿里云产品
2.LB		#青云产品
3.CLB		#腾讯云产品
4.ULB		#Ucloud产品
  • 负载均衡软件

1.nginx
2.Haproxy
3.LVS
  • 负载均衡类型

1.四层负载均衡
所谓四层负载均衡指的是OSI七层模型中的传输层,那么传输层Nginx已经能支持TCP/IP的控制,所以只需要对客户端的请求进行TCP/IP协议的包转发就可以实现负载均衡,那么它的好处是性能非常快、只需要底层进行应用处理,而不需要进行一些复杂的逻辑

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

3.四层和七层负载均衡的区别
四层负载均衡数据包在底层就进行了分发,而七层负载均衡数据包则是在最顶层进行分发、由此可以看出,七层负载均衡效率没有四负载均衡高。
但七层负载均衡更贴近于服务,如:http协议就是七层协议,我们可以用Nginx可以作会话保持,URL路径规则匹配、head头改写等等,这些是四层负载均衡无法实现的。
注意:四层负载均衡不识别域名,七层负载均衡识别域名

二、负载均衡实践

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

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

# ngx_http_upstream_module

#语法
Syntax:	upstream name { ... }
Default:	—
Context:	http

#例子
upstream backend {
    server backend1.example.com       weight=5;
    server backend2.example.com:8080;
    server backup1.example.com:8080   backup;
    server backup2.example.com:8080   backup;
}

server {
	... ...
    location / {
        proxy_pass http://backend;
    }
}
  • 环境准备

主机IP身份
lb0110.0.0.4,172.16.1.4负载均衡
web01172.16.1.7web服务端
web02172.16.1.8web服务端
  • web01准备网站

# 配置Nginx
[root@web01 ~]# vim /etc/nginx/conf.d/linux.wp.com.conf 
server {
    listen 80;
    server_name linux.wp.com;
    charset utf8;

    location / {
        root /code/wordpress;
        index index.php;
    }

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME /code/wordpress/$fastcgi_script_name;
        include fastcgi_params;
    }
}
# 上传网站代码
[root@web01 ~]# ll /code/
drwxr-xr-x 5 www www 4096 416 19:30 wordpress

# 配置hosts访问
10.0.0.7 linux.wp.com
http://linux.wp.com/
  • web02准备网站

# 配置Nginx
[root@web02 ~]# vim /etc/nginx/conf.d/linux.wp.com.conf 
server {
    listen 80;
    server_name linux.wp.com;
    charset utf8;

    location / {
        root /code/wordpress;
        index index.php;
    }

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME /code/wordpress/$fastcgi_script_name;
        include fastcgi_params;
    }
}

# 上传网站代码
[root@web02 ~]# ll /code/
drwxr-xr-x 5 www  www      4096 416 19:16 wordpress

# 配置hosts访问
10.0.0.8 linux.wp.com
http://linux.wp.com/
  • lb01配置负载均衡

[root@lb01 ~]# vim /etc/nginx/conf.d/linux.wp.com.conf 
upstream web_group {
    server 172.16.1.7:80;
    server 172.16.1.8;
}

server {
    listen 80;
    server_name linux.wp.com;

    location / {
        proxy_pass http://web_group;
        include proxy_params;
    }
}
  • 准备代理优化文件

[root@lb01 ~]# vim /etc/nginx/proxy_params
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 10s;
proxy_read_timeout 10s;
proxy_send_timeout 10s;
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 8 8k;
  • 重启访问测试

# 重启
[root@lb01 ~]# nginx -t && systemctl restart nginx

# 配置hosts
10.0.0.4 linux.wp.com

# 访问
http://linux.wp.com/

三、负载均衡常见问题

  • 问题
如果后端服务器出现问题,负载均衡仍然会将请求发送给相应机器

如果后台服务连接超时,Nginx是本身是有机制的,如果出现一个节点down掉的时候,Nginx会更据你具体负载均衡的设置,将请求转移到其他的节点上,但是,如果后台服务连接没有down掉,但是返回错误异常码了如:504、502、500,这个时候你需要加一个负载均衡的设置,如下:proxy_next_upstream http_500 | http_502 | http_503 | http_504 |http_404;意思是,当其中一台返回错误码404,500...等错误时,可以分配到下一台服务器程序继续处理,提高平台访问成功率。
  • 解决问题的模块
Syntax:	proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | http_429 | non_idempotent | off ...;
Default:	proxy_next_upstream error timeout;
Context:	http, server, location
  • 配置
[root@lb01 ~]# vim /etc/nginx/conf.d/linux.wp.com.conf
upstream blog {
    server 172.16.1.7;
    server 172.16.1.8;
}

server {
    listen 80;
    server_name linux.wp.com;

    location / {
        proxy_pass http://blog;
        include proxy_params;
        #可以配置,可以写到include
        proxy_next_upstream http_500 | http_502 | http_503 | http_504 | http_403 | http_404;
    }
}

#重启
[root@lb01 ~]# systemctl restart nginx

四、负载均衡调度算法

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

upstream blog {
    server 172.16.1.7;
    server 172.16.1.8;
}
  • 加权轮询配置

#当后端服务器配置不同的情况下会用到加权轮询。列如:一台内存为4G,一台为8G
upstream blog {
    server 172.16.1.7 weight=1;
    server 172.16.1.8 weight=2;
}
  • ip_bash配置方法

upstream web_group {
    server 172.16.1.7:80;
    server 172.16.1.8;
    ip_hash;
}

#一般用来做会话保持

五、负载均衡后端状态

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

upstream blog {
	#一般情况下,维护场景使用
    server 172.16.1.7 down;
    server 172.16.1.8;
}
  • backup状态配置

upstream web_group {
    server 172.16.1.7;
    server 172.16.1.8 backup;
}
  • 访问错误状态配置

upstream web_group {
    server 172.16.1.7;
    server 172.16.1.8 max_fails=3 fail_timeout=10s;
}
  • 最大连接数配置

upstream web_group {
    server 172.16.1.7;
    server 172.16.1.8 max_conns=100;
}

六、Nginx负载均衡健康检查

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

[root@lb02 ~]# yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel patch
  • 下载第三方模块

[root@lb02 ~]# wget http://nginx.org/download/nginx-1.14.2.tar.gz
[root@lb02 ~]# wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/master.zip
  • 解压及安装

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

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

[root@lb02 ~]# cd nginx-1.14.2/

[root@lb02 nginx-1.14.2]# patch -p1 <../nginx_upstream_check_module-master/check_1.14.0+.patch
[root@lb02 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@lb02 nginx-1.14.2]# make && make install
  • 在已有的负载均衡上增加健康检查的功能

[root@lb01 conf.d]# cat proxy_web.conf
upstream web {
    server 172.16.1.7:80 max_fails=2 fail_timeout=10s;
    server 172.16.1.8:80 max_fails=2 fail_timeout=10s;
    check interval=3000 rise=2 fall=3 timeout=1000 type=tcp;
    #interval  检测间隔时间,单位为毫秒
    #rise      表示请求2次正常,标记此后端的状态为up
    #fall      表示请求3次失败,标记此后端的状态为down
    #type      类型为tcp
    #timeout   超时时间,单位为毫秒
}

server {
    listen 80;
    server_name linux.lb.com;
    location / {
        proxy_pass http://web;
        include proxy_params;
    }

    location /upstream_check {
        check_status;
    }
}
  • 重启访问页面

#重启
#配置hosts
#访问
http://linux.lb.com/upstream_check

七、Nginx负载均衡会话保持

  • 什么是会话保持

我们在访问网站的时候,进行登陆以后,服务器上回生成一个 session,然后服务器会携带着session_id返回给浏览器记录一个 cookie 值,当第二次访问时,cookie会来服务器上与session进行对比,如果对比成功,则不需要重新登录

在使用负载均衡的时候会遇到会话保持的问题,可通过如下方式进行解决。
1.使用nginx的ip_hash,根据客户端的IP,将请求分配到对应的IP上
2.基于服务端的session会话共享(NFS,MySQL,memcache,redis,file)
  • session共享的方法

1.把多台后端服务器session文件目录挂载到NFS同一目录
2.通过程序将session存储到mysql数据库
3.通过程序将session存储到redis缓存
  • web01上搭建phpmyadmin

上传包

[root@web01 ~]# cd /code/
[root@web01 code]# rz                                                                               
[root@web01 code]# ll
-rw-r--r--. 1 root root 11060845 Oct 18 10:48 phpMyAdmin-4.9.0.1-all-languages.zip

解压

并改名[root@web01 code]# unzip phpMyAdmin-4.9.0.1-all-languages.zip
[root@web01 code]# mv phpMyAdmin-4.9.0.1-all-languages php

修改连接数据库代码

[root@web01 code]# cp /code/php/{config.sample.inc.php,config.inc.php}
[root@web01 code]# vim /code/php/config.inc.php
$cfg['Servers'][$i]['host'] = '172.16.1.51';

授权站点目录

[root@web01 code]# chown -R www.www /code/

配置nginx

[root@web01 ~]# vim /etc/nginx/conf.d/linux.php.com.conf
server {
    listen 80;
    server_name linux.php.com;
    root /code/php;

    location / {
        index index.php;
    }

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
[root@web01 ~]# systemctl restart nginx

配置hosts访问

#配置hosts
10.0.0.7 linux.php.com

#访问页面  http://linux.php.com/

#报错:
Error during session start; please check your PHP and/or webserver log file and configure your PHP installation properly. Also ensure that cookies are enabled in your browser.
session_start(): open(SESSION_FILE, O_RDWR) failed: Permission denied (13)
session_start(): Failed to read session data: files (path: /var/lib/php/session)

#解决:
[root@web01 ~]# chown -R www.www /var/lib/php/session

再次登录测试

#登录测试,如果登录用户密码错误
mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'172.16.1.7' (using password: YES)

#数据库授权
MariaDB [(none)]> grant all on *.* to root@'172.16.1.%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
  • web02同步web01

同步站点文件

[root@web01 ~]# scp -r /code/php 172.16.1.8:/code/

同步nginx配置

[root@web01 ~]# scp /etc/nginx/conf.d/linux.php.com.conf 172.16.1.8:/etc/nginx/conf.d/

授权目录

[root@web01 ~]# chown -R www.www /var/lib/php/session
[root@web02 ~]# chown -R www.www /code/

访问测试

#重启
[root@web02 ~]# systemctl restart nginx

#配置hosts
linux.php.com

#访问
http://linux.php.com/index.php
  • 配置负载均衡

配置

[root@lb01 ~]# vim /etc/nginx/conf.d/linux.php.com.conf
upstream phpmyadmin {
    server 172.16.1.7;
    server 172.16.1.8;
}

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

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

[root@lb01 ~]# 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 ~]# systemctl restart nginx

访问

#配置hosts
10.0.0.4 linux.php.com

#访问报错
Failed to set session cookie. Maybe you are using HTTP instead of HTTPS to access phpMyAdmin.
  • 解决方式一

挂载session文件的目录

[root@web01 ~]# mount -t nfs 172.16.1.31:/data/wp /var/lib/php/session/
[root@web02 ~]# mount -t nfs 172.16.1.31:/data/wp /var/lib/php/session/
  • 解决方式二

使用redis实现session共享
安装redis

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

配置服务

[root@db01 ~]# vim /etc/redis.conf
bind 172.16.1.51

启动服务

[root@db01 ~]# systemctl start redis
#检查
[root@db01 ~]# netstat -lntp
tcp        0      0 172.16.1.51:6379        0.0.0.0:*               LISTEN      13305/redis-server

修改PHP服务将session存储到redis

[root@web01 ~]# vim /etc/php.ini
#原配置
#session.save_handler = files
session.save_handler = redis
#;session.save_path = "/tmp"
session.save_path = "tcp://172.16.1.51:6379"

[root@web01 ~]# vim /etc/php-fpm.d/www.conf
#注释以下两行
;php_value[session.save_handler] = files
;php_value[session.save_path]    = /var/lib/php/sessionl

重启

[root@web01 ~]# systemctl restart php-fpm

再次访问测试

http://linux.php.com/index.php
#登录没有问题

redis验证session

1.连接进入redis
[root@db01 ~]# redis-cli -h 172.16.1.51

2.查看所有key
172.16.1.51:6379> keys *

3.查看session的生存时间
172.16.1.51:6379> TTL PHPREDIS_SESSION:43948cd72f7589982cc3758f9d5c2b8d
(integer) 1265

4.退出
172.16.1.51:6379> quit
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值