负载均衡
架构:
概念:
nginx的负载均衡调度算法
nginx简单的负载均衡是基于方向代理之上的
1.平均轮询 #依次访问
2.加权轮询 #根据权重来进行访问,权重大的访问次数比较多 weight=1
3.ip_hash #根据用户的ip进行hash计算,只要是同一个用户发送的,就会交给同一个web
4.fair策略 #自动根据服务器的性能来分配数据
5.url_hash #根据商品的url来分配给不同的主机,购物类的网站
默认使用平均轮询,可以通过添加参数使用权重 ip哈希等
默认使用七层负载,也可以使用四层
七层负载是client发送请求给负载nginx;nginx解析后重新定义请求报文,发送给web服务器;而四层负载则是client的请求报文由nginx直接转发给后端,不需要经过解析 这个功能需要通过三条参数开启
在服务器集群中,负载均衡用于从“upstream”模块定义的后端服务器列表中选取一台服务器接受用户的请求(即反向代理),为了避免单独一个服务器压力过大,将来自用户的请求转发给不同的服务器
实验:
#负载均衡,建立在反向代理之上的
#安装两个台httpd
#apache1,192.168.5.4
yum -y install httpd
echo apache > /var/www/html/index.html
systemctl start httpd
systemctl stop firewalld
setenforce 0
curl 192.168.2.10
apache
#apache2,1
systemctl stop firewalld
setenforce 0
yum -y install httpd
echo apache2 > /var/www/html/index.html
systemctl start httpd
curl 192.168.2.40
apache2
#nginx设置七层负载
vim /usr/local/nginx/conf/nginx.conf
#gzip on;
upstream apache { #apache负载均衡集群名,自己设定
server 192.168.5.4 max_fails=2 fail_timeout=30;; #默认是轮询,未加权重
server 192.168.5.5 max_fails=2 fail_timeout=30;; #请求失败的次数,和失败后暂停时间
}
server {
listen 80;
server_name www.ceshi_3.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#root html;
#index index.html index.htm;
porxy_pass http//:apache; #设定location转向负载均衡集群
}
}
#重启nginx
killall nginx
nginx
#验证轮询效果
[root@localhost ~]# curl 192.168.5.4
apache
[root@localhost ~]# curl 192.168.5.5
apache2
[root@localhost ~]# curl 192.168.5.4
apache
[root@localhost ~]# curl 192.168.5.5
apache2
#nginx设置四层负载,添加参数
proxy_set_header Host $http_host; #获取域名
proxy_set_header X-Real-IP $remote_addr; #获取到客户端的ip;后端得到真实的ip
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #四层的,想要实现更多的并发
#四层负载参数添加方法
location / {
#root html;
#index index.html index.htm;
proxy_pass http://apache;
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;
}
rded_for;
}