Jamal的博客

nginx超时转发机制

nginx超时转发机制

配置

在配置nginx的时候,我们经常会配置upstream来配置后端转发的一些规则,最常见的就是nginx后面挂了几台tomcat的机器,upstream写法如下示例:

1
2
3
4
upstream linuxidc {
server 192.168.31.114:8080;
server 192.168.31.223:8080;
}

下面是对应的server的配置

1
2
3
4
5
6
7
8
9
10
11
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://linuxidc;
proxy_connect_timeout 2s;
proxy_read_timeout 2s;
proxy_send_timeout 2s;
}
}

在nginx中,当一个请求到达后端机器,后端机器因某些原因(load高等等)响应变慢导致超时的时候,nginx会把这个请求转发到另外的后端机器上,这个配置是:

1
proxy_next_upstream on;

在nginx中是默认打开的。以下来做个试验:
后端192.168.31.114 192.168.31.223两台机器都是node的一个server,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
192.168.31.114:server.js
var http = require("http");
http.createServer(function(request, response) {
for(var i = 0; i < 1000000; i++) {
console.log(i);
}
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8080);
192.168.31.223:server.js
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8080);

可以看到两者的区别在于114的机器在每次请求的时候会走一个循环,循环会导致读取超时;223的机器则是立刻返回响应。

验证

(1)112 223开启,nginx开启转发机制: