使用Nginx進行TCP/UDP/IPV6端口轉發【原創】


nginx安裝添加stream模塊

先確定nginx安裝時,編譯的時候添加了--with-stream這個模塊支持。nginx 版本 >=1.9才支持。

# ../sbin/nginx -V
nginx version: nginx/1.10.3
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-23) (GCC) 
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-pcre --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-stream

修改nginx配置文件

比如10.32.7.76有訪問10.35.30.121的3306端口權限。10.45.23.47也想訪問,利用nginx轉發tcp。在10.32.7.76安裝nginx轉發訪問10.35.30.121的3306端口-->10.32.7.76的端口12345

在nginx.conf最后一行添加

stream {
    #將12345端口轉發到10.35.30.121的3306端口
    server {
        listen 12345;
        proxy_connect_timeout 5s;
        proxy_timeout 20s;
        proxy_pass 10.35.30.121:3306;
    }
}

 

如果報錯nginx: [emerg] "stream" directive is not allowed,請注意如果你用的是nginx的1.10版本的stream,那么http段和steam段是平行的

 

 nginx reload操作。

測試端口轉發

服務器10.45.23.47訪問10.35.30.121端口3306是不通的,也訪問不了數據庫

 

 現在訪問轉發服務器10.32.7.76的端口12345,測試一下

訪問成功。

nginx轉發UPD、IPV6

nginx.conf添加如下配置,並使用nginx -s reload重載nginx使其生效,同時注意防火牆/安全組放行對應的端口。

stream {
    #將12345端口轉發到192.168.1.23的3306端口
    server {
        listen 12345;
        proxy_connect_timeout 5s;
        proxy_timeout 20s;
        proxy_pass 192.168.1.23:3306;
    }
    #將udp 53端口轉發到192.168.1.23 53端口
    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass 192.168.1.23:53;
    }
    #ipv4轉發到ipv6
    server {
        listen 9135;
        proxy_connect_timeout 10s;
        proxy_timeout 30s;
        proxy_pass [2607:fcd0:107:3cc::1]:9135;
    }
}
  • listen:后面填寫源端口(也就是當前服務器端口),默認協議為TCP,可以指定為UDP協議
  • proxy_connect_timeout:連接超時時間
  • proxy_timeout:超時時間
  • proxy_pass:填寫轉發目標的IP及端口號

注意:nginx可以將IPV4的數據包轉發到IPV6,IPV6的IP需要使用[]括起來。

總結

目前能實現端口轉發的工具大致有:rinetd、SSH、iptables、nginx、haproxy,其中rinetd配置最為簡單,但不支持UDP轉發,並且該軟件已經好幾年未更新,如果您服務器上已經安裝了nginx,不妨用nginx做端口轉發。

參考

使用Nginx進行TCP/UDP端口轉發 - 小z博客
https://www.xiaoz.me/archives/10578

nginx 轉發tcp連接 - imcati - 博客園
https://www.cnblogs.com/imcati/p/11717802.html

(3條消息) Nginx 配置TCP代理轉發_jeikerxiao-CSDN博客_nginx tcp代理
https://blog.csdn.net/jeikerxiao/article/details/87863341

nginx報錯”stream”/”upstream” directive is not allowed 錯誤 – 慢慢賺錢博客
https://moneyslow.com/nginx%E6%8A%A5%E9%94%99stream-upstream-directive-is-not-allowed-%E9%94%99%E8%AF%AF.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM