Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Installing npm dependencies inside docker and testing from volume

I want to use Docker to create development environments for a simple node.js project. I'd like to install my project's dependencies (they are all npm packages) inside the docker container (so they won't touch my host) and still mount my code using a volume. So, the container should be able to find the node_modules folder at the path where I mount the volume, but I should not see it from the host.

This is my Dockerfile:

FROM node:6


RUN mkdir /code
COPY package.json /code/package.json
WORKDIR /code

RUN npm install

This is how I run it:

docker build --tag my-dev-env .

docker run --rm --interactive --tty --volume $(pwd):/code my-dev-env npm test

And this is my package.json:

  {
    "private": true,
    "name": "my-project",
    "version": "0.0.0",
    "description": "My project",
    "scripts": {
      "test": "jasmine"
    },
    "devDependencies": {
      "jasmine": "2.4"
    },
    "license": "MIT"
  }

It fails because it can't find jasmine, so it's not really installing it:

> jasmine

sh: 1: jasmine: not found

Can what I want be accomplished with Docker? An alternative would be to install the packages globally. I also tried npm install -g to no avail.

I'm on Debian with Docker version 1.12.1, build 23cf638.

like image 717
Randy Eels Avatar asked Aug 22 '16 19:08

Randy Eels


1 Answers

The solution is to also declare /code/node_modules as a volume, only without bind-mounting it to any directory in the host. Like this:

docker run --rm --interactive --tty --volume /code/node_modules --volume $(pwd):/code my-dev-env npm test

As indicated by @JesusRT, npm install was working just fine but bind-mounting $(pwd) to /code alone was shadowing the existing contents of /code in the image. We can recover whatever we want from /code in the container by declaring it as a data volume -- in this case, just /code/node_modules, as shown above.

A very similar problem is already discussed in Docker-compose: node_modules not present in a volume after npm install succeeds.

like image 89
Randy Eels Avatar answered Nov 01 '22 19:11

Randy Eels