【问题标题】:Read/Write docker volume from nodejs application从 nodejs 应用程序读取/写入 docker 卷
【发布时间】:2020-01-04 20:59:18
【问题描述】:

我有 2 个应用程序。

1.后端nodejs应用

2.前端nodejs应用

两者都在 docker 容器中运行。

我的目标是从后端应用程序上传图像并从前端应用程序访问它们。我猜,在容器之间共享图像文件的唯一方法是卷。 所以我在 docker-compose 文件中创建了一个卷“资产”。但是如何从后端应用程序将数据写入卷文件夹,以及如何从前端应用程序访问卷文件夹。

预期行为

// on backend app
fs.writeFileSync("{volume_magic_path}/sample.txt", "Hey there!");

// on frontend app
fs.readFileSync("{volume_magic_path}/sample.txt", 'utf8');

docker-compose.yml

version: "3.7"
services:

  express:
    build: ./
    restart: always
    ports:
      - "5000:5000"
    volumes:
      - .:/usr/src/app

volumes:
  assets:

所以基本上,我应该为“volume_magic_path”写什么来访问卷文件夹?

【问题讨论】:

  • 您考虑过重新架构吗?共享卷无法扩展 - 拥有一个专用的“存储节点”(可以扩展到多个)似乎是更好的选择。
  • 这样的服务器会有数百台,我无法为每个服务器管理不同的存储节点
  • 这验证了我的观点!数以百计的服务器共享量是等待发生的意外。

标签: node.js docker docker-compose docker-volume


【解决方案1】:

它看起来像一个 XY 问题。前端应用程序永远不必直接访问物理文件。前端代码是在浏览器中运行的,它们没有这样的文件系统 API。访问文件的接口是HTTP。

我认为您正在寻找的是从前端上传文件,并将它们作为 HTTP 资源提供。我要这样做,您必须为文件上传和资源访问创建端点。如果您使用 Express,或者您正在使用的 HTTP 库的任何等效项来提供文件,我建议您使用 express.static()。

【讨论】:

    【解决方案2】:

    请看下面的例子,在后端或前端你已经在你的容器里写了路径location_in_the_container

    服务:

      nginx:
        build: ./nginx/
        ports:
            - 80:80
        links:
            - php
        volumes:
            - app-volume: location_in_the_container
    
    express:
        build: ./
        restart: always
        ports:
            - "5000:5000"
        volumes:
            - app-volume: location_in_the_container
    
    volumes:
        app-volume: 
    

    请替换location_in_the_container

    请查看Volume configuration reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 2017-04-24
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多