如何修复生产中的 502 Bad Gateway 错误(Nginx)?

2024-01-21

当我尝试在数字海洋中托管的项目中上传大小约为 600MB 的大 csv 文件时,它尝试上传但显示 502 Bad Gateway Error (Nginx)。

该应用程序是一个数据转换应用程序。

这在本地工作时效果很好。

sudo tail -30 /var/log/nginx/error.log

shows

[error] 132235#132235: *239 upstream prematurely closed connection while reading response header from upstream, client: client's ip , server: ip, request: "POST /submit/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/submit/", host: "ip", referrer: "http://ip/"

sudo nano /etc/nginx/sites-available/myproject

shows

server {
    listen 80;
    server_name ip;
    client_max_body_size 999M;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
       alias  /root/static/;
    }
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

nginx.conf

user root;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

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

在转换过程发生时,我还运行了 javascript 加载程序。 我怎样才能解决这个问题?


如果您使用 django 3.1 或更高版本,您可以通过这种方式使文件处理异步,并在文件转换发生时向用户返回响应。 你的观点应该是这样的......

    import asyncio
    from django.http import JsonResponse
    from asgiref.sync import sync_to_async
    
    
    @sync_to_async
    def crunching_stuff(my_file):
        # do your conversion here
            
    async def upload(request):
        json_payload = {
            "message": "Your file is being converted"
        }
        my_file = request.POST.get('file')
        
        asyncio.create_task(crunching_stuff(my_file))
        return JsonResponse(json_payload)

在前端,如果您使用 Dropzone.js,您的用户可以看到文件上传进度,并且会更快地获得响应。这是更好的用户体验。https://www.dropzonejs.com/ https://www.dropzonejs.com/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复生产中的 502 Bad Gateway 错误(Nginx)? 的相关文章

随机推荐