Search code examples
node.jsdockerdocker-composedocker-volume

node js docker-compose volume empty


I've written an app that download some images to a folder called storage in src/storage path. everything works great in development mode (without container) and in production mode (container) it works but the volume will be empty.

docker-compose:

version: "3.2"

services:
  app:
    build: .
    volumes:
      - ./storage-data:/src/storage
    depends_on:
      - db
    env_file:
      - prod.env
    networks:
      - app_network

networks:
  app_network:

Dockerfile:

FROM node:14
WORKDIR /usr/src/app
COPY package.json yarn.lock ./

RUN npm install

COPY ./src .

CMD [ "node", "app.js" ]

and this is my download function:

const { createWriteStream } = require("fs");
const { pipeline } = require("stream");
const { promisify } = require("util");
const fetch = require("node-fetch");

const download = async ({ url, path }) => {
  const streamPipeline = promisify(pipeline);
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`unexpected response ${response.statusText}`);
  }

  await streamPipeline(response.body, createWriteStream(path));
};

module.exports = download;

and finally the code:

    for (const [i, product] of products.entries()) {
      const { thumbnail, name } = product;
      const ext = thumbnail.slice(thumbnail.lastIndexOf("."));
      const filePath = `${path.join(__dirname, "../storage")}/${
        brand.text
      }-${slugify(name)}-thumbnail${ext}`;

      try {
        await download({
          url: thumbnail,
          path: filePath,
        });
        products[i].thumbnail = filePath.slice(filePath.indexOf("src"));

        logger.info(`"${name}" thumbnail saved to ${filePath}`);
      } catch (error) {
        logger.error(error);
      }
    }

as I said, it downloads files in container but volume folder is empty and there is no error.

if I check docker container with docker exec i can see downloaded files.


Solution

  • Update:

    You need to mount the volume to the absolute path you see when you execute pwd from a terminal within the container in the images directory.


    You need to change your docker-compose file's volumes like below:

    volumes:
          - ./storage-data:/usr/src/app/src/storage