Nginx + uWSGi + Django长任务Bad Gateway错误

问题描述 投票:1回答:1

我在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继续在后台运行并完成作业(根据视图打印语句)。
  • 如果我尝试通过浏览器连接到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个回答
0
投票

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

vim /etc/nginx/nginx.conf

在http中添加:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.