ammar26
ammar26

Reputation: 1612

Cannot find module error from docker-composer (only on windows)

We are trying to create a container running node.js, using docker (docker-compose, as we intend to add mongodb afterwards as well).

We are copying the package.json in Dockerfile and then mounting a volume in docker-compose.yml which contains the source code to be executed.

Our project structure is as follow.

Project structure

We want source folder to be mounted as volume.

Our package.json file

{
  "name": "node_package",
  "version": "1.0.0",
  "description": "node_package inside node_dir for node_service running on node_container",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node source/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.0"
  }
}

Our Dockerfile

FROM node:10-alpine
WORKDIR /node_dir
COPY package*.json ./
RUN npm install

Our docker-compose.yml

version: "3"
services:

  node_service:

     build: .

     container_name: node_container

     user: node

     working_dir: "/node_dir"

     ports:
     - "8080:3000"

     volumes:
     - ./source:/node_dir/source

     command: npm start

Now when we run this on macOS, it works. It mounts the source folder as volume and then executes command npm start. But when we try the same on windows we get the following error

Cannot find module 'node_dir/source/index.js'

Why it is working on mac but not on windows?

Here is our index.js file

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => {console.log(`Example app listening on port ${port}!`)})

When we copy source folder in Dockerfile then it works on Windows. But if we don't copy source folder in Dockerfile and mount it as volume in docker-compose.yml then command npm start does not work.

Upvotes: 1

Views: 1872

Answers (1)

Masih Jahangiri
Masih Jahangiri

Reputation: 10907

because some node module need to compile so when run npm i npm get Compatible module with OS i.e. the node_module folder in Windows is different with Mac.

best solution: isolate node_module from bind mount in docker-compose. so edit docker-compose.yml from:

volumes:
   - ./source:/node_dir/source

to:

volumes:
   - /node_dir/node_modules # isolate node_modules for compatible os
   - ./source:/node_dir/source

Upvotes: 1

Related Questions