nginx搭建tcp代理服务器
nginx不仅可以是http代理服务器,也可以轻松搭建成tcp代理服务器。
首先我们看下最新开发版的搭建方法
1.安装
>wgethttp://nginx.org/download/nginx-1.9.0.tar.gz >tarzxvfnginx-1.9.0.tar.gz
版本要求1.9.0+
2、配置
worker_processesauto;
error_log/var/log/nginx/error.loginfo;
stream{
upstreambackend{
hash$remote_addrconsistent;
serverbackend1.example.com:12345weight=5;
server127.0.0.1:12345max_fails=3fail_timeout=30s;
serverunix:/tmp/backend3;
}
server{
listen12345;
proxy_connect_timeout1s;
proxy_timeout3s;
proxy_passbackend;
}
server{
listen[::1]:12345;
proxy_passunix:/tmp/stream.socket;
}
}
3.补充
现在nginx1.9是开发版,目前稳定版没有stream的功能,但在下个的稳定版发布时,这功能就会集成进来。因此推荐以后用httpproxy的同学可以考虑换成tcpproxy,如果只是做简单的代理而已,而且性能上会更优异。
二、老版本的搭建方法
nginxtcp代理功能由nginx_tcp_proxy_module模块提供,同时监测后端主机状态。该模块包括的模块有:ngx_tcp_module,ngx_tcp_core_module,ngx_tcp_upstream_module,ngx_tcp_proxy_module,ngx_tcp_upstream_ip_hash_module。
1.安装
#wgethttp://nginx.org/download/nginx-1.4.4.tar.gz #tarzxvfnginx-1.4.4.tar.gz #cdnginx-1.4.4 #./configure--add-module=/path/to/nginx_tcp_proxy_module #make #makeinstall
2.配置
http{
listen80;
location/status{
check_status;
}
}
tcp{
upstreamcluster_www_ttlsa_com{
#simpleround-robin
server127.0.0.1:1234;
checkinterval=3000rise=2fall=5timeout=1000;
#checkinterval=3000rise=2fall=5timeout=1000type=ssl_hello;
#checkinterval=3000rise=2fall=5timeout=1000type=http;
#check_http_send"GET/HTTP/1.0\r\n\r\n";
#check_http_expect_alivehttp_2xxhttp_3xx;
}
server{
listen8888;
proxy_passcluster_www_ttlsa_com;
}
}
这会出现一个问题,就是tcp连接会掉线。原因在于当服务端关闭连接的时候,客户端不可能立刻发觉连接已经被关闭,需要等到当Nginx在执行check规则时认为服务端链接关闭,此时nginx会关闭与客户端的连接。
3.保持连接配置
http{
listen80;
location/status{
check_status;
}
}
tcp{
timeout1d;
proxy_read_timeout10d;
proxy_send_timeout10d;
proxy_connect_timeout30;
upstreamcluster_www_ttlsa_com{
#simpleround-robin
server127.0.0.1:1234;
checkinterval=3000rise=2fall=5timeout=1000;
#checkinterval=3000rise=2fall=5timeout=1000type=ssl_hello;
#checkinterval=3000rise=2fall=5timeout=1000type=http;
#check_http_send"GET/HTTP/1.0\r\n\r\n";
#check_http_expect_alivehttp_2xxhttp_3xx;
}
server{
listen8888;
proxy_passcluster_www_ttlsa_com;
so_keepaliveon;
tcp_nodelayon;
}
}
nginx_tcp_proxy_module模块指令具体参见:http://yaoweibin.github.io/nginx_tcp_proxy_module/README.html