有个接口是通过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使用教程栏目进行学习!










