繁体   English   中英

如何在节点 js docker 容器外(即在 linux 主机内)保存上传的文件?

[英]How to save uploaded files outside node js docker container (i.e. inside linux host machine)?

我在 docker 容器内运行一个快速的 api 服务器。 现在,当我尝试使用multer上传文件时,将dest参数设置为/multer容器内的某处(很可能是/dist/api/ )。

API 是从 dist 运行的,所以__dirname的控制台日志给了我/dist/api/它在 docker 容器内而不是在真实主机中。 我需要将文件上传到/home/uploads/images/ 我怎样才能做到这一点? 也许这很容易,但我对 docker 没有很好的了解。

API 的 Docker 文件

FROM node:8.10

# Set a timezone
ENV TZ=UTC
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

COPY . .  
RUN yarn install  
RUN yarn run build  
CMD node dist  

HEALTHCHECK --interval=5s --timeout=30s --retries=50 \
CMD curl -f localhost:8080/api || exit 1  

Docker 撰写文件

webapi: depends_on: serviceapi: condition: service_healthy restart: always networks: - internal_network build: ./api/ expose: - "8080" ports: - "8080:8080"

文件上传代码

var storage = multer.diskStorage({
      destination: function (req, file, cb) {
         cb(null, '/home/uploads/images/')
     },
     filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

var upload = multer({ storage: storage })

app.post('/profile', upload.any(), function (req, res, next) {  
     //logic goes over here
})

您可以将主机的文件夹映射到容器,

Docker 撰写文件

webapi:
    depends_on:
      serviceapi:
        condition: service_healthy
    restart: always
    networks:
      - internal_network
    build: ./api/
    volumes:
      - "/home/uploads/images/:/folder/in/container"
    expose:
      - "8080"
    ports:
      - "8080:8080"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM