实现一个简单的负载均衡
配置两台负载均衡的机器,也是一样的操作(lb01,lb02)
配置lb01
该负载均衡功能是由Nginx提供,修改nginx.conf如下
1.添加一个负载均衡池参数
#定义负载均衡地址池,填入web服务器的ip,weight是调度算法
upstream www_pools {
server 192.168.178.121 weight=1;
server 192.168.178.122 weight=1;
}
2.修改server{}虚拟主机参数
server {
listen 80;
#本地测试用域名
server_name www.chaoge.com;
#charset koi8-r;
#access_log logs/host.access.log main;
#反向代理参数,转发请求给地址池
location / {
proxy_pass http://www_pools;
}
}
启动lb01负载均衡器
[root@lb01 nginx-1.16.0]# nginx -t
nginx: the configuration file /opt/nginx-1.16.0/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx-1.16.0/conf/nginx.conf test is successful
#如果出现如下错误,表明当nginx还未启动,找不到pid文件
[root@lb01 nginx-1.16.0]# nginx -s reload
nginx: [error] invalid PID number "" in "/opt/nginx-1.16.0/logs/nginx.pid"
#直接启动nginx即可
[root@lb01 nginx-1.16.0]# nginx
#检查负载均衡器
[root@lb01 nginx-1.16.0]# netstat -tunlp|grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 7500/nginx: master
配置hosts文件
[root@lb01 ~]# echo "192.168.178.126 www.chaoge.com bbs.chaoge.com" >> /etc/hosts
实测负载均衡效果
[root@lb01 nginx-1.16.0]# curl www.chaoge.com
chaoge_bbs_125
[root@lb01 nginx-1.16.0]# curl www.chaoge.com
chaoge_bbs_124
[root@lb01 nginx-1.16.0]# curl www.chaoge.com
chaoge_bbs_125
[root@lb01 nginx-1.16.0]# curl bbs.chaoge.com
chaoge_bbs_124
[root@lb01 nginx-1.16.0]# curl bbs.chaoge.com
chaoge_bbs_125
[root@lb01 nginx-1.16.0]# curl bbs.chaoge.com
chaoge_bbs_124
从测试结果中,可以看出,请求逐一的分给两个节点服务器了,实现了请求分发功能。
但是问题是,为何看到的网页内容,一直都是bbs的内容,而非出现www呢?
【图解答案】
#如何解决上述问题
其根本原因是,用户访问域名时候确实是www.chaoge.com,请求首先是发给了Nginx反向代理服务器
#问题是:
代理服务器(lb01)重新发起请求时,默认并没有在请求头里告诉节点服务器要找哪一个虚拟主机【www.chaoge.com】还是【bbs.chaoge.com】
因此后端节点服务器接收到请求之后,并没有主机头信息,默认把请求发给了第一个虚拟主机去处理(以web01的nginx.conf中的配置,也就是bbs站点内容了)
#解决办法:
在反向代理时候,添加主机头信息,明确告诉节点服务器找哪个虚拟主机
proxy_set_header Host $host;
在代理服务器向节点服务器发送HTTP请求头中添加host主机头信息后,若是后端服务器配置了多个虚拟主机,也就可以根据主机头的信息,来进行匹配决定发给哪一个虚拟主机【bbs还是www】。
#nginx.conf修改如下,修改location的配置
server {
listen 80;
server_name www.chaoge.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://www_pools;
# 添加该参数,在向后端发请求的时候,就会保留客户端的主机头信息,发给节点服务器
proxy_set_header Host $host;
}
}
#最终效果,结果和域名就完全对应上了
[root@lb01 ~]# curl www.chaoge.com
chaoge_www_124
[root@lb01 ~]# curl www.chaoge.com
chaoge_www_125
[root@lb01 ~]# curl www.chaoge.com
chaoge_www_124
[root@lb01 ~]# curl bbs.chaoge.com
chaoge_bbs_125
[root@lb01 ~]# curl bbs.chaoge.com
chaoge_bbs_124
[root@lb01 ~]# curl bbs.chaoge.com
chaoge_bbs_125