【问题标题】:How to copy some data from one container to another container by docker-compose.yml如何通过 docker-compose.yml 将一些数据从一个容器复制到另一个容器
【发布时间】:2020-01-16 09:30:42
【问题描述】:

现在我正在开发一个 React 应用程序。对于部署,我想使用 nginx 作为 Web 服务器。我编写了一个包含两个服务的 docker-compose 文件(一个用于 React 应用程序,另一个用于 nginx 网络服务器)。通常 nginx 服务只需要 react 项目中的 'build' 文件夹。

现在我的问题是如何在反应容器运行时将“构建”文件夹从反应容器复制到 nginx 容器目录。

请查看 Dockerfiles 和 yaml 文件。

docker-compose.yaml

version: "3"
services:
  nginx-server:    
    image: nginx_server:dev
    container_name: nginx
    build:
      context: ./nginx
      dockerfile: Dockerfile
    restart: always   

    command: >
      sh -c "cp -R /build/ /var/www/html/"   // I want to do something like that


    volumes:
      - .:/react_app_server/nginx

    ports:
      - 80:80
    depends_on:
      - react-app
    networks:
      - server_network


  react-app:
    container_name: my_react_app
    build:
      context: .
      dockerfile: ./Dockerfile
    image: my_react_app:dev 
    tty: true
    volumes:
      - .:/react_app
    ports:
      - "1109:1109"
    networks:
      - frontend_network
    command: >
      bash -c "npm run-script build"

networks:
  frontend_network:
    driver: bridge
  server_network:
    driver: bridge


volumes:
  static-volume:

用于 React 应用的 Dockerfile

FROM node:10.16.3
RUN mkdir /app
WORKDIR /app
COPY . /app
ENV PATH /app/node_modules/.bin:$PATH
RUN npm install --silent
RUN npm install react-scripts@3.0.1 -g --silent
RUN npm run-script build

适用于 Nginx 的 Dockerfile

FROM nginx:1.16.1-alpine
RUN rm /etc/nginx/conf.d/default.conf
COPY /prod.conf /etc/nginx/conf.d

项目目录

My_React_App
    build
    nginx
        Dockerfile
        prod.conf
    node_modules
    public
    src
    .dockerignore
    docker-compose.yaml
    Dockerfile
    package-lock.json
    package.json
    README.md

【问题讨论】:

    标签: reactjs docker nginx docker-compose docker-volume


    【解决方案1】:

    您实际上不需要复制数据,而是使用相同的卷应该可以工作。

    您需要在两个容器之间共享一个named volume

    您的docker-compose.yaml 应该是:

    version: "3"
    services:
      nginx-server:    
        image: nginx_server:dev
        container_name: nginx
        |
        |
        volumes:
          - .:/react_app_server/nginx
          - app-volume:/var/www/html/
        |
        |
      react-app:
        container_name: my_react_app
        build:
          context: .
        |
        |
        volumes:
          - .:/react_app
          - app-volume:/path/to/build/folder/
        |
        |
    

    注意:这里app-volume 是一个命名卷,我们将其挂载在react-app 容器内的目录中,预计将在该目录中创建构建文件夹。相同的 app-volume 命名卷也安装在 nginx 容器中 /var/www/html/ 您希望复制构建文件夹的位置。

    除了命名卷,您还可以在两个容器中挂载相同的主机目录并共享数据。 -v /samepath/on/host:/path/to/build/folder-v /samepath/on/host:/var/www/html

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 2015-07-16
      • 1970-01-01
      相关资源
      最近更新 更多