【问题标题】:Nginx error with django staticfiles "no such file or directory"Django 静态文件的 Nginx 错误“没有这样的文件或目录”
【发布时间】:2023-02-18 23:44:38
【问题描述】:

我正在尝试让 nginx 处理对 django 应用程序中的静态文件的请求,但它会引发错误

 [error] 20#20: *1 open() "/home/app/web/staticfiles/admin/css/nav_sidebar.css" failed (2: No 
 such file or directory), client: 172.20.0.1, server: , request: "GET 
 /staticfiles/admin/css/nav_sidebar.css HTTP/1.1", host: "127.0.0.1:1337", referrer: 
 "http://127.0.0.1:1337/admin/" 

我做错了什么?我知道请求到达了正确的位置,但由于某种原因无法从该目录做出响应

nginx 配置文件

upstream hello_django {
    server web:8000;
}
server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

     location /staticfiles/ {
        alias /home/app/web/staticfiles/;
    }
}

docker-compose.yml

version: '3.9'
services:
  web:
    build: .
    command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/home/app/web/staticfiles
    expose:
      - 8000
    env_file:
      - .env
    depends_on:
      - db
  db:
    image: postgres:12.0-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    env_file:
      - .env
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/home/app/web/staticfiles
    ports:
      - 1337:80
    depends_on:
      - web
volumes:
  postgres_data:
  static_volume:

文件

FROM python:3.10.0-alpine
WORKDIR /usr/src/app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN pip install --upgrade pip
RUN apk update
RUN apk add postgresql-dev gcc python3-dev musl-dev
COPY ./requirements.txt .
RUN pip install -r requirements.txt
COPY ./entrypoint.sh .
RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh
COPY . .
ENV HOME=/home/app
ENV APP_HOME=/home/app/web
RUN mkdir $HOME
RUN mkdir $APP_HOME
RUN mkdir $APP_HOME/staticfiles
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

入口点.sh

#!/bin/sh

if [ "$DATABASE" = "postgres" ]
then
    echo "Waiting for postgres..."

    while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do
      sleep 0.1
    done

    echo "PostgreSQL started"
fi

cd pets

exec "$@"

【问题讨论】:

    标签: django docker nginx docker-compose django-staticfiles


    【解决方案1】:

    不完全确定这是问题所在,但请删除 nginx 配置中的尾部斜杠。代替:

    location /staticfiles/ {
        alias /home/app/web/staticfiles/;
    }
    

    用这个

    location /staticfiles/ {
       alias /home/app/web/staticfiles;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 2021-10-31
      • 1970-01-01
      • 2016-02-15
      • 2023-04-11
      • 1970-01-01
      • 2019-01-22
      • 2020-11-08
      • 2013-08-08
      相关资源
      最近更新 更多