1

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?

Antonio Gamiz Delgado
  • 1,871
  • 1
  • 12
  • 33

2 Answers2

1

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
Taybur Rahman
  • 1,347
  • 8
  • 20
0

Approach 1

A workaround is you can do

CMD npm install && npm run dev

Approach 2

Have docker install node_modules on docker-compose build and run the app on docker-compose up.

Folder Structure

enter image description here

docker-compose.yml

version: '3.5'
services: 
  api:
    container_name: /$CONTAINER_FOLDER    
    build: ./$LOCAL_FOLDER
    hostname: api
    volumes:
      # map local to remote folder, exclude node_modules
      - ./$LOCAL_FOLDER:/$CONTAINER_FOLDER
      - /$CONTAINER_FOLDER/node_modules
    expose:
      - 88

Dockerfile

FROM node:14.4.0-alpine

WORKDIR /test
COPY ./package.json .
RUN npm install 

# run command
CMD npm run dev
Ashok
  • 3,190
  • 15
  • 31