配置上游健康检查
健康检查是一种根据上游服务的响应能力来确定其健康状况的机制。启用健康检查后,APISIX 将仅将请求转发到被视为健康的上游服务,而不会将请求转发到被视为不健康的服务。
健康检查通常有两种方法:
- 主动健康检查:APISIX 主动并定期向上游服务发送请求,并根据这些请求的响应确定其健康状况。
- 被动健康检查:APISIX 根据上游服务对客户端请求的响应来确定其健康状况,而无需主动探测。
本指南将向你展示如何为你的上游服务配置主动和被动健康检查。
前置条件
启动示例上游服务
在与 APISIX 相同的 Docker 网络中启动两个 NGINX 实例作为示例上游服务:
DOCKER_NETWORK=apisix-quickstart-net
docker run -d -p 8080:80 --network=${DOCKER_NETWORK} --name nginx1 nginx
docker run -d -p 8081:80 --network=${DOCKER_NETWORK} --name nginx2 nginx
验证两个 NGINX 实例都在运行:
for port in 8080 8081; do
curl -s "http://127.0.0.1:$port" | grep -q "Welcome to nginx" &&
echo "NGINX welcome page available on port $port."
done
你应该看到以下响应:
NGINX welcome page available on port 8080.
NGINX welcome page available on port 8081.
配置主动健康检查
主动检查通过定期向服务发送请求或探测并查看它们的响应情况来确定上游服务的健康状况。
以下示例说明如何:
- 在主动探测中发送自定义方法和请求体;
- 使用主动检查检测上游状态变化;
- 在所有上游状态均不健康时观察 APISIX 如何转发请求。
主动 HTTP 和 HTTPS 检查默认使用带空请求体的 GET。当健康端点需要请求负载时,可将 http_method 设为任意受支持的 HTTP 方法,并使用 http_req_body。非空请求体会自动添加相应的 Content-Length 头。
发送 POST 健康检查
将第一个示例 NGINX 服务配置为仅接受 POST 的健康端点,并记录探测的方法、路径和内容长度:
docker exec nginx1 /bin/sh -c 'cat > /etc/nginx/conf.d/default.conf <<"EOF"
log_format health_probe "$request_method $uri $content_length";
server {
listen 80;
access_log /tmp/health-probe.log health_probe;
location = /health {
if ($request_method != POST) {
return 405;
}
return 200 "healthy\n";
}
location / {
return 200 "Welcome to nginx!\n";
}
}
EOF
nginx -s reload'
创建一个带 JSON 请求体的 POST 主动检查路由:
curl "http://127.0.0.1:9180/apisix/admin/routes/post-health-check" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/post-health-check",
"upstream": {
"type": "roundrobin",
"nodes": {
"nginx1:80": 1
},
"checks": {
"active": {
"type": "http",
"http_method": "POST",
"http_path": "/health",
"http_req_body": "{\"status\":\"check\"}",
"req_headers": [
"Content-Type: application/json"
],
"healthy": {
"interval": 2,
"successes": 1
},
"unhealthy": {
"interval": 1,
"http_failures": 1
}
}
}
}
}'
通过路由发送请求以启动健康检查器,等待一次探测后检查 NGINX access log:
curl -i "http://127.0.0.1:9080/post-health-check"
sleep 2
docker exec nginx1 /bin/sh -c "grep 'POST /health' /tmp/health-probe.log | tail -n 1"
路由请求应返回 200 OK。日志应确认主动探测使用 POST,并发送了 18 字节的请求体:
POST /health 18