首页 > 解决方案 > Docker-compose - 如何将容器数据填充到另一个容器?

问题描述

我的 docker-compose 文件如下:

version: '3'

services:
  database:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: qwerty
      POSTGRES_USER: qwerty

  backend:
    depends_on:
      - database
    build:
      #Dockerfile used here will use python image,build the django project and run using uwsgi in port 4000
      context: .
      dockerfile: dockerfile_uwsgi
    ports:
      - "4000:4000"
    image: backend_img
    environment:
      DB_HOST: database
      DB_NAME: qwerty
      DB_USER: qwerty
      DB_PASSWORD: qwerty

  migration:
    depends_on:
      - backend
    image: backend_img
    entrypoint: ["sh", "-c"]
    command: ["
      python manage.py collectstatic --noinput;
      python manage.py makemigrations;
      python manage.py migrate;"]
    environment:
      DB_HOST: database
      DB_NAME: qwerty
      DB_USER: qwerty
      DB_PASSWORD: qwerty

  frontend:
    depends_on:
      - backend
    build:
      #The dockerfile used her uses nginx image, it is configured to act as reverse proxy and serve static files.
      context: .
      dockerfile: dockerfile_nginx
    ports:
      - "9443:8443"


说明docker-compose.yaml:这里后端容器设置django项目并使用uwsgi为项目提供服务,迁移容器使用相同的图像将从所有应用程序目录中收集静态文件并将其填充到容器的当前工作目录中。前端容器是一个 nginx,它充当反向代理。我也想从 nginx 容器中提供静态文件。

我在这里面临的问题是,我希望迁移容器创建的静态文件出现在前端容器中。这样 nginx 就可以提供静态文件了。这怎么可能做到?如果假设设计不应该是这里显示的方式,请建议我如何重新设计以达到要求?

我知道使用共享卷可以做到这一点。但是我不想使用共享卷,因为填充到共享卷中的数据将保留在其中,并且假设如果开发人员修改了应用程序文件夹中的静态内容,则更改不会填充到卷中,除非卷挂载点被刷新. 这是基于我观察到的,如果我错了,请纠正我。

标签: djangodockernginxdocker-composeuwsgi

解决方案


无论在 docker 层为您的资源提供什么服务——gunicorn、uwsgi 等等——都可能支持服务静态资产,并且可以比 django 本身更有效地完成它。

在您的情况下,nginx本质上是您的应用程序之外的。与其尝试“将您的静态资产放入 nginx”,不如让客户端完成这项工作,并在代理后将它们缓存在 nginx 中。Nginx 有很好的缓存支持。

If you really want to get the static assets into a , you can COPY --from=... like in a https://docs.docker.com/develop/develop-images/multistage-build/ to copy the static assets into your custom nginx container. Use the django container as the source - you'll have to make sure its built after your django container. This may not be possible completely within docker-compose. There's legitimate friction there; you'll have the same friction when/if you try to build and deploy docker artifacts to production servers.


推荐阅读