【问题标题】:Nginx+uWSGi+Django long task Bad Gateway errorNginx+uWSGi+Django 长任务 Bad Gateway 错误
【发布时间】:2019-08-03 00:53:56
【问题描述】:

在我的 django 视图中,我有一项很长的任务,需要 120-200 秒才能生成响应。

对于这个特定的视图,Nginx 会在 1 分钟后引发 502 Bad Gateway,并在日志中显示以下错误消息:

[error] 7719#7719: *33 upstream prematurely closed connection while reading response header from upstream,

这是我的 Nginx 配置:

upstream DjangoServer {
    server      127.0.0.1:8000;
    keepalive   300;
}
location / {
    include             proxy_params;
    proxy_pass          http://DjangoServer;
    allow               all;
    proxy_http_version  1.1;
    proxy_set_header    X-Cluster-Client-Ip $remote_addr;

    client_max_body_size    20M;
    keepalive_timeout       300;
    proxy_connect_timeout   300;
    proxy_send_timeout      300;
    proxy_read_timeout      300;
    send_timeout            300;
}

这是我的 uWSGI 配置:

uid=www-data
gid=www-data
http=127.0.0.1:8000
http-keepalive=300
master=1
vacuum=1
workers=2
threads=5
log-5xx=1

注意:

  • Nginx 和 uWSGI 适用于所有其他视图。
  • Django 开发服务器可以正常运行任务。
  • Nginx 502 错误后,uWSGI 继续在后台运行并完成作业,(根据 in view print 语句)。
  • 如果我尝试通过浏览器连接到 uWSGI,过一段时间(少于 120 秒)会显示 ERR_EMPTY_RESPONSE

你可以承担这样的任务

def long_task_view(request):
    start_time = time.time()
    print(start_time)
    # doing stuff
    time.sleep(130)
    print(time.time() - start_time)
    return HttpResponse("The result")

【问题讨论】:

    标签: django nginx uwsgi


    【解决方案1】:

    你可以尝试增加nginx的超时时间:

    vim /etc/nginx/nginx.conf
    

    在http中添加这个:

    http {
         ...
         fastcgi_read_timeout 300;
         ...
    }
    

    但最佳实践是创建一个异步进程来处理所采用的方法。我通常 celery 用于异步任务。

    【讨论】:

    • 这并不能解决我的问题,感谢您推荐 celery。
    • 如果可能的话,我会尝试异步处理
    猜你喜欢
    • 2012-10-01
    • 2019-09-05
    • 2017-02-05
    • 2014-02-07
    • 2018-04-23
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多