使用 docker 和 nodeJS 构建简单应用程序时如何修复错误 "npm ERR! could not detect node name from path or package"?

How to fix error "npm ERR! could not detect node name from path or package" when building simple app with docker and nodeJS?

Docker 文件

FROM node:alpine
COPY ./ ./
RUN npm install
CMD ["npm", "start"]

index.js

const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Hi there');
});
app.listen(8080, () => {
  console.log("Listening on post 8080");
});

package.json

{
  "dependencies": {
    "express": "*"
  },
  "scripts": {
    "start": "node index.js"
  }
}

docker 构建 .

npm ERR! could not detect node name from path or package

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-11-23T23_36_35_301Z-debug.log
The command '/bin/sh -c npm install' returned a non-zero code: 1

我不明白为什么这不起作用。

设置 WORKDIR 然后将文件复制到该目录:

FROM node:alpine

WORKDIR /app
COPY ./ /app

RUN npm install
CMD ["npm", "start"]

如文档中所述:

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. If the WORKDIR doesn’t exist, it will be created even if it’s not used in any subsequent Dockerfile instruction.

npm 的 Github 回购中,提到了一个类似的错误 in this comment as part of the issue on npm not working when run outside a package directory。它似乎只与 nodenpm 的新版本有关(节点 v15.x,npm v7.0.x 作为错误报告):

Fresh install of Node 15.1.0 and npm i -g npm@7.0.9, that for some (probably unrelated) reason don't work properly.
...

24 verbose stack TypeError: could not detect node name from path or package
...
28 verbose node v15.1.0
29 verbose npm  v7.0.8
30 error could not detect node name from path or package

但是在你的情况下,你有一个package.json,所以这可能是因为build命令在没有设置适当的情况下找不到它WORKDIR。因此,不要使用 npm 解决它,只需确保始终设置 WORKDIR。无论如何,如 WORKDIR section of Docker's best practices:

中所述,推荐

For clarity and reliability, you should always use absolute paths for your WORKDIR. Also, you should use WORKDIR instead of proliferating instructions like RUN cd … && do-something, which are hard to read, troubleshoot, and maintain.