djangonginxgunicorndigital-oceanhttp-status-code-502

Nginx gives 502 bad gateway but only for a few http requests


I made a portfolio website using django and hosted it on a digitalocean droplet with Postgres, Nginx, and Gunicorn. After testing it I noticed that a few of the subpages of the portfolio projects gives back the 502 response after 1 second of loading but interestingly enough it's not all of them. The pages that fail tend to have more images but I tried excluding the images the views.py sends to the template, however the ones with the 502 response failed out again.

(for context the images are provided by local server side and not by an online storage service)

The issue seems to be resolved when I reload those pages manually.

Here is the views.py:


def project_view(request:HttpRequest, name:str) -> HttpResponse:
    project = Project.objects.filter(name=name).first()
    images = ProjectImages.objects.filter(project=project)
    


    # for every image in images this downscales that image and compresses it with PIL
    for projectimage in images:
        generate_projectimage(projectimage)
    
    # this downscales the thumbnail image of the project
    generate_downscaled_thumbnail(project)

    return render(request, "project.html", {
        'project': project,
        'images' : images,
    })

The template that receives it:

 <div class="carousel">
                            <div class="carousel-cell">
                                <img src="data:image/jpeg;base64,{{ project.downscale }}" data-src="/media/{{ project.thumbnail }}">
                            </div>
                            {% for projectimage in images %}
                                <div class="carousel-cell">
                                    <img src="data:image/jpeg;base64,{{ projectimage.downscale }}" alt="" data-src="/media/{{ projectimage.image }}">
                                </div>
                            {% endfor %}
</div>

here is the nginx error log: Nginx upstream prematurely closed connection while reading response header from upstream

Is it something to do with nginx or the data that is being sent is too much or limited by a setting?


Solution

  • Check runtime of successful requests, I guess generate_projectimage and generate_downscaled_thumbnail can be long running and they should be moved to background tasks (e.g. use celery)