通过 Nginx 提供 Django 媒体文件(Django/React/Nginx/Docker-Compose)

通过 Nginx 提供 Django 媒体文件(Django/React/Nginx/Docker-Compose)

语境

我有一个使用以下堆栈的单页网络应用程序:

  • React 用于前端
  • Django 作为后端
  • Nginx 用于 Web 服务器

Web 应用程序使用 dockerized docker-compose。我的 React 应用程序从 Django 服务器获取数据(django 使用 Django Rest Framework 构建为 api 端点)。

疑问/问题

我在部署时遇到问题,无法通过 Nginx 提供媒体文件。

到目前为止我尝试过什么

我最初的想法是提供媒体文件,如 stackoverflow 上所示邮政- 这很简单。但是,由于 Nginx 在自己的 docker 中运行(我的 django 服务器也是如此),我无法指向我的 django 媒体文件,因为它们位于不同的容器中。

理想情况下,我不想使用 webpack,而是让 Nginx 负责提供媒体文件。

如果您查看下面的 nginx Dockerfile,您将看到我正在将静态文件复制到 nginx 中,/usr/share/nginx/html/static/staticfiles然后使用 nginx 提供它们(参见location ^~ /static/nginx.conf。我尝试对我的媒体文件执行相同的操作(作为测试),并且成功了 - 但是,网站启动后我上传的所有文件都无法访问,因为复制发生在我构建容器时。

文件结构

Root Dirc  
 |__ docker-compose.yml  
 |__ backend  
      |__ root  
           |__ Project
                |__ api
                     |__ models.py
                     |__ ...
                |__ media
           |__ teddycrepineau
                |__ settings.py
                |__ ...
           |__ production
                |__ Dockerfile
 |__ nginx
      |__ Dockerfile
      |__ nginx.conf
 |__ frontend
      |__ ...

相关代码

docker-compose.yml

version: '3'

volumes:
  postgres_data: {}
  postgres_backup: {}

services:
  postgres:
    image: postgres
    volumes: 
      - postgres_data:/var/lib/postgresql/data
      - postgres_backup:/backups
    env_file: .env

  nginx:
    container_name: nginx
    build:
      context: .
      dockerfile: ./nginx/Dockerfile
    image: nginx
    restart: always
    depends_on: 
      - django
    ports:
      - "80:80"

  django:
    container_name: django
    build:
      context: backend
      dockerfile: ./root/production/Dockerfile
    hostname: django
    ports:
      - 8000:8000
    volumes:
      - ./backend:/app/
    depends_on: 
      - postgres
    command: >
      bash -c '
      python3 ./root/manage.py makemigrations &&
      python3 ./root/manage.py migrate &&
      python3 ./root/manage.py initadmin &&
      gunicorn teddycrepineau.wsgi -b 0.0.0.0:8000 --chdir=./root/'

    env_file: .env

nginx.conf

user nginx;
worker_processes 1;

error_log   /var/log/nginx/error.log warn;
pid         /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include         /etc/nginx/mime.types;
    default_type    application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log      /var/log/nginx/access.log main;

    upstream app {
        server django:8000;
    }

    server {
        listen  80 default_server;
        listen  [::]:80 default_server;
        server_name 0.0.0.0;
        charset utf-80;

        root /usr/share/nginx/html;
        index index.html;

        location / {
            try_files $uri $uri/ @proxy_to_app;
        }

        location @proxy_to_app {
            rewrite ^(.+)$ /index.html last;
        }

        location ^~ /static/ {
            autoindex on;
            alias /usr/share/nginx/html/static/;
        }

        location ~ ^/api {
            proxy_pass http://django:8000;
        }
        location ~ ^/admin {
            proxy_pass http://django:8000;
        }
    }
}

nginx Dockerfile

FROM nginx:latest
ADD ./nginx/nginx.conf /etc/nginx/nginx.conf
COPY ./frontend/build /usr/share/nginx/html
COPY ./backend/root/staticfiles /usr/share/nginx/html/static/staticfiles

Django Dockerfile

FROM python:3.7

ENV PYTHONUNBUFFERED 1

RUN export DEBIAN_FRONTEND=noninteractive

RUN mkdir /app

RUN pip install --upgrade pip
ADD /root/requirements.txt /app/

WORKDIR /app/
ADD . /app/

RUN pip install -r requirements.txt

EXPOSE 8000

Django 设置.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
APPS_DIR = os.path.join(BASE_DIR, 'project')
....
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(APPS_DIR, 'media/')

Django urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^api/', include('project.api.urls')),
    path('summernote/', include('django_summernote.urls')),
] 
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


更新

当我安装共享卷并在我的卷中引用它时,尝试访问 django 后端上传的图像时nginx.conf出现问题。404 page not found

docker-compose.yml

version: '3'

volumes:
  postgres_data: {}
  postgres_backup: {}

services:
  postgres:
    image: postgres
    volumes: 
      - postgres_data:/var/lib/postgresql/data
      - postgres_backup:/backups
    env_file: .env

  nginx:
    container_name: nginx
    build:
      context: .
      dockerfile: ./nginx/Dockerfile
    image: nginx
    restart: always
    depends_on: 
      - django
    ports:
      - "80:80"
    volumes:
      - ./static:/app/backend/root/staticfiles
      - ./media:/app/backend/root/project/media

  django:
    container_name: django
    build:
      context: backend
      dockerfile: ./root/production/Dockerfile
    hostname: django
    ports:
      - 8000:8000
    volumes:
      - ./backend:/app/
      - ./static:/app/backend/root/staticfiles
      - ./media:/app/backend/root/project/media
    depends_on: 
      - postgres
    command: >
      bash -c '
      python3 ./root/manage.py collectstatic --no-input &&
      python3 ./root/manage.py makemigrations &&
      python3 ./root/manage.py migrate &&
      python3 ./root/manage.py initadmin &&
      gunicorn teddycrepineau.wsgi -b 0.0.0.0:8000 --chdir=./root/'

    env_file: .env 

nginx.conf

user nginx;
worker_processes 1;

error_log   /var/log/nginx/error.log warn;
pid         /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include         /etc/nginx/mime.types;
    default_type    application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log      /var/log/nginx/access.log main;

    upstream app {
        server django:8000;
    }

    server {
        listen  80 default_server;
        listen  [::]:80 default_server;
        server_name localhost;
        charset utf-80;

        root /usr/share/nginx/html;
        index index.html;

        location / {
            try_files $uri $uri/ @proxy_to_app;
        }

        location @proxy_to_app {
            rewrite ^(.+)$ /index.html last;
        }

        location ^~ /static/ {
            autoindex on;
            alias /usr/share/nginx/html/static/;
        }

        location ^~ /media/ {
            autoindex on;
            alias /app/backend/root/project/media/;
        }

        location ~ ^/api {
            proxy_pass http://django:8000;
        }
        location ~ ^/admin {
            proxy_pass http://django:8000;
        }
    }
}

答案1

如果此问题仅发生在 Django 中,您可以尝试更改静态文件格式 -

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

一般来说,当我们进行生产时,静态文件会出现一些问题,所以它可能会有所帮助!

文档可以帮助 !

相关内容