文章

Nginx_健康检测

方法一:

Active Health Checks可以检查范围更广的故障类型,并且仅适用于Nginx Plus

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
# 在zone指令中,指定区域名称和区域大小。 (此处,dns_zone是区域名称,而64k是区域大小)。
stream {
    #...
    upstream dns_upstream {
        zone   dns_zone 64k;
        server 192.168.136.130:53;
        server 192.168.136.131:53;
        server 192.168.136.132:53;
    }
    #...
}

# 在将流量转发到upstream组(通过proxy_pass)的服务器块中,为health_check指令指定UDP参数。
stream {
    #...
    server {
         listen       53 udp;
         proxy_pass   dns_upstream;
         health_check udp;
         health_check_timeout 5s;
    }
    #...
}


# Fine-Tuning 运行状况检查
我们可以通过为health_check指令指定以下给定参数来微调运行状况检查:
interval - 它定义Nginx Plus在几秒钟内发送健康检查请求的频率(默认值为5秒)。
passes - 服务器必须响应几次连续的健康检查才能被视为健康。预设值是1。
fails - 一些连续的健康检查表明服务器必须响应才能被认为是不健康的。预设值是1。

server {
    listen       53 udp;
    proxy_pass   dns_upstream;
    health_check interval=20 passes=2 fails=2 udp;
}

方法二:

ngx_healthcheck_module

下载

1
https://github.com/zhouchangxun/ngx_healthcheck_module#description

编译安装

1
2
3
./auto/configure --with-stream --add-module=../ngx_healthcheck_module/
make

配置

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
55
56
57
58
59
60
61
62
63
64
user  root;
worker_processes  1;
error_log  logs/error.log  info;
#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        # status interface
        location /status {
            healthcheck_status json;
        }
        # http front
        location / { 
          proxy_pass http://http-cluster;
        }   
    }
    # as a backend server.
    server {
        listen 8080;
        location / {
          root html;
        }
    }
    
    upstream http-cluster {
        # simple round-robin
        server 127.0.0.1:8080;
        server 127.0.0.2:81;

        check interval=3000 rise=2 fall=5 timeout=5000 type=http;
        check_http_send "GET / HTTP/1.0\r\n\r\n";
        check_http_expect_alive http_2xx http_3xx;
    }
}

stream {
    upstream tcp-cluster {
        # simple round-robin
        server 127.0.0.1:22;
        server 192.168.0.2:22;
        check interval=3000 rise=2 fall=5 timeout=5000 default_down=true type=tcp;
    }
    server {
        listen 522;
        proxy_pass tcp-cluster;
    }
    
    upstream udp-cluster {
        # simple round-robin
        server 127.0.0.1:53;
        server 8.8.8.8:53;
        check interval=3000 rise=2 fall=5 timeout=5000 default_down=true type=udp;
    }
    server {
        listen 53 udp;
        proxy_pass udp-cluster;
    }
    
}
本文由作者按照 CC BY 4.0 进行授权