Nginx-反向代理

功能模块:

ngx_http_upstream_module --- upstream 负载均衡
ngx_http_proxy_module    --- proxy_pass 反向代理

反向代理:proxy_pass模块,将接收到的请求抛给后面的反向代理服务器,由它
去寻找目标服务器获取数据。

负载均衡:upstream模块,根据配置的权重大小将请求分发给不同服务器不同
数量的请求。

环境准备:

lb01 10.0.0.5
lb02 10.0.0.56
web01 10.0.0.7
web02 10.0.0.8

安装nginx软件

yum -y install nginx

编写nginx服务配置文件

官网案例:

模块:ngx_http_upstream_module

Example:
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;
	}
}
vim /etc/nginx/conf.d/lb.conf

upstream test {
server 10.0.0.7:80;
server 10.0.0.8:80;
server 10.0.0.9:80;
}
server {
	listen		80;
	server_name	www.test.com;
	location / {
		proxy_pass http://test;
	}
}
#客户端用www.test.com去访问时,反向代理服务器就会将它变成test去寻找后端web服务器获取数据

实现负载功能测试

搭建集群测试环境:

for name in www bbs blog;do echo "$name 10.0.0.7">/html/$name/test.html;done

for name in www bbs blog;do echo "$name 10.0.0.8">/html/$name/test.html;done

for name in www bbs blog;do echo "$name 10.0.0.9">/html/$name/test.html;done

修改windows解析文件

10.0.0.5	www.test.com bbs.test.com blog.test.com

效果

[root@lb02 ~]# curl www.test.com
10.0.0.7 www.test.com
[root@lb02 ~]# curl www.test.com
10.0.0.8 www.test.com
[root@lb02 ~]# curl www.test.com
10.0.0.9 www.test.com
[root@lb02 ~]# curl www.test.com
10.0.0.7 www.test.com
[root@lb02 ~]# curl www.test.com
10.0.0.8 www.test.com
[root@lb02 ~]# curl www.test.com
10.0.0.9 www.test.com
#lb01主机将请求平均的分配各个web主机,从而达到负载均衡

其他例子:

1.访问不同的网站地址,不能显示不同的网站页面
模块:proxy_set_header Host $host;

2.访问网站用户地址信息无法进行分析统计
模块:proxy_set_header X-Forwarded-For $remote_addr;

3.访问负载均衡会出现错误页面,影响用户体验
模块:proxy_next_upstream error timeout http_404 http_502 http_403;

posted @ 2021-08-30 13:52  Cai_HL  阅读(39)  评论(0编辑  收藏  举报
>