Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm install doesn't work in Docker

Tags:

npm

docker

This is my Dockerfile:

FROM node:7

RUN apt-get update && apt-get install -y --no-install-recommends \
    rubygems build-essential ruby-dev \
    && rm -rf /var/lib/apt/lists/*

RUN npm install -gq gulp bower

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app

RUN npm install

CMD ["gulp", "start:dev"]

When I build the image, the npm install command executes with little output and really quickly. I actually build it through docker-compose which does have a volume mounted - and I cannot see the node_modules folder being created on my hose. When I launch a container on this image, I can see there is no node_modules folder. I then execute npm install and things start working - it takes 2-3 minutes to install all the packages and the node_modules folder is indeed created.

What is happening here? What am I doing wrong? Why doesn't npm install work at build time, but then it works at run time?

like image 759
Jenna S Avatar asked Feb 11 '26 15:02

Jenna S


2 Answers

Also copying up the source and running npm install means that whenever the source code changes, the npm install step cache becomes invalid.

Instead, separate the steps/caches like so;

COPY package*.json ./
RUN npm install
like image 179
Oliver Caine Avatar answered Feb 14 '26 07:02

Oliver Caine


The npm install should have worked based on your Dockerfile. You can see the created files if you run the image without a mounted volume (DIRNAME: where your docker-compose.yml is located):

docker run --rm -it DIRNAME_node ls -ahl /usr/src/app

With docker build, all data is stored in the image. So, it's intended that you don't see any files created on your host.

If you mount a volume (generally in Linux, also in a Docker container), it overlays the directory. So you can't see the node_modules created in the build step.

I suggest you do your tests based on the Docker image itself and don't mount the volume. Then you have an immutable Docker image which is better for deployment.

like image 30
Dominik Avatar answered Feb 14 '26 05:02

Dominik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!