在大型項目四層負載有LVS,但在中小型項目或者內部有很多應用需要做TCP四層基於端口轉,以前我們採用Socat,後面也嘗試使用iptables來做四層的端口轉發,同樣HAProxy提供高可用性、負載均衡以及基於TCP和HTTP應用的代理,但由於其配置相對複雜,在實際生產項目中還是以Nginx爲主,
Nginx1.9的推出不使用使之支持HTTP2.0,另外一上更加讓人興奮的就是默認支持TCP端口的四層負載均衡能力,話多多說直接看實例代碼
server { listen 127.0.0.1:12345; #監聽端口 proxy_pass 192.168.1.22:8080; #轉發到後端端口 }
看上面栗子,是不是覺得做端口轉發配置特別簡單
參考地址:http://nginx.org/en/docs/stream/ngx_stream_proxy_module.html
server { ... deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; deny all; }
在上面的栗子基礎上,增加一訪問限制,和HTTP的一模一樣也
參考地址:http://nginx.org/en/docs/stream/ngx_stream_access_module.html
worker_processes auto; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } stream { upstream backend { server 192.168.1.22:12345; server 192.168.1.23:12345; } server { listen 12345; proxy_pass backend; } }
來一上完整的栗子,這是一上帶伏在均衡的栗子哦,看了是不是特別激動,會Http反向代理的,看這代碼毫無壓力
如需要更加強大的東西可 以參考:
http://nginx.org/en/docs/stream/ngx_stream_core_module.html
server { listen 12345; proxy_connect_timeout 1s; proxy_timeout 1m; proxy_pass example.com:12345; } server { listen [::1]:12345; proxy_pass unix:/tmp/stream.socket; }
如上栗子,不光支持TCP/IP V4,還支持V6哦(不過暫時也用不上),並且還可以對連接的時效做一些限制,比起以前用過的iptables和socat端口轉發強大太多了,並且還很容易理解.
上參考路徑:http://nginx.org/en/docs/stream/ngx_stream_proxy_module.html
upstream backend { hash $remote_addr consistent; server backend1.example.com:12345 weight=5; server backend2.example.com:12345; server unix:/tmp/backend3; server backup1.example.com:12345 backup; server backup2.example.com:12345 backup; } server { listen 12346; proxy_pass backend; }
等等,還沒完,Nginx還有更加強大的就是對我產的轉發源也可以進行簡單明瞭的設置,基本沿用了Nginx http反向代理的配置方法主風格,簡直太喜歡.
http://nginx.org/en/docs/stream/ngx_stream_upstream_module.html
最後用上Nginx,媽媽再也不用擔心複雜架構,各種異構應用使用各種奇葩的七層協議及端口呢!