【问题标题】:Django Nginx Gunicorn Upstream Premature closed connection while reading responseDjango Nginx Gunicorn Upstream 在读取响应时过早关闭连接
【发布时间】:2020-05-07 05:17:42
【问题描述】:

nginx 配置

server { 
    listen 80;
    server_name private.com;
    client_max_body_size 4G;
    client_body_buffer_size 8000M;
    client_body_timeout 120;
    proxy_connect_timeout 900s;
    proxy_read_timeout 900s;
    location = /favicon.ico { access_log off; log_not_found off; }
    autoindex on;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/dm/stat.cok;
    }
}

gunicorn.service

[Unit]
Description=gunicorn daemon
After=network.target


[Service]
User=Pa
Group=www-data
WorkingDirectory=/home/un/foldername
ExecStart=/home/un/foldername/bin/gunicorn \
        --access-logfile - \
        --workers 3 \
        --timeout 450 \
        --bind unix:/home/dm/stat.sock scistat.wsgi:application

[Install]
WantedBy=multi-user.target

我上传了一个 90mb 大小的大型 excel 文件,它包含 450000+ 行和 6 列。文件上传后,计算excel文件的行列f乘以计算excel文件的总行列,但是这个错误显示“upstream提前关闭连接,同时从上游读取响应头”

【问题讨论】:

  • 多久会失败?匹配超时设置之一。
  • 另外,没有理由将proxy_connect_timeout 设置为超过 75 秒。
  • @OlegRusskin,需要 5 分钟计算 excel 文件的行和列,然后出现 502 bad gateway 错误并检查 nginx 中的错误,显示上游过早关闭的连接。
  • @OlegRusskin proxy_connect_timeout 最长为 75 秒?

标签: django nginx gunicorn


【解决方案1】:

这看起来像长时间运行的同步请求 - 用户上传大文件,它正在视图中进行处理,这需要大量时间并且只有在对用户请求的响应被发回之后。

在处理文件时,没有向用户返回响应,并且 gunicorn 工作人员由于超时而被杀死。为了验证这一点 - 尝试将 gunicorn 中的超时时间增加到 900 或更高(然后 if 可能会因超过 nginx proxy_read_timeout 而终止)。


最好不要增加 gunicorn 超时时间远离默认 30 秒(除非真的需要) - 尝试删除/降低超时时间并修改如下代码。

上传视图中只保留文件保存/基本验证逻辑 - 文件上传到服务器后尽快返回响应。

使用Celery 在单独的 celery worker 中运行长时间运行/周期性/异步任务 - 例如处理/计算上传的文件。

可以制作单独的端点/视图来获取上传文件或结果的状态信息。


视图处理时间应尽可能短——这会极大地影响用户体验。如果用户在发出请求后需要等待超过几秒钟的时间才能得到响应 - 那是不好的。如果需要几分钟 - 祝你好运。长时间运行的操作最好以异步方式执行 - 并且

【讨论】:

  • 好的,谢谢,我会试试你的建议。
猜你喜欢
  • 2019-05-15
  • 2018-11-09
  • 2018-06-11
  • 2017-08-12
  • 2019-04-04
  • 1970-01-01
  • 2014-04-02
  • 2012-08-15
  • 2018-09-21
相关资源
最近更新 更多