1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > nginx tcp端口转发_使用Nginx进行TCP/UDP端口转发

nginx tcp端口转发_使用Nginx进行TCP/UDP端口转发

时间:2020-08-27 23:00:39

相关推荐

nginx tcp端口转发_使用Nginx进行TCP/UDP端口转发

Nginx 配置TCP/UDP端口转发

nginx 的功能非常强大,其中作为代理服务器是非常常用的功能,但是之前的nginx代理只能做七层代理,也就说是基于应用层面的代理,TCP层面的代理一般会配合haproxy 来使用。但是自从nginx 1.9 以后通过stream模块实现了tcp 代理功能,无需其他软件配合即可实现四层代理和七层代理,即:访问该服务器的指定端口,nginx就可以充当端口转发的作用将流量导向另一个服务器,同时获取目标服务器的返回数据并返回给请求者。nginx的TCP代理功能跟nginx的反向代理不同的是:请求该端口的所有流量都会转发到目标服务器,而在反向代理中可以细化哪些请求分发给哪些服务器;另一个不同的是,nginx做TCP代理并不仅仅局限于WEB的URL请求,还可以转发如memcached、MySQL等点到点的请求

环境

ip

主机名

端口

说明

192.168.1.101

node1

3389

nginx服务器

192.168.1.102

node2

~

客户端

8.8.8.8

~

389

目标服务器

1.安装nginx服务

1.1 安装nginx

默认安装stream模块,我写文档时nginx版本为1.14.0

参考:RHEL/CentOS 安装 nginx

1.2 对于已经安装nginx的,检查是否编译时带with-stream参数

[root@node1 ~]# nginx -V |grep with-stream

有with-stream参数,可以代理tcp协议

2 配置nginx的tcp代理

请注意,stream块和http块是两个不同的模块,stream不属于http模块,即不能放到/etc/nginx/conf.d/,stream是通过tcp层转发,而不是http转发。

如配置在http内,启动nginx会报如下错误:

nginx: [emerg] "server" directive is not allowed here

2.1 修改主配置文件,添加stream目录

[root@node1 ~]# cd /etc/nginx/

[root@node1 ~]# cp -a nginx.conf{,_$(date +%F)}

[root@node1 ~]# vim nginx.conf

# 最后追加如下内容

# tcp/ip proxy

include /etc/nginx/tcp.d/*.conf;

2.2 添加tcp转发配置

[root@node1 ~]# mkdir tcp.d

[root@node1 ~]# cd tcp.d

在新建的 tcp.d 目录下创建 conf 文件新建一个 tcp 配置,例如我转发到IP为8.8.8.8的389端口

[root@node1 ~]# vim openldap.conf

stream{

upstream tcpssh{

hash $remote_addr consistent;

server 8.8.8.8:389 max_fails=3 fail_timeout=10s;

}

server{

listen 3389;

proxy_connect_timeout 20s;

proxy_timeout 5m;

proxy_pass tcpssh;

}

}

说明:

"upstream tcpssh":转发的目的地址和端口等设置;其中tcpssh为自定义;

"server":提供转发的服务,即访问localhost:3389,会跳转至代理"tcpssh"指定的转发地址.。

这里就是配置的监听本地3389端口,会将流量相应转发到8.8.8.8服务器的389端口上。

测试配置文件是否正确

[root@node1 ~]# nginx -t -c /etc/nginx/nginx.conf

[root@node1 ~]# nginx -t -c /etc/nginx/tcp.d/openldap.conf

2.3 启动nginx服务

启动nginx服务

[root@node1 ~]# systemctl start nginx.service

查看是否启动

[root@node1 ~]# systemctl status nginx.service

● nginx.service - nginx - high performance web server

Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)

Active: active (running) since Sat -09-29 11:34:01 CST; 5h 37min ago

Docs: /en/docs/

Main PID: 26114 (nginx)

CGroup: /system.slice/nginx.service

├─26114 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf

└─26115 nginx: worker process

Sep 29 11:34:01 node1 systemd[1]: Starting nginx - high performance web server...

Sep 29 11:34:01 node1 systemd[1]: Started nginx - high performance web server.

[root@node1 ~]#

3 客户端配置

3.1 测试连接目标端口:

[root@node2 ~]# telnet 192.168.1.101 3389

Trying 192.168.1.101...

Connected to 192.168.1.101.

Escape character is '^]'.

出现"Connected to 192.168.1.101",说明连接成功

测试完成,"Ctrl+C"结束

3.2 相关业务软件配置

把要连接8.8.8.8:389的配置改为nginx服务器ip(192.168.1.101),及代理端口3389。

如果业务没有出现问题的话,则说明已经配置完成了

END

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。