小知识:nginx搭建tcp代理服务器

nginx不仅可以是http代理服务器,也可以轻松搭建成tcp代理服务器。

首先我们看下最新开发版的搭建方法

1. 安装

?
1
2
> wget http://nginx.org/download/nginx-1.9.0.tar.gz
> tar zxvf nginx-1.9.0.tar.gz

版本要求 1.9.0+

2、配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
worker_processes auto;
error_log /var/log/nginx/error.log info;
stream {
upstream backend {
hash $remote_addr consistent;
server backend1.example.com:12345 weight=5;
server 127.0.0.1:12345      max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
server {
listen 12345;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass backend;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}

3. 补充

现在nginx 1.9是开发版,目前稳定版没有stream的功能,但在下个的稳定版发布时,这功能就会集成进来。因此推荐以后用http proxy的同学可以考虑换成tcp proxy,如果只是做简单的代理而已,而且性能上会更优异。

二、老版本的搭建方法

nginx tcp代理功能由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. 安装
?
1
2
3
4
5
6
# wget http://nginx.org/download/nginx-1.4.4.tar.gz
# tar zxvf nginx-1.4.4.tar.gz
# cd nginx-1.4.4
# ./configure –add-module=/path/to/nginx_tcp_proxy_module
# make
# make install

2. 配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
http {
listen 80;
location /status {
check_status;
}
}
tcp {
upstream cluster_www_ttlsa_com {
# simple round-robin
server 127.0.0.1:1234;
check interval=3000 rise=2 fall=5 timeout=1000;
#check interval=3000 rise=2 fall=5 timeout=1000 type=ssl_hello;
#check interval=3000 rise=2 fall=5 timeout=1000 type=http;
#check_http_send “GET / HTTP/1.0\r\n\r\n”;
#check_http_expect_alive http_2xx http_3xx;
}
server {
listen 8888;
proxy_pass cluster_www_ttlsa_com;
}
}

这会出现一个问题,就是tcp连接会掉线。原因在于当服务端关闭连接的时候,客户端不可能立刻发觉连接已经被关闭,需要等到当Nginx在执行check规则时认为服务端链接关闭,此时nginx会关闭与客户端的连接。

3. 保持连接配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
http {
listen 80;
location /status {
check_status;
}
}
tcp {
timeout 1d;
proxy_read_timeout 10d;
proxy_send_timeout 10d;
proxy_connect_timeout 30;
upstream cluster_www_ttlsa_com {
# simple round-robin
server 127.0.0.1:1234;
check interval=3000 rise=2 fall=5 timeout=1000;
#check interval=3000 rise=2 fall=5 timeout=1000 type=ssl_hello;
#check interval=3000 rise=2 fall=5 timeout=1000 type=http;
#check_http_send “GET / HTTP/1.0\r\n\r\n”;
#check_http_expect_alive http_2xx http_3xx;
}
server {
listen 8888;
proxy_pass cluster_www_ttlsa_com;
so_keepalive on;
tcp_nodelay on;
}
}

nginx_tcp_proxy_module模块指令具体参见: http://yaoweibin.github.io/nginx_tcp_proxy_module/README.html

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:在Ubuntu系统上安装Nginx服务器的简单方法

2023-5-4 1:22:51

建站知识

小知识:Nginx服务器中的GZip配置参数详解

2023-5-4 1:41:35

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索