简体   繁体   中英

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

I am running an express api server inside a docker container. Now when I try to upload file using multer by setting dest param as / it gets uploaded somewhere inside docker container (most likely /dist/api/ ).

The API is running from dist so a console log of __dirname gives me /dist/api/ which is inside docker container not in real host. I need to upload the file inside /home/uploads/images/ . How can I acheive that? Maybe this is easy but I don't have a good knowledge in docker.

Docker File For API

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 Compose File

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

File Upload Code

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
})

You can map a folder of your host machine to your conatainer ,

Docker Compose File

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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