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

公司原有的测试数据库在主机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了。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CN-FuWei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值