Search code examples
djangodockernginxdocker-composegunicorn

Django not loading static from nginx in docker container


I django server cannot load static files, however they are accessible directly through a URL.

I have a django server that is served by gunicorn inside a docker container.

My Django static sttings.py:

STATICFILES_DIRS = [
    (os.path.join(BASE_DIR, "static")),
]

STATIC_URL = "/static/"
STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, "../static"))

My Nginx conf:

http {
    sendfile on;
    

    server {
        listen 80;
        server_name localhost;

        location / {
            proxy_pass http://gunicorn:8000;
        }
        location /static/ {
            autoindex on;
            alias /static/;
        }
    }
}

My nginx docker-compose configuration:

  nginx:
    image: nginx:1.19.6-alpine
    depends_on:
      - gunicorn
    ports:
      - "80:80"
    expose:
      - "80"
      - "443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./certs:/etc/nginx/certs
      - nginx_static:/static

When i start the django server with debug mode on, the files load at localhost:8000 where the gunicorn container is, but they are not avaliable at localhost:80 where my nginx container is.

When I start it with debug off, static files arent loaded at all.

When I try to access a static file through nginx, e.g. localhost:80/static/my_static.css the file loads

I think this may be an issue with my django settings as calling the static in a html template like: {% static 'img/logo.png' %} will load that image, however none of my other css files will load even though {% load static %} is on every template

any help is much appreciated


Solution

  • Turns out that nginx was serving my css as a text file not a css file. fix was to include MIME types include /etc/nginx/mime.types;:

    http {
        sendfile on;
        
    
        server {
            listen 80;
            server_name localhost;
    
            location / {
                proxy_pass http://gunicorn:8000;
            }
            location /static/ {
                include  /etc/nginx/mime.types;
                autoindex on;
                alias /static/;
            }
        }
    }