基本用法

upstream被包裹在http模块内,和server模块同级

一个upstream需要设置一个名称,这个名称可以在server里作proxy主机使用

1
2
3
4
5
upstream  node {
server 127.0.0.1:9001;
server 127.0.0.1:9002;
server 127.0.0.1:9003;
}
1
2
3
location / {
proxy_pass http://node;
}

权重weight

权重越大,该服务器承载的并发就越高

1
2
3
4
5
upstream  node {
server 127.0.0.1:9001 weight=3;
server 127.0.0.1:9002 weight=2;
server 127.0.0.1:9003 weight=1;
}

fail_timeout和backup

fail_timeout是故障等待超时时间

backup是备用服务器参数,可以为一个upstream设置一个备用服务器,在生产服务器全部都出问题时,可以自动切换到备用服务器上,为恢复服务争取时间

1
2
3
4
5
upstream  node {
server 127.0.0.1:9001 fail_timeout=60;
server 127.0.0.1:9002 fail_timeout=20;
server 127.0.0.1:9003 backup;
}

测试代码

使用express启动三个服务,端口号为9001、9002和9003:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const express = require('express')
var num = 1
const app = express()

app.get('/list',(req,res)=>{
res.json({
code:200,
message:"Nginx 负载均衡9001"
})
console.log("Nginx 负载均衡9001",num)
num++
})
//------------------------------9001
app.listen(9001,()=>{
console.log('9001 success')
})

//-----------------------------------
const express = require('express')
var num = 1
const app = express()

app.get('/list',(req,res)=>{
res.json({
code:200,
message:"Nginx 负载均衡9002"
})
console.log("Nginx 负载均衡9002",num)
num++
})
//------------------------------9002
app.listen(9002,()=>{
console.log('9002 success')
})

//--------------------------------

const express = require('express')
var num = 1
const app = express()

app.get('/list',(req,res)=>{

res.json({
code:200,
message:"Nginx 负载均衡9003"
})
console.log("Nginx 负载均衡9003",num)
num++
})
//------------------------------9003
app.listen(9003,()=>{
console.log('9003 success')
})