30秒后出现502个网关错误

时间:2020-04-13 08:26:32

标签: nginx gunicorn bad-gateway

我网站上的一个页面需要在服务器上进行长时间的计算(约2分钟)。如果我在localhost上运行网站,则工作正常。但是在生产的时候〜30秒。这是Nginx conf的http部分:

http {
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;
tcp_nodelay         on;
keepalive_timeout   120;
types_hash_max_size 2048;

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

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_read_timeout 300;
            proxy_connect_timeout 300;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }

}

我尝试添加:

fastcgi_read_timeout 300;
proxy_read_timeout 300;

最后(在“服务器”之后),但是它什么也没做。

1 个答案:

答案 0 :(得分:2)

如果收到502 Bad Gateway错误,则表明您的应用程序服务器(我猜是根据您的标签,它是Unicorn)正在发送超时而不是Nginx,您应该在生产服务器中的unicorn.rb文件中增加超时时间

worker_processes 2
listen "/tmp/xxx.socket"
##equal to your proxy read timeout in the Nginx config.
timeout 300 
pid "/tmp/unicorn.xxx.pid"

对于Python Green Unicorn,请执行以下操作:

NUM_WORKERS=3
TIMEOUT=300

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=x.x.x.x \
--pid=$PIDFILE