Nginx 和 Gunicorn 静态文件在我的 docker-compose django 项目中找不到,即使日志显示“125 个静态文件复制到”/app/static”

问题描述 投票:0回答:1

我已经设置了 nginx 文件夹、Dockerfile、.env、docker-compose.yml 和 entrypoint.sh 文件,一切都运行正常,我能够看到应有的页面。但唯一的问题是我无法加载静态文件。

gunicorn
容器日志正在显示

“未找到”并且 nginx 容器显示失败(2:没有这样的文件 或目录)。

这些是我的配置文件:

docker-compose.yml

version: '3'

services:
  marathon_gunicorn:
    volumes:
      - static:/static
    env_file:
      - .env
    build: 
      context: .
    ports:
      - "8010:8000"
      
  nginx:
    build: ./nginx
    volumes:
      - static:/static
    ports:
      - "8012:80"
    depends_on:
      - marathon_gunicorn

  db:
    image: postgres:15
    container_name: postgres_db
    restart: always
    environment:
      POSTGRES_DB: xxx
      POSTGRES_USER: xxx
      POSTGRES_PASSWORD: xxx
    volumes:
      - pg_data:/var/lib/postgresql/data

volumes:
  static:
  pg_data:`

入口点.sh

#!/bin/sh

# Apply database migrations
python manage.py migrate --no-input

# Collect static files
python manage.py collectstatic --no-input

# Start Gunicorn server
gunicorn absamarathon.wsgi:application --bind 0.0.0.0:8000

Django Dockerfile

FROM python:3.8

RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt

COPY ./absamarathon /app

WORKDIR /app

COPY ./entrypoint.sh /
ENTRYPOINT [ "sh", "/entrypoint.sh" ]

nginx/default.conf

upstream django {
    server marathon_gunicorn:8000;
}

server {
    listen 80;

    location / {
        proxy_pass http://django;
    }

    location /static/ {
    alias /static/;
}

    # location /media/ {
    #     alias /app/media/;
    # }
}

设置.py

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
django nginx docker-compose static gunicorn
1个回答
0
投票

你的ngix配置不正确,因为它不能正确处理静态,因为你没有告诉nginx服务器/static的文件夹在哪里。您应将

/static/
放在
/
上方,以便它首先匹配。

server {
     listen 80;

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

     location / {
        proxy_pass http://django;
      }

}

© www.soinside.com 2019 - 2024. All rights reserved.