1.Nginx四层负载均衡原理
Nginx四层负载均衡就是实现通过访问某个ip的端口转发至对应的服务器上,如图当访问10.0.0.5的5555端口就会跳转至web服务器172.1.16.7的22号端口,当访问10.0.0.5的6666端口就会转发到mysql服务器的3306端口,高效的保护了内网的安全。
为什么企业不再使用lvs而选择使用Nginx做负载
1.Nginx既支持四层又支持七层
2.很多企业使用云平台,但是云平台网络环境不支持lvs
3.都是用Nginx方便统一管理
2.Nginx四层负载均衡配置
一般做四层负载均衡的都是一对一的连接,比如ssh、mysql,明确需要登录某台主机的某个端口来做操作,可以实现一个跳板机
注意:四层负载均衡配置stream只能配置一个,也就是说关于四层负载的配置文件只允许有一个
2.1.四层负载均衡语法
stream { upstream name { //定义虚拟资源池 server ip:port; } server { //调用虚拟资源池 listen port; proxy_pass name; //由于是四层负载所以不用加http:// } }
2.2.实例
配置四层负载,实现访问192.168.810.210的6666端口就会访问到172.16.1.20的22号端口
[root@localhost nginx]# mkdir conf.c 在nginx.conf文件中写入这两行,主要要写在events下面http上面,stream与http同级 [root@localhost nginx]# vim nginx.conf #四层负载 include /etc/nginx/conf.c/*.conf; [root@localhost conf.c]# vim ssh.conf stream { upstream lb_ssh_20 { server 172.16.1.20:22; } upstream lb_ssh_30 { server 172.16.1.30:22; } upstream lb_ssh_40 { server 172.16.1.40:22; } server { listen 6666; proxy_pass lb_ssh_20; } server { listen 7777; proxy_pass lb_ssh_30; } server { listen 8888; proxy_pass lb_ssh_40; } } [root@localhost conf.c]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@localhost conf.c]# systemctl reload nginx
效果:
666端口7777端口3.Nginx负载均衡TCP实战
需求概述
1.通过访问负载均衡的6666端口,实际是后端的web01的22端口在提供服务。
2.通过访问负载均衡的7777端口,实际是后端的web02的22端口在提供服务。
3.通过访问负载均衡的8888端口,实际是后端的web03的22端口在提供服务。
2.通过访问负载均衡的9999端口,实际是后端的mysql的3306端口在提供服务。
3.1.四层负载均衡配置
[root@localhost conf.c]# vim ssh_mysql.conf stream { upstream ssh_20 { //定义web01的ssh连接池 server 172.16.1.20:22; } upstream ssh_30 { //定义web02的ssh连接池 server 172.16.1.30:22; } upstream ssh_40 { //定义web03的ssh连接池 server 172.16.1.40:22; } upstream mysql_20 { //定义mysql的ssh连接池 server 172.16.1.20:3306; } server { listen 6666; proxy_pass ssh_20; proxy_timeout 60s; proxy_connect_timeout 30s; } server { listen 7777; proxy_pass ssh_30; proxy_timeout 60s; proxy_connect_timeout 30s; } server { listen 8888; proxy_pass ssh_30; proxy_timeout 60s; proxy_connect_timeout 30s; } server { listen 9999; proxy_pass mysql_20; proxy_timeout 60s; proxy_connect_timeout 30s; } } [root@localhost conf.c]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@localhost conf.c]# systemctl reload nginx
3.2.效果
- 1.通过访问负载均衡的6666端口,实际是后端的web01的22端口在提供服务。2.通过访问负载均衡的7777端口,实际是后端的web02的22端口在提供服务。
- 3.通过访问负载均衡的8888端口,实际是后端的web03的22端口在提供服务。
- 4.通过访问负载均衡的9999端口,实际是后端的mysql的3306端口在提供服务。