Nginx redirect with Gunicorn on Django app not working properly

Viewed 458

I've developed a simple Django web application but am currently struggling to set up nginx to properly serve static files.

The app runs correctly with Gunicorn on port 8000. I'm trying to add static files by accessing the port 8080.

Unfortunately, I get the following timeout message after a request on port 8080:

nginx_1  | 2020/09/02 12:16:56 [error] 27#27: *5 upstream prematurely closed connection while reading response header from upstream, client: 172.18.0.1, server: , request: "GET /admin/ HTTP/1.1", upstream: "uwsgi://172.18.0.4:8000", host: "0.0.0.0:8080"

I believe the error is coming from the server: , part of the error message above, but can't seem to figure out how to actually solve it.

Here is my nginx default.conf file:

server {
    listen 8080;

    location /static {
        autoindex off;
        alias /vol/static;
    }

    location / {
        uwsgi_pass app:8000;
        proxy_request_buffering off;
        proxy_buffering off;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        include /etc/nginx/uwsgi_params;
    }
}

Here is the Dockerfile of my nginx image:

FROM nginxinc/nginx-unprivileged:1-alpine

COPY /docker/prod/nginx/uwsgi_params /etc/nginx/uwsgi_params

USER root

RUN mkdir -p /vol/static
RUN chmod 755 /vol/static

USER nginx

And here's my docker-compose.yml:

version: "3"
services:
  app:
    build:
      context: .
      dockerfile: docker/prod/python/Dockerfile
    ports:
      - 8000:8000
    volumes:
      - .:/workspace:cached
      - static_data:/vol/web
    working_dir: /workspace/src/
    environment:
      - DJANGO_SETTINGS_MODULE=config.settings.production
    env_file:
      - ./src/.env
    command: sh -c "python manage.py migrate && python manage.py init_db && python manage.py collectstatic --noinput && gunicorn --preload --bind 0.0.0.0:8000 --log-level debug -w 4 config.wsgi"

  # Serving static files with nginx
  nginx:
    build:
      context: .
      dockerfile: docker/prod/nginx/Dockerfile
    volumes:
      - static_data:/vol/static
      - ./docker/prod/nginx/default.conf:/etc/nginx/conf.d/default.conf
    ports:
      - 8080:8080
    depends_on:
      - app

volumes:
  pgdata:
  static_data:
  

Any help would be extremely appreciated. I've spent like a "bad amount of time" on this :D

1 Answers

I know this isn't a proper answer to this question, but I'll leave it here in case anyone runs into the same issue.

I ended up giving up on nginx entirely and just used whitenoise to serve my static files. The configuration was 10x easier and the result seems the same. There are probably some cases for which one is better than the other but for my case it worked great.

Related