天天看點

使用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;
 
  }
}      

不要讓懶惰占據你的大腦,不讓要妥協拖跨你的人生。青春就是一張票,能不能趕上時代的快車,你的步伐掌握在你的腳下,good luck