- 为什么要使用负载均衡
- 解决web服务器的单点故障,让web服务器做成一个集群
- 将请求平均下发给后端的web服务器
负载均衡的叫法
LB:Load Balance
SLB:Server Load Balance
公有云中的叫法
阿里云:SLB
腾讯云:CLB
青云:QLB(LB)
ucloud:ULB
AWS:ELB
负载均衡产品
- 软件
- Nginx
- HAproxy
- LVS
- 硬件
- F5
四层负载均衡和七层负载均衡的区别
- 1.一个是四层:传输层,一个是七层:应用层
- 2.四层传输速度要比七层快
- 3.四层无法识别域名,七层可以识别域名
负载均衡实现场景
Nginx要实现负载均衡需要用到 proxy_pass 代理模块配置 Nginx负载均衡与Nginx代理不同地方在于,Nginx的一个 location 仅能代理一台服务器,而Nginx负载均衡则是 将客户端请求代理转发至一组upstream虚拟服务池.
负载均衡
Syntax: upstream name { ... }
Default: —
Context: http
upstream name {
server xxx;
server xxx;
}
官方案例配置
## upstream模块配置
模块名 后端主机池:名字(根据网站域名起名)
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
server backup1.example.com:8080 backup;
server backup2.example.com:8080 backup;
}
server {
location / {
proxy_pass http://backend;
}
}
upstream blog.yjt.com {
server 172.16.1.7:8888;
server 172.16.1.8;
}
server {
location / {
proxy_pass http://blog.yjt.com;
}
}
配置负载均衡
环境准备
主机名 | WanIP | LanIP | 角色 | 应用 |
lb01 | 10.0.0.5 | 172.16.1.5 | 负载均衡 | nginx |
web01 | 10.0.0.7 | 172.16.1.7 | web网站 | nginx、php |
web02 | 10.0.0.8 | 172.16.1.8 | web网站 | nginx、php |
编辑nginx配置文件
[root@web01 conf.d]# vim /etc/nginx/conf.d/lb.yjt.com.conf
server{
listen 9999;
server_name lb.yjt.com;
root /code/lb;
index index.html;
}
[root@web02 conf.d]# vim /etc/nginx/conf.d/lb.yjt.com.conf
server{
listen 9999;
server_name lb.yjt.com;
root /code/lb;
index index.html;
}
[root@web01 conf.d]# mkdir /code/lb
[root@web02 conf.d]# mkdir /code/lb
[root@web01 conf.d]# echo 'web01' > /code/lb/index.html
[root@web02 conf.d]# echo 'web02' > /code/lb/index.html
[root@web01 conf.d]# nginx -t
[root@web01 conf.d]# systemctl reload nginx
[root@web02 conf.d]# nginx -t
[root@web02 conf.d]# systemctl reload nginx
## 域名解析
10.0.0.7 lb.yjt.com
# 配置负载均衡
[root@lb01 ~]# vim /etc/nginx/conf.d/lb.yjt.com.conf
upstream lb.yjt.com {
server 172.16.1.7:9999;
server 172.16.1.8:9999;
}
server {
listen 80;
server_name lb.yjt.com;
location /{
proxy_pass http://lb.yjt.com;
include proxy_params;
}
}
负载均衡常见典型故障
如果后台服务连接超时,Nginx是本身是有机制的,如果出现一个节点down掉的时候,Nginx会更据你具体负载均衡 的设置,将请求转移到其他的节点上,但是,如果后台服务连接没有down掉,但是返回错误异常码了如:504、 502、500,这个时候你需要加一个负载均衡的设置,如下:proxy_next_upstream http_500 | http_502 | http_503 | http_504 |http_404;意思是,当其中一台返回错误码404,500...等错误时,可以分配到下一台服务器程序继续处 理,提高平台访问成功率。
## 解决方案
### 遇到如下状态码的机器,跳过请求的下发,直接下发到其他正常的服务器
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
upstream lb.zls.com {
server 172.16.1.7:9999;
server 172.16.1.8:9999;
server 172.16.1.9:9999;
}
server {
listen 80;
server_name lb.yjt.com;
location /{
proxy_pass http://lb.yjt.com;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
include proxy_params;
}
}
负载均衡调度算法
调度算法 | 概述 |
轮询(rr) | nginx做负载均衡默认使用轮询的调度算法:将请求平均下发到后端的web服务器 |
加权轮询(wrr) | 增加权重,根据服务器的配置,给轮询加上权重 |
源IP(ip_hash) | 根据用户的IP,将同一IP地址的请求,下发到同一台服务器上 |
源url(url_hash) | 根据用户访问的URL,将同一URL的请求,下发到同一台服务器上 |
最小连接数 | 哪台服务器的连接数最少,就将请求下发到该服务器上 |