[toc]

四层负载均衡概述

什么是四层负载均衡

OSI七层网络模型中,四层是传输层,传输层就是端口到端口的通信方式;

四层负载均衡:及时在传输层做端口的转发(端口映射)

四层负载应用场景

  1. 四层负载均衡仅能转发TCP/IP协议、UDP协议、通常用来转发端口,如:TCP/SSH:22、UDP/53;
  2. 四层负载均衡可以用来解决七层负载均衡端口限制问题;(七层负载均衡最大使用65535个端口号) ????
  3. 四层负载均衡可以解决七层负载均衡高可用问题;(多台后端七层负载均衡能同时的使用)
  4. 四层的转发效率比七层的高得多,但仅支持TCP/IP协议,不支持http和https协议;
  5. 大并发场景通常会选择使用在七层负载前面增加四层负载均衡。
1
2
3
4
# 四层+七层来做负载均衡,四层可以保证七层负载的高可用;
# nginx就无法保证自己服务的高可用,需要依赖LVS或者keepalive;
# 比如tcp的负载均衡,有些请求是TCP协议(mysql ssh);
# 一些请求只需要使用四层负载均衡进行端口的转发,我们会使用四层负载均衡

image-20230616210050479

支持四层均衡和七层均衡的应用

nginx

  • 四层负载均衡(nginx1.9版本之后才有stream模块,才可以做四层)
    • stream
  • 七层负载均衡
    • upstream

LVS

  • 四层负载均衡

HAproxy

  • 四层负载均衡
  • 七层负载均衡

部署四层负载均衡

环境准备

主机名 WanIP LanIP 角色 应用
lb01 10.0.0.5 172.16.1.5 七层负载均衡 nginx
lb02 10.0.0.6 172.16.1.6 四层负载均衡 nginx
web01 10.0.0.7 172.16.1.7 web网站 nginx php
web02 10.0.0.8 172.16.1.8 web网站 nginx php
db01 10.0.0.51 172.16.1.51 数据库 mariadb

部署四层负载(lb02)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 在web01 web02部署wordpress网页

# 在db01部署远端mariadb数据库

# 在lb01部署七层负载均衡,服务器池为web01 web02

# 在lb02部署四层负载均衡

# 添加nginx源
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

# 安装nginx
yum install -y nginx

# 四层负载
vim /etc/nginx/nginx.conf

stream {
upstream backend {
server 172.16.1.5:80;
}

server {
listen 90;
proxy_pass backend;
}
}

http {
.....
.........
}

image-20230108143512101

nginx四层负载实现端口转发

在10.0.0.6起789 映射到10.0.0.8的22端口(lb02)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 创建stream.d目录
vim /etc/nginx/stream.d

# 主配置文件添加include
vim /etc/nginx/nginx.conf

user nginx;
worker_processes auto;

error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;

events {
worker_connections 1024;
}

include /etc/nginx/stream.d/*.conf; # 添加这一行-nginx配置文件指向目录

# 实现789映射到22端口的需求
## 可以随意添加但stream只能存在一个
vim /etc/nginx/stream.d/789_22.conf

stream {
upstream web02_ssh {
server 172.16.1.8:22;
}
server {
listen 789;
proxy_pass web02_ssh; # 使用789端口映射172.16.1.8:22
}
upstream backend {
server 172.16.1.5:80;
}
server {
listen 90;
proxy_pass backend; # 使用90端口映射172.16.1.5:80
}
}

# 重启nginx
systemctl restart nginx

# 虚拟机连接