美文网首页
NGINX 后端服务器 TIME_WAIT 问题解决

NGINX 后端服务器 TIME_WAIT 问题解决

作者: gruan | 来源:发表于2020-07-17 16:16 被阅读0次

    在网上搜索 NGINX TIME_WAIT 大多数的解决方法是:
    修改 /etc/sysctl.conf 文件

    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_tw_recycle = 1
    

    然后用命令启用:

    sudo /sbin/sysctl -p
    

    然后看一下 TIME_WAIT 的数量:

    netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
    

    ss -ant | awk 'NR>1 {++s[$1]} END {for(k in s) print k,s[k]}'
    

    就说行了.
    然而,这个鸡毛只是解决了 NGINX 服务器的 TIME_WAIT 问题, 对后端服务器一点帮助都没有...



    如上图, 我就是按网上配置的, 后端服务器的 TIME_WAIT 还是多的不得了, 应用程序报了大量的这个错:

    对端口的访问被拒绝。
    

    亲测有效的方案是 keepalive + proxy_http_version 1.1 + proxy_set_header Connection ""

    upstream http_backend {
        server 127.0.0.1:8080;
        keepalive 16;
    }
    
    server {
        ...
    
        location /http/ {
            proxy_pass http://http_backend;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            ...
        }
    }
    

    参考文档
    指令 keepalive xxx 的意思:

    The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed.

    大至是说如果keepalive 的空闲连接数超过这个值, 就关掉最近最少使用的连接. 这个 xxx 是数量的意思, 有人说这个是时间, 是不对的. 具体这个数值设为多少, 我没有经验, 要慢慢调整吧.

    keepalive 只有在 http1.1 下起作用, 所以要加上 proxy_http_version 1.1;
    同时还要移除 http 请求头中的 Connection 参数, 因为它可能设置成了 Close
    proxy_set_header Connection ""

    回头看一下后端服务器的 TIME_WAIT

    效果显著

    相关文章

      网友评论

          本文标题:NGINX 后端服务器 TIME_WAIT 问题解决

          本文链接:https://www.haomeiwen.com/subject/xbvghktx.html