zl程序教程

您现在的位置是:首页 >  云平台

当前栏目

nginx通过四层代理实现端口转发

代理Nginx 实现 通过 端口 转发 四层
2023-09-14 09:15:46 时间

公司原有的测试数据库在主机192.168.10.5上边,现在数据库转移到了192.168.10.4上,为了不让各个地方都需要更改地址,现在需要一个四层代理工具,将原来请求到192.168.10.5的3306端口转发到192.168.10.4的3306端口。

这个工具,用到了 nginx 的四层代理。

官方文档:http://nginx.org/en/docs/stream/ngx_stream_core_module.html

四层代理依赖模块ngx_stream_core_module,该模块自 1.9.0 版开始可用。默认情况下,此模块不构建,应使用配置参数启用 --with-stream。

安装过程简示:

[root@linux-node1 src]# tar xf nginx-1.10.3.tar.gz 
[root@linux-node1 src]# cd nginx-1.10.3
[root@linux-node1 nginx-1.10.3]# useradd -s /sbin/nologin -M www
[root@linux-node1 nginx-1.10.3]# yum install gcc gcc-c++ zlib-devel pcre-devel openssl openssl-devel -y
[root@linux-node1 nginx-1.10.3]# ./configure --prefix=/usr/local/nginx-1.10.3 --user=www --group=www --with-http_ssl_module --with-http_stub_status_module --with-file-aio --with-stream
[root@linux-node1 nginx-1.10.3]# make && make install 

可以通过nginx -V查看一下是否将上述模块编译进来,如果没有,可以重新编译一下。

来到主配置:

worker_processes  1;
events {
    worker_connections  1024;
}
stream {  
        upstream tcp_proxy {
        hash $remote_addr consistent;  #远程地址做个hash
        server 192.168.10.4:22;
   }
      server {
        listen 2222;
        proxy_connect_timeout 1s;
        proxy_timeout 10s;  #后端连接超时时间
        proxy_pass tcp_proxy;
     }
  }

此配置是将本机的 2222 端口转发到 192.168.10.4 的 22 端口,配置之后,试验一下:

[root@7-3 nginx]$ssh -p 2222 root@192.168.10.5
The authenticity of host '[192.168.10.5]:2222 ([192.168.10.5]:2222)' can't be established.
ECDSA key fingerprint is 05:2f:63:e9:87:be:b4:44:d3:d7:77:a0:52:e0:4f:2f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[192.168.10.5]:2222' (ECDSA) to the list of known hosts.
root@192.168.10.5's password:
Last login: Wed Nov  7 15:24:33 2018 from 192.168.10.1
[root@7-2 ~]$hostname -I
192.168.10.4

刚刚设置了 10 的超时,如果需要的话,可以将之注释掉。

同理,配置数据库端口的转发也就非常简单了:

worker_processes  1;
events {
    worker_connections  1024;
}
stream {  
        upstream tcp_proxy {
        hash $remote_addr consistent;  #远程地址做个hash
        server 192.168.10.4:3306;
   }
      server {
        listen 3306;
        proxy_connect_timeout 1s;
       # proxy_timeout 10s;  #后端连接超时时间
        proxy_pass tcp_proxy;
     }
  }

这样一来,用户连接192.168.10.5:3306的时候,就会被转发到192.168.10.4:3306了。