第一节:基础知识
1.反向代理常用设备
- 硬件:F5
- 软件:Nginx HAproxy
2.需要掌握的基本概念
- 问题一:为什么需要用反向代理
- 问题二:反向代理都有哪些软件或硬件
- 问题三:Nginx反向代理是什么模块
- 问题四:什么是负载均衡
- 问题五:反向代理和负载均衡解决了什么问题?
- 问题六:怎么配置nginx反向代理
- 问题七:怎么配置nginx负载均衡
第二节: Nginx反向代理参数解释
官方案例:
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
解释:
proxy_pass http://172.16.1.7:8080; #将用户的请求转发给后端的nginx服务器处理
proxy_set_header Host $host; #将用户访问的地址记录到自己的HOST记录上
proxy_set_header X-Real-IP $remote_addr; #将用户访问的IP记录到自己的IP地段上
常用的代理配置参数:
proxy_set_header Host $http_host; #将用户访问的地址记录到自己的HOST记录上
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #将用户访问IP记录到自己的X-Forwarded-For地段上
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
第三节:Nginx反向代理配置
需求:
lb服务器的80端口,跳转到web01服务器上的 8080端口
web服务器操作:
1.配置nginx文件
[root@web01 ~]# cat /etc/nginx/conf.d/web01.conf
server {
listen 8080;
server_name www.mysun.com;
location / {
root /code;
index www.html;
}
}
2.写入测试页面
echo "web01" > /code/www.html
3.检查并重启Nginx
nginx -t
systemctl restart nginx
lb服务器:
1.安装NGINX
yum -y install nginx
2.编写代理需要的参数配置文件
[root@lb01 ~]# cat /etc/nginx/proxy_params
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
3.编写代理服务配置文件
[root@lb01 ~]# cat /etc/nginx/conf.d/proxy.conf
server {
listen 80;
server_name www.mysun.com;
location / {
proxy_pass http://172.16.1.7:8080;
include proxy_params;
}
}
4.检查并启动Nginx
nginx -t
systemctl start nginx
5.windos操作:
绑定hosts文件打开网页测试
10.0.0.5 www.mysun.com
第三节:反向代理结合负载均衡配置
1.负载均衡图解
2.地址规划
web01 | www.mysun.com | blog.mysun.com | bbs.mysun.com |
---|---|---|---|
web02 | www.mysun.com | blog.mysun.com | bbs.mysun.com |
lb01 | www.mysun.com | blog.mysun.com | bbs.mysun.com |
3.配置web服务器
cat >/etc/nginx/conf.d/www.conf <<EOF
server {
listen 80;
server_name www.mysun.com;
location / {
root /code;
index www.html;
}
}
EOF
cat >/etc/nginx/conf.d/bbs.conf <<EOF
server {
listen 80;
server_name bbs.mysun.com;
location / {
root /code;
index bbs.html;
}
}
EOF
cat >/etc/nginx/conf.d/blog.conf <<EOF
server {
listen 80;
server_name blog.mysun.com;
location / {
root /code;
index blog.html;
}
}
EOF
echo "$(hostname) bbs" > /code/bbs.html
echo "$(hostname) www" > /code/www.html
echo "$(hostname) blog" > /code/blog.html
4.重启nginx
nginx -t
systemctl restart nginx
5.配置lb服务器
[root@lb01 ~]# cat /etc/nginx/conf.d/proxy.conf
upstream web_pools {
server 172.16.1.7;
server 172.16.1.8;
}
server {
listen 80;
server_name www.mysun.com bbs.mysun.com blog.mysun.com;
location / {
proxy_pass http://web_pools;
include proxy_params;
}
}
6.重启nginx
nginx -t
systemctl restart nginx
7.windows操作:
绑定本地hosts文件:
10.0.0.5 www.mysun.com bbs.mysun.com blog.mysun.com