时间:2022-03-14 10:04:55 | 栏目:Nginx | 点击:次
我们都知道 nginx 是一款优秀的反向代理服务,用过 nginx 的也应该都知道 upstream,upstream 节点一般置于 http 节点大括号中,常规在 upstream 中配置需要被负载均衡的服务器列表。
比较多的使用做如下示意:
#user nobody nobody。
#worker_processes 2;
#pid /nginx/pid/nginx.pid;
error_log log/error.log debug;
events {
……
}
http {
……
upstream testserver {
server 192.168.1.5:8080;
server 192.168.1.6:8080;
……
}
server {
……
location / {
……
proxy_pass http://testserver;
}
}
}
从结构可以看出,这种用的比较多的配置,主要是应对 http 反向代理的。
但是如果我们想对后端服务的 TCP 进行代理,nginx 支持吗?比如 mysql、redis 等,答案是肯定的,其实 nginx 也是支持对 TCP/UDP 进行负载均衡的,下面要说到的就是 nginx 的 stream 模块,通过配置 stream 可以实现这样的需求,这里还是更多的推荐主要将 nginx 用于 http 反向代理。
Nginx 的 TCP/UDP 负载均衡是应用 Stream 代理模块(ngx_stream_proxy_module)和 Stream 上游模块(ngx_stream_upstream_module)实现的。Nginx 的 TCP 负载均衡与 LVS 都是四层负载均衡的应用,所不同的是,LVS 是被置于 Linux 内核中的,而 Nginx 是运行于用户层的,基于 Nginx 的 TCP 负载可以实现更灵活的用户访问管理和控制。
基本概念科普完了,下面来看一下具体的配置示例:
worker_processes 4;
worker_rlimit_nofile 40000;
events {
worker_connections 8192;
}
stream {
upstream my_servers {
least_conn;
# 5s内出现3次错误,该服务器将被熔断5s
server <IP_SERVER_1>:3306 max_fails=3 fail_timeout=5s;
server <IP_SERVER_2>:3306 max_fails=3 fail_timeout=5s;
server <IP_SERVER_3>:3306 max_fails=3 fail_timeout=5s;
}
server {
listen 3306;
proxy_connect_timeout 5s; # 与被代理服务器建立连接的超时时间为5s
proxy_timeout 10s; # 获取被代理服务器的响应最大超时时间为10s
proxy_next_upstream on; # 当被代理的服务器返回错误或超时时,将未返回响应的客户端连接请求传递给upstream中的下一个服务器
proxy_next_upstream_tries 3; # 转发尝试请求最多3次
proxy_next_upstream_timeout 10s; # 总尝试超时时间为10s
proxy_socket_keepalive on; # 开启SO_KEEPALIVE选项进行心跳检测
proxy_pass my_servers;
}
}
注:如果你配置 steam 模块无效,请检查一下你使用的版本是否支持 stream,如果未内置该模块,你需要在编译的时候指定参数 --with-stream 进行编译使其支持stream代理。