有個接口是通過socket通信,對端服務器訪問存在ip限制,只好通過跳板機,因為它具備訪問對端服務器的權限。nginx1.9開始支持tcp層的轉發,通過stream實現的,而socket也是基于tcp通信。
實現過程:
1.安裝nginx,stream模塊默認不安裝的,需要手動添加參數:–with-stream,根據自己系統版本選擇nginx1.9或以上版本。
2.nginx.conf 配置,參考說明:ngx_stream_core_module
nginx.conf
user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { ................. } # tcp層轉發的配置文件夾 include /etc/nginx/tcp.d/*.conf;
請注意,stream配置不能放到http內,即不能放到/etc/nginx/conf.d/,因為stream是通過tcp層轉發,而不是http轉發。
如配置在http內,啟動nginx會報如下錯誤:
nginx: [emerg] "server" directive is not allowed here
3.在tcp.d下新建個bss_num_30001.conf文件,內容如下:
stream { # 添加socket轉發的代理 upstream bss_num_socket { hash $remote_addr consistent; # 轉發的目的地址和端口 server 130.51.11.33:19001 weight=5 max_fails=3 fail_timeout=30s; } # 提供轉發的服務,即訪問localhost:30001,會跳轉至代理bss_num_socket指定的轉發地址 server { listen 30001; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass bss_num_socket; } }
4.重啟nginx,訪問localhost:30001,會跳轉到bss_num_socket指定的轉發地址130.51.11.33:19001。
更多Nginx相關技術文章,請訪問Nginx使用教程欄目進行學習!?
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END