暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Nginx stream 模块实现端口转发

生有可恋 2024-01-23
1876

Nginx 的 stream 模块可用于处理四层(传输层)的代理功能,允许你在 TCP 和 UDP 层上进行代理。这个模块可以用于实现端口转发、TCP/UDP 负载均衡等场景。

以下是一个完整的 Nginx 配置文件,用于演示如何配置端口转发:

    user www-data;
    worker_processes auto;
    pid run/nginx.pid;


    events {
    worker_connections 768;
    }


    stream {


    server {
    listen 7890 so_keepalive=on;
    proxy_pass 192.168.1.1:7890;
    }


    server {
    listen 7891 so_keepalive=on;
            proxy_pass 192.168.1.2:7890;
    }


    server {
    listen 7892 so_keepalive=on;
            proxy_pass 192.168.1.3:7890;
    }
    }


    使用 nginx 命令检查配置文件是否正确:

      $ nginx -t -c root/nginx/nginx.conf
      nginx: the configuration file root/nginx/nginx.conf syntax is ok
      nginx: configuration file root/nginx/nginx.conf test is successful

      启动 Nginx 服务:

        $ nginx -c root/nginx/nginx.conf

        检查代理的端口是否处于监听状态:

          $ netstat -lntp| grep nginx
          tcp 0 0 0.0.0.0:7890 0.0.0.0:* LISTEN 76767/nginx.conf
          tcp 0 0 0.0.0.0:7891 0.0.0.0:* LISTEN 76767/nginx.conf
          tcp 0 0 0.0.0.0:7892 0.0.0.0:* LISTEN 76767/nginx.conf

          除了代理 TCP 端口,Nginx 也可以代理 UDP 端口:

            stream {
            # TCP 配置


            server {
            listen 12345; # 监听的源端口
            proxy_pass backend_server:5678; # 转发到目标服务器的端口
            }


            # UDP 配置


            server {
            listen 53 udp; # UDP 端口监听
            proxy_pass backend_dns:53; # 转发到目标 DNS 服务器的端口
            }
            }

            除了可以转发单个后端端口,也可以配置多个后端服务器,实现负载均衡。示例:

              stream {
              upstream backend_servers {
                      server backend_svr1:5678;
                      server backend_svr2:5678;
                      server backend_svr3:5678;
              }


              server {
              listen 12345;
              proxy_pass backend_servers;
              }
              }


              参考

                https://nginx.org/en/docs/stream/ngx_stream_core_module.html
                https://github.com/dunwu/nginx-tutorial

                全文完。

                如果转发本文,文末务必注明:“转自微信公众号:生有可恋”。

                文章转载自生有可恋,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                评论