djangonginxnginx-configdjango-staticfilesdjango-deployment

NGINX serve static files - django project has no styling


I managed to deploy my Django app but I can not pass the static files with Nginx. I have followed all the instructions for deploying to production. When I inspect the page all I see is empty static folder Can anyone spot the mistake?

Thanks a lot

nginx.conf

 10 upstream app_upstream {
  9     server app:8080;
  8 }
  7
  6 server {
  5     listen 80;
  4     listen 443;
  1     server_name #######;
  2
  3     location /static/ {
  4         alias /static/;
  5     }
  6
  7     location /media/ {
  8         alias /media/;
  9     }
 10
 11     location / {
 12         proxy_set_header Host $host;
 13         proxy_pass http://app_upstream;
 14     }
 15 }

settings.py

14
 13 STATIC_URL = '/static/'
 12 STATIC_ROOT = '/static/'

docker-compose.yml

....
 12   app:
 13     build: .
 14     ports:
 15       - 8000:8000
 16       - 8080:8080
 17     env_file:
 18       - db_${RTE}.env
 19     volumes:
 20       - .:/app/
 21       - static:/static/
 22       - media:/media/
 23     depends_on:
 24       - db
 25
 26   nginx:
 27     build: nginx/
 28     ports:
 29       - 443:443
 30       - 80:80
 31     volumes:
 32       - ./nginx/${RTE}/conf.d/:/etc/nginx/conf.d/
 34       - static:/static/
 35       - media:/media/
 36     depends_on:
 37       - app
 38
 39 volumes:
 40   static:
...

Error message when I docker-compose:

nginx_1  | 2022/01/10 16:26:17 [error] 10#10: *8 open() "/static/custom.css" failed (2: No such--More
--More--

Solution

  • Having had a similar issue (but NOT using Docker), perhaps this might help.

    If you have a static folder in your root project for project level static files, and if you also have a command to run python manage.py collectstatic --noinput in your docker-compose or Dockerfile, which not understanding Docker too well, I think you'd still need in production, then perhaps renaming the STATIC_URL and STATIC_ROOT in settings.py can help since that command will try to collect all static files from all your apps into one folder. Try something like this:

        STATIC_URL = '/staticfiles/'
        STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
        STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))]
    

    Note that you would also have to update your Nginx file, i.e.,

        server {
                ...
                location /staticfiles/ {
                ...
               }