博客 > 术业专攻> 阿里云方面> 一些实操> nginx通过四层代理实现端口转发 2019年08月29日 11:25:13
公司原有的测试数据库在主机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
了。
本文参考地址:https://www.cnblogs.com/w787815/p/6682824.html
© 2018 www.qingketang.net 鄂ICP备18027844号-1
武汉快勤科技有限公司 13554402156 武汉市东湖新技术开发区关山二路特一号国际企业中心6幢4层7号
扫码关注,全站教程免费播放
订单金额:
支付金额:
支付方式: