Docker 未将 Django 媒体文件保存到项目 'media' 生产目录中

Docker is not saving django media files into project 'media' directory on production

应用说明


我有一个应用程序,后端使用 django-gunicorn,前端使用 reactjs-nginx,全部容器化并托管在 aws ec2 实例上。

问题


在开发环境中,媒体文件永久保存在'media'目录中。不过,这些文件仅在生产时保存在当前 运行 docker 容器中。因此,当我 rebuild/stopped 新代码推送的容器时,这些文件将被删除。

预期


我想将文件存储在 'media' 文件夹中以供永久使用。

重要代码


settings.py

ENV_PATH = Path(__file__).resolve().parent.parent
STATIC_ROOT = BASE_DIR / 'django_static'
STATIC_URL = '/django_static/'

MEDIA_ROOT = BASE_DIR / 'media/'

MEDIA_URL = '/media/'

docker-撰写-production.yml

version: "3.3"

services:
    db:
       image: postgres
       restart: always #Prevent postgres from stopping the container
        volumes:
               - ./data/db:/var/lib/postgresql/data
        environment:
                 - POSTGRES_DB=postgres
                 - POSTGRES_USER=postgres
                 - POSTGRES_PASSWORD=postgres
    ports:
        - 5432:5432

nginx:
    restart: unless-stopped
    build:
        context: .
        dockerfile: ./docker/nginx/Dockerfile
    ports:
        - 80:80
        - 443:443
    volumes:
        - static_volume:/code/backend/server/django_static
        - ./docker/nginx/production:/etc/nginx/conf.d
        - ./docker/nginx/certbot/conf:/etc/letsencrypt
        - ./docker/nginx/certbot/www:/var/www/certbot
    depends_on:
        - backend

# Volume for certificate renewal
certbot:
    image: certbot/certbot
    restart: unless-stopped
    volumes:
        - ./docker/nginx/certbot/conf:/etc/letsencrypt
        - ./docker/nginx/certbot/www:/var/www/certbot
    entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
backend:
    restart: unless-stopped
    build:
        context: .
        dockerfile: ./docker/backend/Dockerfile

    entrypoint: /code/docker/backend/wsgi-entrypoint.sh
    volumes:
        - .:/code
        - static_volume:/code/backend/server/django_static
    expose:
        - 8000
    depends_on:
        -   db

volumes:
       static_volume: { }
       pgdata: { }

我终于弄明白了。我忘记在我的 docker-compose 文件中将 .:/code 添加到我的 nginx 卷配置中。 Thank to this answer

更新了 nginx 卷 conf

        volumes:
        - .:/code
        - static_volume:/code/backend/server/django_static
        - ./docker/nginx/production:/etc/nginx/conf.d
        - ./docker/nginx/certbot/conf:/etc/letsencrypt
        - ./docker/nginx/certbot/www:/var/www/certbot