1

node:internal/modules/cjs/loader:1148 throw err; ^ Error: Cannot find module '/app/index.js' at Module._resolveFilename (node:internal/modules/cjs/loader:1145:15) at Module._load (node:internal/modules/cjs/loader:986:27) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12) at node:internal/main/run_main_module:28:49 { code: 'MODULE_NOT_FOUND', requireStack: [] }

getting above error while running docker image of express server

tried with npm install express in docker file below is my docker file

# Use an official Node.js runtime as a parent image
FROM node:20

# Set the working directory in the container
WORKDIR /app

# Copy the package.json and package-lock.json files
COPY package*.json ./

# Install dependencies
RUN npm install express

# Copy the rest of the application code
COPY . .

# Expose the port the app runs on
EXPOSE 5000

# Command to run the application
CMD ["node", "index.js"]

i have checked my directory index.js file is properly placed

6
  • 1
    How are you running the container? For Node in particular, many common setups overwrite absolutely everything in the container with volume mounts, which can result in unpredictable problems like this; try removing a docker run -v or Compose volumes: block if you have one. Commented Jul 4, 2024 at 11:09
  • Hello @DavidMaze.. currently i am not using any volume or compose still facing such issues.. any solution for that ? Commented Jul 4, 2024 at 14:14
  • Try RUN npm i before the second copy command Commented Jul 4, 2024 at 17:08
  • still same error @LNTR Commented Jul 5, 2024 at 5:06
  • 1
    i have added COPY ./src . just after RUN npm i and guess what, it worked thanks for the response everyone. Commented Jul 5, 2024 at 8:41

1 Answer 1

0

The reason you're getting an error is because you have to install all the module dependencies before running the application. To do this, we have to install all available modules in package.json . In a regular development environment, we can easily accomplish this by running the command:

npm install ( npm i for short )

So, to do the same thing when building a docker image, we can simply add the command RUN npm install just before the application execution command. (I.E CMD ["node", "index.js"]). The updated Dockerfile then looks something like this.

FROM node:20

WORKDIR /app

COPY package*.json ./
COPY . .
EXPOSE 5000
RUN npm i

CMD ["node", "index.js"]

P.S : Always make sure the working directory that you build your image from is the one that contains the package.json. Otherwise it will produce an error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.