文章目录

  • 引言
  • 1 查看Nginx版本
  • 1.1 打开终端
  • 1.2 查看版本信息
  • 2 配置Nginx的TCP代理
  • 2.1 修改主配置文件,添加stream目录
  • 2.2 添加TCP转发配置
  • 2.3 检查配置文件
  • 2.4 重启Nginx服务
  • 3 客户端测试
  • END


引言

自从Nginx 1.9 以后无需其他软件配合,通过stream模块就可以实现了TCP代理功能,即可通过访问该服务器的指定端口,Nginx就可以充当端口转发的作用将请求该端口的所有流量都会转发到目标服务器,同时获取目标服务器的返回数据并返回给请求者。以下基于已安装Nginx的状态下配置Nginx实现代理TCP的功能。若有小伙伴还没安装Nginx,网上有很多教程,本文不对此进行阐述。

1 查看Nginx版本

1.1 打开终端

Ctrl+Alt+T打开终端

nginx 支持tcp转发 nginx配置tcp转发_linux

1.2 查看版本信息

查看版本信息,检查是否编译时带with-stream参数

终端输入:sudo nginx -V |grep with-stream

我的版本是1.14.2,有with-stream参数,可以代理TCP协议

nginx 支持tcp转发 nginx配置tcp转发_网络_02

2 配置Nginx的TCP代理

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

  1. 进入Nginx文件目录
pi@raspberrypi:~ $ cd /etc/nginx/
  1. 备份一份nginx.conf
pi@raspberrypi:/etc/nginx $ sudo cp -a nginx.conf{,_$(date +%F)}
  1. 编辑nginx.conf
pi@raspberrypi:/etc/nginx $ sudo nano nginx.conf
  1. 在打开的nginx.conf底部添加如下内容:
include /etc/nginx/tcp.d/*.conf;

nginx 支持tcp转发 nginx配置tcp转发_nginx 支持tcp转发_03

  1. Ctrl + O Enter 保存
  2. Ctrl + X 退出

2.2 添加TCP转发配置

  1. 创建tcp.d目录
pi@raspberrypi:/etc/nginx $ sudo mkdir tcp.d
  1. 进入tcp.d目录
pi@raspberrypi:/etc/nginx $ cd tcp.d
  1. 创建conf文件
pi@raspberrypi:/etc/nginx/tcp.d $ sudo nano openldap.conf
  1. 输入如下内容:
  • 注:(以下内容以目标服务器IP地址为8.8.8.8 端口号为 389为例,运用时记得修改为自己的IP和端口)
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”:提供转发的服务,即监听端口为3389,访问localhost:3389,会跳转至代理"tcpssh"指定的转发地址。
即会将流量相应转发到8.8.8.8服务器的389端口上。

2.3 检查配置文件

pi@raspberrypi:/etc/nginx/tcp.d $ sudo nginx -t -c /etc/nginx/nginx.conf

nginx 支持tcp转发 nginx配置tcp转发_debian_04

2.4 重启Nginx服务

  1. 重启Nginx服务
pi@raspberrypi:/etc/nginx/tcp.d $ sudo nginx -s reload
  1. 查看Nginx是否启动
pi@raspberrypi:/etc/nginx/tcp.d $ systemctl status nginx.service

nginx 支持tcp转发 nginx配置tcp转发_linux_05

  1. 查看3389端口是否在监听
pi@raspberrypi:~ $ sudo netstat nap |grep 3389

nginx 支持tcp转发 nginx配置tcp转发_网络_06

3 客户端测试

我用的是虚拟机上的Ubuntu

  1. Ctrl+Alt+T打开终端
  2. 在终端输入
telnet 192.168.1.101 3389

注意:
192.168.1.101:为服务器主机IP要根据自己的服务器IP地址确定
- 可通过在终端输入 ifconfig 查看
- 找到
wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.101 netmask 255.255.255.0 broadcast …
以上IP地址为192.168.1.101
3389:就是上面设置的监听端口3389

在终端输入 telnet 192.168.1.101 3389后显示:

china@ubuntu:~$  telnet 192.168.1.101 3389
Trying 192.168.1.101 3389...
Connected to 192.168.1.101.
Escape character is '^]'.

出现Connected to 192.168.1.101.则说明连接成功

至此配置完成。

END

如果出现

telnet: Unable to connect to remote host: Network is unreachable

nginx 支持tcp转发 nginx配置tcp转发_debian_07


那就是虚拟机没网,可以参考我的这篇文章 VMware虚拟机上Ubuntu无网络解决方法 进行配置后再次尝试。

参考文章https://blog.51cto.com/moerjinrong/2287680