负载均衡会话保持及健康检查

一、回顾

1.负载均衡的作用

1.把请求平均的分配到后端服务器上
2.后端服务器的高可用

2.负载均衡的软件和类型

1.nginx			支持四层负载均衡和七层负载均衡
2.LVS			只支持四层负载均衡
3.haproxy		支持四层负载均衡和七层负载均衡

3.负载均衡语法

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 {
	listen 80;
	server_name www.test.com;
    location / {
        proxy_pass http://backend;
    }
}

4.负载均衡调度算法

调度算法 说明
轮询 逐一的将请求平均的分配到后端
加权轮询 根据设置的权重值,将请求按比例分配至后端服务器
ip_hash 根据访问来源的IP将请求始终分配到一台机器
url_hash 根据访问的url,将请求始终分配到一台机器
least_conn 哪一台机器接收的请求少,就将新的请求分配到哪一台机器

二、负载均衡后端状态

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

1.down状态配置测试

[root@lb01 ~]# vim /etc/nginx/conf.d/proxy.conf 
upstream web {
    server 172.16.1.7:80 down;
    server 172.16.1.9:80;
}
#一般在代码上线或维护服务器时使用该状态

2.backup状态测试

[root@lb01 ~]# vim /etc/nginx/conf.d/proxy.conf 
upstream web {
    server 172.16.1.7:80;
    server 172.16.1.9:80;
    server 172.16.1.10:80 backup;
    server 172.16.1.11:80 backup;
}

3.max_fails配置

[root@lb01 ~]# vim /etc/nginx/conf.d/proxy.conf 
upstream web {
    server 172.16.1.7:80 max_fails=3 fail_timeout=10s;
    server 172.16.1.9:80;
}

4.测试max_conns最大TCP连接数

[root@lb01 ~]# vim /etc/nginx/conf.d/proxy.conf 
upstream web {
    server 172.16.1.7:80 max_conns=10;
    server 172.16.1.9:80;
}

三、负载均衡结合项目

1.配置blog的负载均衡

[root@lb01 ~]# vim /etc/nginx/conf.d/blog.conf 
upstream blog {
    server 172.16.1.7:80;
    server 172.16.1.9:80;
}

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

    location / {
        proxy_pass http://blog;
        include /etc/nginx/proxy_params;
    }
}

[root@lb01 ~]# systemctl restart nginx
#配置hosts,访问测试

2.配置wecenter的负载均衡

[root@lb01 ~]# vim /etc/nginx/conf.d/zh.conf 
upstream zh {
    server 172.16.1.7:80;
    server 172.16.1.9:80;
}

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

    location / {
        proxy_pass http://zh;
        include /etc/nginx/proxy_params;
    }
}

3.负载均衡常见错误

1)错误

如果后端服务器返回报错,负载均衡仍然会将请求分配到出错的web服务器,因为负载均衡只会根据调度算法将请求分配到后端,不会进行判断后端是否正常

2)解决错误的模块语法

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

3)配置方法

[root@lb01 ~]# vim /etc/nginx/conf.d/zh.conf 
upstream zh {
    server 172.16.1.7:80;
    server 172.16.1.9:80;
}

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

    location / {
        proxy_pass http://zh;
        include /etc/nginx/proxy_params;
        proxy_next_upstream http_502 error timeout;
    }
}

四、Nginx负载均衡健康检查

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

1.安装依赖包

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

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

[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

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

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

4.进入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

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

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

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

[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.web.com;
    location / {
        proxy_pass http://web;
        include proxy_params;
    }

    location /upstream_check {
        check_status;
    }
}

#编辑优化文件
[root@lb02 /etc/nginx]# vim /etc/nginx/proxy_params 
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 8 128k;

6.创建用户和目录

[root@lb02 /etc/nginx]# groupadd nginx -g 666
[root@lb02 /etc/nginx]# useradd nginx -u 666 -g 666

[root@lb02 /etc/nginx]# mkdir /var/cache/nginx/

7.启动并访问

[root@lb02 /etc/nginx]# /usr/sbin/nginx

#配置hosts
10.0.0.5 linux.web.com

五、Nginx负载均衡会话保持

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

1.session共享的方法

1.把多台机器的session文件挂载到NFS
2.通过程序将session存储到MySQL数据库
3.通过程序将session存储到redis

2.搭建第一台phpmyadmin

1)上传包

[root@web01 ~]# cd /code/
[root@web01 /code]# rz phpMyAdmin-4.9.0.1-all-languages.zip

2)解压

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

3)配置代码

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

4)配置nginx

[root@web01 /code]# 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;
    }
}

5)重启访问

[root@web01 /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@web01 /code]# systemctl restart nginx

#配置hosts
10.0.0.7 linux.php.com

6)访问页面错误

#报错
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 /code]# chown -R www.www /var/lib/php/session

7)再次访问测试

#如果忘记数据库远程连接密码
[root@db01 ~]# mysql -uroot -pLinhd@123

MariaDB [(none)]> grant all on *.* to root@'172.16.1.%' identified by '123';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> select user,host,password from mysql.user;

3.同步配置到第二台服务器

1)推送配置和站点

#推送站点目录
[root@web01 /code]# scp -r /code/php 172.16.1.9:/code/

#推送nginx配置
[root@web01 /code]# scp /etc/nginx/conf.d/linux.php.com.conf 172.16.1.9:/etc/nginx/conf.d/

2)重启访问

[root@web03 ~]# systemctl restart nginx

#配置hosts
10.0.0.9 linux.php.com

3)授权目录

#报错
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@web03 /code]# chown -R www.www /var/lib/php/session

4.配置负载均衡

1)配置

[root@lb01 ~]# cp /etc/nginx/conf.d/blog.conf /etc/nginx/conf.d/php.conf
[root@lb01 ~]# vim /etc/nginx/conf.d/php.conf
upstream php {
    server 172.16.1.7:80;
    server 172.16.1.9:80;
}

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

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

2)重启并访问

[root@lb01 ~]# systemctl restart nginx

#配置hosts
10.0.0.4 linux.php.com

5.使用redis实现session共享

1)安装redis

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

2)配置redis

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

3)启动redis

[root@db01 ~]# systemctl start redis

#检查启动
[root@db01 ~]# netstat -lntp  
tcp        0      0 172.16.1.51:6379        0.0.0.0:*          LISTEN      29104/redis-server
tcp        0      0 127.0.0.1:6379          0.0.0.0:*          LISTEN      29104/redis-server 

4)配置PHP服务将session存储到redis

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

[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

5)重启php

[root@web01 /code]# systemctl restart php-fpm
[root@web03 /code]# systemctl restart php-fpm

6)访问测试

7)redis查看seesion

[root@db01 ~]# redis-cli 
127.0.0.1:6379> keys *
1) "PHPREDIS_SESSION:8b8721df0b5736149ea0c716f05773e9"
2) "PHPREDIS_SESSION:b59336d7a1a053c6d26c2550032c1609
127.0.0.1:6379> TTL PHPREDIS_SESSION:b59336d7a1a053c6d26c2550032c1609
(integer) 1199

原文地址:https://www.cnblogs.com/xiaolang666/p/13596923.html