docker nginx django gunicorn not serving static files in production

Question:

Trying to deploy website with nginx + gunicorn + docker + django. But ngingx isn’t serving static files. Following are the configurations:

Django project structure

enter image description here

settings file production.py

STATIC_URL = "/static/"

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


STATIC_ROOT = "/app/forex/static/admin/"

Docker file for nginx

FROM nginx:1.19.0

COPY ./default.conf /etc/nginx/conf.d/default.conf

nginx configurations

upstream django {
    server website:8000;
}

server {
    listen 80;
    
    client_max_body_size 100M;
    proxy_set_header X-Forwarded-Proto $scheme;

    location / {
        proxy_pass http://django;
    }
    
    location /media/ {
        alias /app/media/;
    }

    location /static/ {
        alias /app/forex/static/admin/;
    }
}

Gunicorn docker file

FROM python:3


ADD requirements.txt /app/requirements.txt

ADD . /app
WORKDIR /app
EXPOSE 8000:8000

RUN pip install --upgrade pip && pip install -r /app/requirements.txt
RUN python manage.py collectstatic --no-input --settings=forex.settings.production

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "forex.wsgi:application", "DJANGO_SETTINGS_MODULE=forex.settings.production"]

docker-compose.yml

services:
    website:
        build:
          context: .
          dockerfile: Dockerfile.app
        env_file:
          - env
        container_name: website_container_8
    nginx:
        build: ./nginx
        volumes:
            - static:/app/forex/static/admin/
        ports:
            - "80:80"
        depends_on:
            - website
volumes:
  static:

FROM nginx container, it isn’t copying static files.
enter image description here

What do I need to change to make it working?

Asked By: Junaid Ali

||

Answers:

Your files are located at your website container, you need to share it, with the nginx container:

services:
    website:
        build:
          context: .
          dockerfile: Dockerfile.app
        env_file:
          - env
        container_name: website_container_8
        volumes:
            - static:/app/forex/static/admin/ #<-- you want to share this
    nginx:
        build: ./nginx
        volumes:
            - static:/app/forex/static/admin/ #<-- with this folder
        ports:
            - "80:80"
        depends_on:
            - website
volumes:
  static: #<-- you can do it through this
Answered By: C1sc0
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.