我使用 Nginx 做负载均衡,有时候可能某一台服务器可能会临时出问题,无法访问。这个时候就需要检测服务器是否有问题,这里的检测方式有两种:
1、被动健康检测
就是会判断请求在规定时间内是否报错,如果连续报错多少次,就暂停访问这台服务器多少秒,之后在循环前面的操作。
2、主动健康检测
就是 Nginx主动向其他服务器不间断的发送请求,判断健康检查请求是否得到正确响应。但是这个需要安装第三方的模块。
我今天这里只讲被动健康检查,只需要配置一下 Nginx 的配置文件就可以了,非常简单。完整的配置如下:
重点代码下面来详细讲解一下
upstream detayun_server {server 127.0.0.1:8000 max_fails=1 fail_timeout=140s;server 192.168.31.217:80 max_fails=1 fail_timeout=140s;}
这里就是配置不同的服务器,
max_fails 参数就是最大失败次数,如果连续失败次数超过设置的值,就会把这台标记为不可用。
fail_timeout是标记失败的时间,max_fails触发了,就把这台服务器标记为不可用的时间。
所以整体的意思是,如果某台服务器有一次请求触发失败,就会把这台服务器140秒内标记为不可用,所有的请求都不会在140秒内发送给这个服务器。所以 max_fails 和 fail_timeout 两个参数是需要配合一起使用的。
proxy_connect_timeout 3s; proxy_read_timeout 3s;
proxy_connect_timeout 指令用于设置 Nginx 与后端服务器建立连接的超时时间。这个超时时间是从 Nginx 发起连接到服务器开始,到服务器响应连接请求为止的时间。如果在这个时间内没有建立连接,Nginx 将关闭连接并返回一个错误。
proxy_read_timeout 指令用于设置 Nginx 从后端服务器读取响应的超时时间。这个超时时间是从 Nginx 收到后端服务器的第一个字节开始,到接收完整个响应为止的时间。如果在这个时间内没有接收到完整的响应,Nginx 将关闭连接并返回一个错误。
设置这两个参数,可以让 Nginx 更快的判断某台服务器是否不可用。默认可能会判断20秒,之后就只需要6秒就可以判断完毕。
完整配置如下:
#user nobody;
worker_processes 1;#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;proxy_connect_timeout 3s; proxy_read_timeout 3s; #上传文件的大小限制 默认1MBclient_max_body_size 50m;upstream detayun_server {server 127.0.0.1:8000 max_fails=1 fail_timeout=140s;server 192.168.31.217:80 max_fails=1 fail_timeout=140s;}server {listen 80;server_name detayun.cn;root E:\Python\lixin_project\lixin;location / {proxy_set_header Host $http_host; # 设置代理服务器的HTTP_HOST头部proxy_pass http://detayun_server;root html;index index.html index.htm;}location /static {try_files $uri /static/img/detayun_logo1.png;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}# HTTPS serverserver {listen 443 ssl;server_name detayun.cn;root E:\Python\lixin_project\lixin;ssl_certificate detayun.pem;ssl_certificate_key detayun.key;ssl_session_cache shared:SSL:1m;ssl_session_timeout 5m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;location / {proxy_set_header Host $http_host; # 设置代理服务器的HTTP_HOST头部proxy_pass http://detayun_server;root html;index index.html index.htm;}location /static {#alias /root/test;try_files $uri /static/img/detayun_logo1.png;}
}