为什么Nginx proxy_connect_timeout似乎不起作用

时间:2018-08-27 09:13:46

标签: nginx proxypass

我有一个由nginx提供的api服务器,配置如下。我使用“ proxy_connect_timeout”和“ proxy_next_upstream”制作“备份服务器”,这意味着“ proxy_pass http://backup_server;”很忙(可能是因为mysql / redis连接超时),请求时间长达400ms,它返回给我一个http_504,请求传到“ jump_to_error”,然后由lua脚本处理(lua只是返回一个静态文件内容,我也在下面显示)。

    location /xxx/xxx/xxx{
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host xxx.xxx.xxx;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_connect_timeout 400ms;
            proxy_send_timeout 400ms;
            proxy_read_timeout 400ms;
            proxy_buffer_size 256k;
            proxy_buffers 4 256k;
            proxy_busy_buffers_size 256k;
            proxy_temp_file_write_size 256k;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_404 http_429;
            proxy_max_temp_file_size 128m;
            proxy_pass http://backup_server;
            access_log /nginx.log json;
            error_page  429 500 502 503 504 = @jump_to_error;
    }

location @jump_to_error {
    default_type 'text/plain';
    content_by_lua_file xxx.lua;
    access_log /lua.log json;
    }

但是,当请求qps增加(大约40 / sec)时,nginxlog中的$ upstream_response_time会超过400ms。我已经检查了cpu负载,磁盘IO和网络IO,它们都是正常的。

request_time log

所以,我对此有两个疑问。

  1. 为什么$ upstream_response_time大于nginx.conf中设置的“ proxy_connect_timeout”。(我还测试了,如果继续增加qps,时间甚至可能超过1s。)

  2. 我还检查了我的在线nginx日志,发现有些请求带有两个“上游状态/上游时间”。我在proxy_pass模块中设置了两台服务器,并且我知道一台服务器宕机时proxy_pass将返回两个上游状态(502 200)和两个上游时间(http://nginx.org/en/docs/http/ngx_http_upstream_module.html)。但是我不明白为什么只有一个“ 504状态”中有两个“ 504状态”的请求大约占0.1%。

there are a few double 504 status

这是我的lua脚本,它们仅返回静态文件内容。我曾经调试过日志,以lua记录时间成本,几乎所有请求都小于10ms,所以也许我们可以假设lua与上述问题无关。

function readfile(path)
  local file = io.open(path, "r")
  if file then
    local content = file:read("*a")
    io.close(file)
    return content
  end
  return nil
end


local file = "/xxx/xxx/file1"

local content = readfile(file)
ngx.header["Access-Control-Allow-Origin"] = "*"
ngx.header["Content-Type"] = "text/plain; charset=utf-8"
ngx.print(content)

0 个答案:

没有答案