docker 容器中的运行时错误,找不到模块

Runtime error in docker container, Module not found

对于新手问题,我很抱歉,但我一直在解决这个错误,我有一个 Express 应用程序,我正在尝试 运行 它作为一个 docker 容器。我用过这个 Dockerfile:

FROM node:14.17.0-alpine
COPY /src /nodejs
WORKDIR /nodejs
ADD package*.json ./
RUN npm install

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

这是我的 package.js 文件:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js -e js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "express-rate-limit": "^5.1.3",
    "nodemon": "^2.0.3",
    "prom-client": "^12.0.0",
    "puppeteer": "^10.4.0"
  }
}

我正在使用 windows 10,我用来部署容器的命令是:

docker run --name express-api -d -p 4000:4000 docker-express-app

执行上述命令后得到的错误,在power shell:

internal/modules/cjs/loader.js:888

  throw err;

  ^


Error: Cannot find module '/nodejs/app.js'

    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15)

    at Function.Module._load (internal/modules/cjs/loader.js:730:27)

    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)

    at internal/main/run_main_module.js:17:47 {

  code: 'MODULE_NOT_FOUND',

  requireStack: []

}

对这个问题的任何想法表示赞赏。

P.S:我的项目层次结构是这样的:

https://i.stack.imgur.com/ptlkI.png

您没有在容器中复制 app.js 文件。

WORKDIR /nodejs
COPY src .
COPY app.js .
ADD package*.json ./
RUN npm install

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

这应该可以解决问题。

我认为更简单的方法可能是制作一个 dockerignore file and copy everything. Another problem is that you're using ADD instead of COPY. You just need to copy your files in the container and I think COPY would suffice as ADD has some extra functionality 这可能会造成混淆。