Docker + NodeJS: node_modules not the same between docker-compose up and docker-compose run

Viewed 232

I am trying to dockerize a simple node js app for development purposes. To do so I created a simple Dockerfile:

FROM node:15-alpine

# Code folder inside Docker
RUN mkdir /code
WORKDIR /code


# Install deps before mounting volume to improve caching
COPY package*.json ./
RUN npm install

# No need to copy code, we are building a volume later
EXPOSE 1234

As well as two (very similar) docker-compose.yml files, one for testing and the other for running the app in dev mode.

version: "3.1"
services:
  db:
    image: mongo:4
    environment:
      MONGO_INITDB_ROOT_USERNAME: my-user
      MONGO_INITDB_ROOT_PASSWORD: my-pswd
      MONGO_INITDB_DATABASE: my-db

  app:
    environment:
      - NODE_ENV=development
    depends_on:
      - "db"
    build: .
    ports:
      - "1234:1234"
    env_file: ./.docker.env
    command: npm run dev
    volumes:
      - .:/code
      - /code/node_modules

The problem is that whenever i launch docker-compose up, npm run dev which is just pointing to nodemon index.js fails because the nodemon packaage is not installed.

Whenever i launch docker-compose run app it runs without any issues. As well as docker-compose run app sh which allows me to launch npm run dev without any issues.

Both docker-compose.yml and docker-compose.test.yml have NODE_ENV=development, and the test file also launches a command from node_modules (mocha to be exact`).

Note that this behaviour appeared once i migrated from node:15 to node:15-alpine.

I would be very grateful if anyone has any idea why.

1 Answers

Can you please try mapping your node_modules like so:

volumes:
  - .:/code
  - node_modules:/code/node_modules

Alternatively, try building again but first clearing your cache with:

docker-compose build --no-cache

then running docker-compose up

Related