Skip to main content
 首页 » 编程设计

python之大型 Nginx/uwsgi 服务内容挂起 keepalive_timeout 秒

2025年05月04日10fff_TT

我使用如下 View 通过 django 1.5.1 提供动态生成的 pdf:

pdf = generate_pdf() 
response = HttpResponse(pdf, mimetype="application/pdf") 
response['Content-Disposition'] = 'attachment; filename=1234_2013_10_30.pdf' 
return response 

100% 的时间在开发服务器上工作。但是,我使用的是 uwsgi 版本 1.9.18.2 和 nginx 版本 1.1.19 并得到以下行为:

$ curl -v -o test.out "http://localhost/demo/awc.pdf?submissionType=addition&permit=1234" 
... 
* Connected to localhost (127.0.0.1) port 80 (#0) 
> GET /demo/awc.pdf?submissionType=addition&permit=1234 HTTP/1.1 
> User-Agent: curl/7.21.2 (Windows) libcurl/7.21.2 OpenSSL/1.0.0a zlib/1.2.3 
> Host: localhost 
> Accept: */* 
> 
  0     0    0     0    0     0      0      0 --:--:--  0:00:10 --:--:--     0 
 
< HTTP/1.1 200 OK 
< Server: nginx/1.1.19 
< Date: Wed, 30 Oct 2013 22:14:23 GMT 
< Content-Type: application/pdf 
< Transfer-Encoding: chunked 
< Connection: keep-alive 
< Vary: Accept-Language, Cookie 
< Content-Language: en-us 
< Content-Disposition: attachment; filename=1234_2013_10_30.pdf 
< 
{ [data not shown] 
100 2313k    0 2313k    0     0  270k       0 --:--:--  0:00:12 --:--:--     0 
..... 
100 2313k    0 2313k    0     0  77452      0 --:--:--  0:00:30 --:--:--     0* transfer closed with outstanding read data remaining 
100 2313k    0 2313k    0     0  75753      0 --:--:--  0:00:31 --:--:--     0* Closing connection #0 
 
curl: (18) transfer closed with outstanding read data remaining 

总而言之,客户端在 10 秒内得到响应,在约 2 秒内下载所有数据,然后再挂起 18 秒。

并非巧合,我的 nginx 配置指定了 keepalive_timeout 20s;。等待 keepalive_timeout 秒后, 内容完全没问题。 我可以通过将 keepalive_timeout 设置为零来“解决”问题,但这并不是一个真正可行的解决方案。

当内容很小(小于 ~1MB)时,问题莫名其妙地消失了。

> GET "http://localhost/demo/awc.pdf?submissionType=addition&permit=5678" HTTP/1.1 
> User-Agent: curl/7.21.2 (Windows) libcurl/7.21.2 OpenSSL/1.0.0a zlib/1.2.3 
> Host: localhost 
> Accept: */* 
> 
  0     0    0     0    0     0      0      0 --:--:--  0:00:04 --:--:--     0< HTTP/1.1 200 OK 
< Server: nginx/1.1.19 
< Date: Wed, 30 Oct 2013 22:39:12 GMT 
< Content-Type: application/pdf 
< Transfer-Encoding: chunked 
< Connection: keep-alive 
< Vary: Accept-Language, Cookie 
< Content-Language: en-us 
< Content-Disposition: attachment; filename=1234_2013_10_30.pdf 
< 
{ [data not shown] 
100  906k    0  906k    0     0   190k      0 --:--:--  0:00:04 --:--:--  246k* Connection #0 to host localhost left intact  

我猜它与分块编码或缺少内容长度 header 有关,但我似乎找不到神奇的咒语。有什么想法吗?

请您参考如下方法:

仍然不确定为什么会出现最初的问题,但找到了一个不错的解决方法:

在 nginx 配置中禁用分块传输编码似乎可以避免这个问题。

location / { 
    uwsgi_pass unix:///var/run/uwsgi/app/socket; 
    include uwsgi_params; 
    # keepalive_timeout 0; 
    chunked_transfer_encoding off; 
}