nginx四层负载均衡代理七层负载均衡流程

一,四层负载均衡语法

语法: stream { ... } 默认:— 位置:main #示例:四层负载均衡stream模块跟http模块在同一级别,不能配置在http里面 stream { upstream backend { server backend1.example.com:12345 weight=5; server 127.0.0.1:12345max_fails=3 fail_timeout=30s; } server { listen 12345; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass backend; } }

二,四层负载均衡实践

1,服务器准备

主机ip身份lb01192.168.15.5七层负载均衡lb02192.168.15.6四层负载均衡web01192.168.15.7web服务器web02192.168.15.8web服务器web03192.168.15.9web服务器db01192.168.15.51数据库

2,四层负载均衡服务器安装:lb02(只能用官方源安装Nginx,注:epel源安装的Nginx无法使用四层负载均衡 因为epel源安装的Nginx中没有--with-srearm 参数)

1.)配置官方源(所有的配置必须顶格写)

[root@lb02 ~]# vim /etc/yum.repos.d/nginx.repo

输入下面内容:

[nginx-stable] name=nginx stable repo baseurl= gpgcheck=1 enabled=1 gpgkey= module_hotfixes=true [nginx-mainline] name=nginx mainline repo baseurl= gpgcheck=1 enabled=0 gpgkey= module_hotfixes=true

2.)如果安装官方源,epel源必须注释掉(避免epel源影响)

[root@lb02 ~]# cd /etc/yum.repos.d/ [root@lb02 yum.repos.d]# gzip epel.repo

3.)yum清空缓存

[root@lb02 ~]# yum clean all [root@lb02 ~]# yum makecache

4.)安装nginx

[root@lb02 ~]# yum install nginx -y

5.)测试是否安装成功

nginx -v

6.)查看nginx配置文件

rpm -qc nginx

7.)启动nginx

systemctl start nginx

3,web服务器配置(3台web服务器配置文件的配置一样)

1)web01

2) web02

3)web03

部署完毕后全部启动nginx

systemctl start nginx

4,lb01(七层负载均衡服务器配置文件部署)

5,lb02(七层负载均衡服务器配置文件部署)

1)修改配置文件

vi/etc/nginx/nginx.conf

usernginx; worker_processesauto; error_log/var/log/nginx/error.log notice; pid/var/run/nginx.pid; events { worker_connections1024; } stream { include /etc/nginx/stream.conf/*.conf; }

2)新增配置

[root@lb02 ~]# mkdir /etc/nginx/stream.conf [root@lb02 ~]# cd /etc/nginx/stream.conf

vi nginx.conf

upstream nginx { server 172.16.1.5:80; } server { listen 80; proxy_pass nginx; }

3)启动nginx并测试

systemctl restart nginx

6,修改Windows的hosts文件并测试

案例一:实现SSH代理端口

要求使用192.168.15.6的1234端口链接192.168.15.5的22端口

lb02配置:

1.新增配置文件

[root@lb02 stream.conf]# cd /etc/nginx/stream.conf

vi ssh.conf

upstream ssh { server 172.16.1.5:22; } server { listen 1234; proxy_pass ssh; }

2.重启nginx

systemctl restart nginx

3.测试

[root@lb02 stream.conf]# ssh 192.168.15.6 -p 1234

案例二:实现代理MySQL服务

要求使用192.168.15.6的33060端口代理192.168.15.51的3306端口

开启db01数据库服务器:

systemctl start mariadb

lb02配置:

1.新增配置文件

[root@lb02 stream.conf]# cd /etc/nginx/stream.conf

vi mysql.conf

upstream mysql { server 172.16.1.51:3306; } server { listen 33060; proxy_pass mysql; }

2.重启nginx

systemctl restart nginx

3.测试

[root@db01 ~]#mysql -uroot -p -h192.168.15.6 -P33060