在 docker 中运行 Node Express 服务器时出错

问题描述 投票:0回答:1

节点:内部/模块/cjs/loader:1148抛出错误; ^ 错误:在 Module._resolveFilename (node:internal/modules/cjs/loader:1145:15) 和 Module._load (node:internal/modules/cjs/loader:986) 处找不到模块“/app/index.js”: 27) 在 Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12) 在 node:internal/main/run_main_module:28:49 { code: 'MODULE_NOT_FOUND', requireStack: [] }

运行 Express 服务器的 docker 镜像时出现上述错误

在 docker 文件中尝试使用 npm install express,下面是我的 docker 文件

# 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"]

我已经检查了我的目录index.js文件是否放置正确

node.js docker express dockerfile docker-machine
1个回答
0
投票

您收到错误的原因是您必须在运行应用程序之前安装所有模块依赖项。为此,我们必须在 package.json 中安装所有可用模块。在常规的开发环境中,我们可以通过运行命令轻松完成此操作:

npm install
(简称
npm i

因此,要在构建 docker 映像时执行相同的操作,我们只需在应用程序执行命令之前添加命令

RUN npm install
即可。 (即
CMD ["node", "index.js"]
)。更新后的 Dockerfile 看起来像这样。

FROM node:20

WORKDIR /app

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

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

P.S:始终确保构建映像的工作目录是包含 package.json 的目录。否则会产生错误。

© www.soinside.com 2019 - 2024. All rights reserved.