简体   繁体   中英

Docker + Nodejs Getting Error: Cannot find module “for a module that I wrote”

I am Docker beginner. I was able to implement docker for my nodejs project, but when I try to pull it I am getting the error

Error: Cannot find module 'my_db' 

(my_db is a module that I wrote that handles my mysql functionality).

So I am guessing my modules are not bundled into the docker image, right? I moved my modules to a folder name my_node_modules/ so they won't be ignored. I also modified the Dockerfile as follow:

FROM node:11.10.1
ENV NODE_ENV production
WORKDIR /usr/src/app
COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./my_node_modules/*", "./"]
RUN npm install --production --silent && mv node_modules ../
COPY . .
EXPOSE 3000
CMD node index.js

What am I missing?

Thanks

I would do something like this. First create a .dockerignore :

.git
node_modules

The above ensures that the node_modules folder is excluded from the actual build context.

You should add any temporary things to your .dockerignore . This will also speed up the actual build, since the build context will be smaller.

In my docker file I would then first only copy package.json and any existing lock file in order to be able to cache this layer:

FROM node:11.10.1
ENV NODE_ENV production
WORKDIR /usr/src/app
# Only copy package* before installing to make better use of cache
COPY package*.json .
RUN npm install --production --silent
# Copy everything
COPY . .
EXPOSE 3000
CMD node index.js

Like I also wrote in my comment, I have no idea why you are doing this mv node_modules ../ ? This will move the node_modules directory out from the /usr/src/app folder, which is not what you want.

It would also be nice to see how you are actually including your module.

If you own module resides in the following folder my_node_modules/my_db it will be copied when doing COPY . . COPY . . in the above docker file. Then in your index.js file you should be able to use the module like this:

const db = require('./my_node_modules/my_db');

COPY . . this step will override everything in the current directory and copying node modules from Host is not recommended and maybe it breaks the container in case of host biners compiled for Window and you are using Linux container.

So better to refactor your Dockerfile and install modules inside docker instead of copying from the host.

FROM node:11.10.1
ENV NODE_ENV production
WORKDIR /usr/src/app
COPY . .
RUN npm install --production --silent
EXPOSE 3000
CMD node index.js

Also will suggest using .dockerignore

# add git-ignore syntax here of things you don't want copied into docker image

.git
*Dockerfile*
*docker-compose*
node_modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM