Nginx/Tengine 根据域名进行健康检查
【摘要】Tengine,增加了ngx_http_upstream_check_module模块,这样提供了主动式后端服务器健康检查的功能,功能非常赞。之前一直使用都是通过HTTP(ip+port),TCP(port)方式,如果后端服务器有多个虚拟主机,健康检查会收到干扰,所以使用域名(domain)进行健康检查是有必要的。经过一些测试,发现如下方法可行,于是记录并share出来,希望对一些有类似需求的同学有所帮助。
测试案例:
前端服务器使用Tengine,配置healthckeck.sudops.com域名,proxy_pass到后端服务器
后端服务器同样使用Tengine/Nginx,配置两个虚拟主机 healthckeck.sudops.com和healthckeck2.sudops.com,并且设置healthckeck2.sudops.com为默认Vhost
具体配置文件如下,两个虚拟主机配置
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 |
具体配置文件如下,两个虚拟主机配置 # cat healtcheck_backend.conf server { listen 8090; server_name healthckeck.sudops.com; index index.html index.htm; access_log off; location / { root html/1; access_log off; } } # cat healtcheck_backend_2.conf server { listen 8090 default; server_name healthckeck2.sudops.com; index index.html index.htm; access_log off; location / { root html/2; access_log off; } } |
html创建两个目录和健康检查文件
1 2 |
echo "1 ok" > html/1/status.html echo "2 ok" > html/2/status.html |
Tengine前端配置文件:
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 |
#cat healthckeck.sudops.com.conf server { listen 80; server_name healthckeck.sudops.com; index index.html index.htm; root html; access_log off; location / { add_header Xdebug healthcheck01; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_pass http://healthcheck_sudops; access_log off; } } #cat nginx.conf upstream healthcheck_sudops { server 10.233.146.19:8090 weight=1 max_fails=2 fail_timeout=30s; check interval=5000 rise=2 fall=5 timeout=1000 type=http; #check_http_send "HEAD /index.html HTTP/1.0\r\n\r\n"; check_http_send "HEAD /status.html HTTP/1.1\r\nConnection: keep-alive\r\nHost: healthckeck.sudops.com\r\n\r\n"; check_http_expect_alive http_2xx http_3xx; } |
这样就可以通过修改后端服务器的vhost配置及健康检查页面来进行测试了。
测试过程:
1. 为达到效果,把html/2/status.html文件重命名为html/2/status.html.bak
因为8090端口默认的vhost是healthckeck2.sudops.com,所以如果使用配置
1 |
check_http_send "HEAD /index.html HTTP/1.0\r\n\r\n"; |
请求http://healthckeck.sudops.com/status.html会落到healthckeck2.sudops.com vhost上,后端这样会返回404,健康检查失败,前端返回502
如果使用
1 |
check_http_send "HEAD /status.html HTTP/1.1\r\nConnection: keep-alive\r\nHost: healthckeck.sudops.com\r\n\r\n"; |
进行健康检查,这样会将http header Host: healthckeck.sudops.com传过去,有了host头,后端服务器就不会落到默认的vhost中,健康检查成功,返回200,页面可以正常访问了。
本文固定链接: https://www.sudops.com/nginx-tengine-health-check-with-domain.html | 运维·速度