无法使用NGINX提供Django静态文件

slhcrj9b  于 2022-11-02  发布在  Nginx
关注(0)|答案(1)|浏览(185)

我正在尝试部署一个Django和React网站使用gunicorn,nginx和docker。
我无法让nginx读取我的静态文件,例如django管理面板。我已经运行了python manage.py collecstatic,文件在recommendations-be/backend/static
下面是docker-compose.yml文件:

version: '3'

services:
  backend:
    build:
      context: ./recommendations-be
    command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 --timeout 0
    ports:
      - "8000:8000"
    volumes:
      - static:/django/backend/static
  frontend:
    build:
      context: ./recommendations-fe
    volumes:
      - react_build:/react/build
  nginx:
    image: nginx:latest
    ports:
      - "80:8080"
    volumes:
      - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro
      - react_build:/var/www/react
      - static:/django/backend/static
    depends_on:
      - backend
      - frontend
volumes:
  static:
  react_build:

下面是我的nginx配置文件:

upstream api {
    server backend:8000;
}

server {
    listen 8080;

    location / {
        root /var/www/react;
    }

    location /api/ {
        proxy_pass http://api;
        proxy_set_header Host $http_host;
    }

    location /static/ {
        alias /django/backend/static;
    }

}

下面是后端目录recommendations-be中的Dockerfile

FROM python:3.10.8-slim-buster

ENV PYTHONUNBUFFERED 1

WORKDIR /django

COPY requirements.txt requirements.txt

RUN pip install --upgrade pip --no-cache-dir
RUN pip install -r requirements.txt --no-cache-dir

COPY . .

而 Django settings.py

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

下面是我的项目中的文件结构:file structure

oipij1gg

oipij1gg1#

在您的nginx配置中,请进行以下更改:

location /static/ {
    alias /static/
}

然后,在您的docker-compose.yml文件中,在Nginx的卷定义中,请替换以下行

- static:/django/backend/static

与以下内容一致:

- static:/static

Nginx现在应该能够为您的静态文件提供服务了。

相关问题