Nginx功能很多,性能也非常优秀,尤其在负载均衡上,但大家常见的只用到了7层负载。
从nginx1.9.0版本以后,加入了四层负载均衡模块,相对于LVS来说,可以减少对Virtual IP、Real IP的设置,部署起来更简洁高效,维护也相对简单。
这里介绍一下使用nginx的stream模块进行反向代理
负载均衡Nginx服务搭建流程
软件安装(一定要下载1.9.0以后的nginx版本,否则不支持4层负载均衡):
yum install nginx-1.20.1-1.el7.ngx.x86_64 net-tools -y
/etc/nginx.nginx.conf配置:
user nginx;
worker_processes auto;
worker_rlimit_nofile 20480; #增大最大连接数
pid /var/run/nginx.pid;
events {
worker_connections 9216; #默认为1024,但请求过多会出现worker_connections are not enough while connecting to upstream报错
}
include /etc/nginx/conf.d/*.conf; #加载/etc/nginx/conf.d/下面所有的.conf结尾的配置文件在/etc/nginx/conf.d/目录中删除default.conf,并创建load_balance.conf,仅需配置此文件即可:
stream { #设置stream
log_format proxy '$remote_addr [$time_local] ' #以下四行为日志格式
'$protocol $status $bytes_sent $bytes_received '
'$session_time "$upstream_addr" '
'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
access_log /var/log/nginx/tcp-access.log proxy; #访问代理日志
error_log /var/log/nginx/error.log warn; #错误日志
open_log_file_cache off;
upstream cluster1 { #设置后端需要负载均衡的服务器
hash $remote_addr; #IP哈希算法
server 192.168.1.31:8080 max_fails=1 fail_timeout=20s; #在20s内连接失败一次后,在集群中剔除此主机,20秒后主机重新加入集群
server 192.168.1.32:8080 max_fails=1 fail_timeout=20s;
;
}
upstream cluster2 {
hash $remote_addr;
server 192.168.1.33:8081 max_fails=1 fail_timeout=20s;
server 192.168.1.34:8081 max_fails=1 fail_timeout=20s;
}
#cluster1
server {
listen 8080; #负载均衡监听端口
proxy_connect_timeout 1s; #与被代理服务器建立连接的超时时间为1s
proxy_timeout 2s; #获取被代理服务器的响应最大超时时间为2s
proxy_next_upstream on; #当被代理的服务器返回错误或超时时,将未返回响应的客户端连接请求传递给upstream中的下一个服务器
proxy_next_upstream_tries 3; #转发尝试请求最多3次
proxy_next_upstream_timeout 2s; #总尝试超时时间为2s
proxy_socket_keepalive on; #开启SO_KEEPALIVE选项进行心跳检测
proxy_pass cluster1; #代理服务器集群
}
#cluster2
server {
listen 8081;
proxy_connect_timeout 1s;
proxy_timeout 2s;
proxy_next_upstream on;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 2s;
proxy_socket_keepalive on;
proxy_pass cluster2;
}
}配置完成后,检查nginx配置文件是否正确,并设置开机启动:
nginx -t #nginx配置检查 systemctl enable nginx systemctl start nginx


网友留言: