首页 > 解决方案 > 如果正文太大,Nginx/Uwsgi/Flask POST 超时

问题描述

我正在使用基于https://github.com/tiangolo/uwsgi-nginx-flask-docker/tree/master/python3.6的 dockerimage 。我在里面运行一个接受 POST 的 python 应用程序,对 json 主体进行一些处理,然后返回一个简单的 json 响应。像这样的帖子:

curl -H "Content-Type: application/json" -X POST http://10.4.5.168:5002/test -d '{"test": "test"}'

工作正常。但是,如果我发布一个更大的 json 文件,我会得到一个 504:网关超时。

curl -H "Content-Type: application/json" -X POST http://10.4.5.168:5002/test -d @some_6mb_file.json

我感觉 Nginx 和 Uwsgi 之间的通信存在问题,但我不确定如何解决。

编辑:我跳入 docker 容器并手动重新启动 nginx 以获得更好的日志记录。我收到以下错误:

2018/12/21 20:47:45 [错误] 611#611: *1 上游超时(110:连接超时)同时从上游读取响应标头,客户端:10.4.3.168,服务器:,请求:“POST /模型/refuel_verification_model/predict HTTP/1.1”,上游:“uwsgi://unix:///tmp/uwsgi.sock”,主机:“10.4.3.168:5002”

从容器内部,我启动了我的 Flask 应用程序的第二个实例,在没有 Nginx 和 Uwsgi 的情况下运行,它运行良好。返回响应大约需要 5 秒(由于数据的处理时间。)

配置:

/etc/nginx/nginx.conf:

user  nginx;
worker_processes 1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
daemon off;

/etc/nginx/conf.d/nginx.conf:

server {
    listen 80;
    location / {
        try_files $uri @app;
    }
    location @app {
        include uwsgi_params;
        uwsgi_pass unix:///tmp/uwsgi.sock;
    }
    location /static {
        alias /app/static;
    }
}

/etc/nginx/conf.d/upload.conf:

client_max_body_size 128m;
client_body_buffer_size 128m;

标签: pythonnginxflaskuwsgi

解决方案


在代理到 aiohttp (Python) 应用程序时,我遇到了这种行为。

就我而言,在代理的位置块中,我需要禁用缓存:

从块中删除:

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;

结果,工作配置是这样的:

  server {
    listen 80;
    location / {
        try_files $uri @app;
    }
    location @app {
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_redirect off;
      proxy_buffering off;
      proxy_pass http://myapp;
    }
    location /static {
        alias /app/static;
    }
}

推荐阅读