Nginx 配置TCP代理

Nginx 配置TCP代理

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代理

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

stream不属于http模块内的,需要配置在http 括号外层

[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_proxy.d/*.conf;

2.2 添加tcp转发配置

[root@node1 ~]# mkdir tcp_proxy.d
[root@node1 ~]# cd tcp_proxy.d

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

[root@node1 ~]# vim openldap.conf
stream{
    upstream testssh{
        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 testssh;
    }
}

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

测试配置文件是否正确

[root@node1 ~]# nginx -t -c /etc/nginx/nginx.conf
[root@node1 ~]# nginx -t -c /etc/nginx/tcp_proxy.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 2018-09-29 11:34:01 CST; 5h 37min ago
     Docs: http://nginx.org/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

猜你喜欢

转载自blog.51cto.com/moerjinrong/2287680