notexactly
notexactly

Reputation: 1018

NGINX does not serve the collected static files

I am running a dockerized Django application on an AWS EC2 instance, and the page loads without the static files, even though NGINX has them collected. I find this pretty strange, as it had not happened to me until now (at least on my local machine). It would be greatly appreciated if you could help me solve this issue.

This is my docker-compose.yml file:

version: "3"

services:
  web:
    restart: always
    build: .
    command: bash -c "
      python manage.py makemigrations &&
      python manage.py migrate &&
      python manage.py creategroups &&
      python manage.py initializesuperuser &&
      python manage.py collectstatic --noinput &&
      daphne -b 0.0.0.0 -p 80 DL.asgi:application"
    expose:
      - 80
    environment:
      - DJANGO_SETTINGS_MODULE=DL.production_settings
    volumes:
      - static_volume:/usr/src/app/DL/static/
      - media_volume:/usr/src/app/media_cdn

  nginx:
    restart: always
    build: ./nginx
    ports:
      - "80:80"
    volumes:
      - static_volume:/static/
      - media_volume:/media/
    depends_on:
      - web

volumes:
  static_volume:
  media_volume:

Here's production_settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = "/usr/src/app/DL/static/"   

A snippet of the file structure inside the web container (DL_app is the name of the Django app):

usr
|
|──src
   |
   |──app
      |
      |──DL
         |
         |──DL
         |
         |──DL_app
         |  |
         |  |──static
         |
         |──manage.py
         |
         |──static

And, lastly, here's nginx.conf:

upstream web {
    server web:80;
}

server {
    listen 80;
    location / {
        proxy_pass http://web;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_redirect off;
    }
    location /static/ {
        alias /usr/src/app/DL/static/;
    }
    location /protected/ {
        alias /media/;
    }
}

Upvotes: 2

Views: 422

Answers (1)

anemyte
anemyte

Reputation: 20186

You have mounted static files in nginx container at /static path:

  nginx:
    restart: always
    build: ./nginx
    ports:
      - "80:80"
    volumes:
      - static_volume:/static/  # here

But your NGINX configuration defines they are at /usr/src/app/DL/static/

    location /static/ {
        alias /usr/src/app/DL/static/; # there is no such path in NGINX container
        #alias /static/;  # this should work
    }

Upvotes: 3

Related Questions