Search code examples
dockerdocker-volume

How to avoid node_modules folder being deleted


I'm trying to create a Docker container to act as a test environment for my application. I am using the following Dockerfile:

FROM node:14.4.0-alpine
WORKDIR /test
COPY package*.json ./
RUN npm install .
CMD [ "npm", "test" ]

As you can see, it's pretty simple. I only want to install all dependencies but NOT copy the code, because I will run that container with the following command:

docker run -v `pwd`:/test -t <image-name>

But the problem is that node_modules directory is deleted when I mount the volume with -v. Any workaround to fix this?


Solution

  • When you bind mount test directory with $PWD, you container test directory will be overridden/mounted with $PWD. So you will not get your node_modules in test directory anymore. To fix this issue you can use two options.

    1. You can run npm install in separate directory like /node and mount your code in test directory and export node_path env like export NODE_PATH=/node/node_modules then Dockerfile will be like:
    FROM node:14.4.0-alpine
    WORKDIR /node
    COPY package*.json ./
    RUN npm install .
    WORKDIR /test
    CMD [ "npm", "test" ]
    
    
    1. Or you can write a entrypoint.sh script that will copy the node_modules folder to the test directory at the container runtime.
    FROM node:14.4.0-alpine
    WORKDIR /node
    COPY package*.json ./
    RUN npm install .
    WORKDIR /test
    COPY Entrypoint.sh ./
    ENTRYPOINT ["Entrypoint.sh"]
    

    and Entrypoint.sh is something like

    #!/bin/bash
    cp -r /node/node_modules /test/.
    npm test