四层负载均衡的特点
- 四层负载均衡仅能转发TCP/IP协议、UDP协议、通常用来转发端口,如:tcp/22、udp/53;
- 四层负载均衡可以用来解决七层负载均衡端口限制问题;(七层负载均衡最大使用65535个端口号)
- 四层负载均衡可以解决七层负载均衡高可用问题;(多台后端七层负载均衡能同时的使用)
- 四层的转发效率比七层的高得多,但仅支持tcp/ip协议,不支持http和https协议;
- 通常大并发场景通常会选择使用在七层负载前面增加四层负载均衡。
nginx部署
本次使用yum
安装的方式。
配置yum源
cat > nginx-upstream.repo << EOF
[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
EOF
## 清理缓存
yum clean all
## 生成缓存
yum makecache fast
安装nginx
yum install nginx -y
创建用户:
groupadd www -g 666 && useradd www -u 666 -g 666 -s /sbin/nologin -M
配置nginx:
vim /etc/nginx/nginx.conf
user www;
启动nginx:
systemctl start nginx && systemctl enable nginx && systemctl status nginx
配置四层代理
首先,配置nginx主配置文件:
vim /etc/nginx/nginx.conf
#注释http层所有内容
user www;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
#添加一个包含文件
include /etc/nginx/conf.c/*.conf;
#http {
# include /etc/nginx/mime.types;
# default_type application/octet-stream;
# log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
# access_log /var/log/nginx/access.log main;
# sendfile on;
# #tcp_nopush on;
# keepalive_timeout 65;
# #gzip on;
# include /etc/nginx/conf.d/*.conf;
#}
配置四层负载均衡,这里提供一个示例:
# cat veos-baidu-mongo.conf
# TCP MongoDB
stream {
server {
listen 23000;
proxy_pass veos-baidu-mongocluster;
proxy_connect_timeout 60s;
proxy_timeout 60m;
}
upstream veos-baidu-mongocluster {
server 10.x.x.x:23000 max_fails=3 fail_timeout=10;
server 10.x.x.x:23000 max_fails=3 fail_timeout=10;
server 10.x.x.x:23000 max_fails=3 fail_timeout=10;
}
}
平滑重启nginx:
nginx -t
nginx -s reload