使用Nginx转发TCP/UDP数据

编译安装Nginx

从1.9.0开始,nginx就支持对TCP的转发,而到了1.9.13时,UDP转发也支持了。提供此功能的模块为ngx_stream_core。不过Nginx默认没有开启此模块,所以需要手动安装

cd /usr/local/src
wget http://nginx.org/download/nginx-1.12.1.tar.gz
tar zxf nginx-1.12.1.tar.gz
cd nginx-1.12.1
./configure --prefix=/usr/local/nginx --with-stream
make && make install

配置Nginx

TCP转发

目标:通过3000端口访问本机Mysql(其中mysql使用yum安装,默认配置文件)

/usr/local/nginx/conf/nginx.conf配置如下:

user nobody;
worker_processes auto;
 
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
 
#pid logs/nginx.pid;
 
 
events {
use epoll;
worker_connections 1024;
}
 
 
stream {
  server {
  listen 3000;
  proxy_pass 127.0.0.1:3306;
 
  4# 也支持socket
  4# proxy_pass unix:/var/lib/mysql/mysql.socket;
  }
}

UDP转发

目标: 发送UDP数据到3000端口,3001端口可以接收

/usr/local/nginx/conf/nginx.conf配置如下:

user nobody;
worker_processes auto;
 
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
 
#pid logs/nginx.pid;
 
 
events {
use epoll;
worker_connections 1024;
}
 
 
stream {
  server {
  listen 3000 udp;
  proxy_pass 127.0.0.1:3001;
 
  }
}
原文地址:https://www.cnblogs.com/guigujun/p/8075620.html