How to serve staticfiles from docker django app to hosted nginx

Viewed 43

My goal is to serve the staticfiles to nginx on ubuntu from a docker django app container without using docker nginx

I setup the reverse proxy to django all works fine in dev mode but when i turn Debug to False nginx doesn't recognize the staticfiles path here's a screenshot

Here's my dockerfile for django app

FROM python:3.9
RUN mkdir /app
WORKDIR /app
COPY . /app
RUN pip install pipenv
RUN pipenv install --system --deploy --ignore-pipfile
EXPOSE 8000
ENTRYPOINT ["python", "manage.py"]
CMD ["runserver", "0.0.0.0:8000"]

And here's my nginx config

upstream django { 
    server 127.0.0.1:8001;
 } 
 server {
    server_name django.com;
    listen 80;
    listen 8000;
    client_max_body_size 100M;
    location / {    
        proxy_pass http://django;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forward-Proto http;
        proxy_set_header X-Nginx-Proxy true;

        proxy_redirect off;
        proxy_read_timeout 1000;
        proxy_connect_timeout 1000;
        proxy_send_timeout 1000; 
    }
} 
1 Answers

To have NGINX serve your staticfiles, your config needs to be edited. How do you expect nginx to find your files otherwise?

Luckily, it's a simple edit. :)

upstream django { 
    server 127.0.0.1:8001;
 } 
 server {
    server_name django.com;
    listen 80;
    listen 8000;
    client_max_body_size 100M;
    
    location /static {
        alias /PATH/TO/STATIC_FILES;
    }

    location / {    
        proxy_pass http://django;
        ...
    }
} 

Don't forget to configure your static root, and run:

py manage.py collectstatic

This will make sure Django's default CSS/JS is included in your staticfiles.

When DEBUG=True, your staticfiles will be served by Django. This is not good, and can lead to some serious perfomance and security problems.

Edit:

Alternatively, have a look at Django-Whitenoise. It's great for serving staticfiles.

http://whitenoise.evans.io/en/stable/

Related