背景

在我们的场景下,nginx 的 upstream servers 是一堆容器。 容器的主机名不变,但其 ip 可能发生变化。 我希望在容器 ip 发生变化时,无需变更 nginx 的配置。

实现

直接上代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
map $x $backend {
    1       server1:12345;
    2       server2:12345;
    3       server3:12345;
    
    default backupserver:12345;
}

server {
    listen 7777;

    location /r {
        resolver 114.114.114.114 valid=60s ipv6=off;
        set_by_lua_block $x { return math.random(3) }
        proxy_pass http://$backend;
    }
}

做一下性能测试

静态 upstream

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$ ./wrk --latency -d 1m -t 10 -c 100  http://127.0.0.1:7777/s
Running 1m test @ http://127.0.0.1:7777/s
  10 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     5.93ms    5.66ms 177.31ms   97.39%
    Req/Sec     1.85k   238.42     2.30k    69.12%
  Latency Distribution
     50%    5.16ms
     75%    5.85ms
     90%    7.06ms
     99%   27.34ms
  1105047 requests in 1.00m, 188.59MB read
  Non-2xx or 3xx responses: 1105047
Requests/sec:  18412.50
Transfer/sec:      3.14MB

动态 upstream

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$ ./wrk --latency -d 1m -t 10 -c 100  http://127.0.0.1:7777/d
Running 1m test @ http://127.0.0.1:7777/d
  10 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     6.33ms    3.98ms 101.19ms   96.57%
    Req/Sec     1.68k   185.44     2.27k    77.58%
  Latency Distribution
     50%    5.73ms
     75%    6.46ms
     90%    7.28ms
     99%   25.91ms
  1005401 requests in 1.00m, 171.58MB read
  Non-2xx or 3xx responses: 1005401
Requests/sec:  16751.96
Transfer/sec:      2.86MB

玩得开心 :)

-EOF-