gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:37:27 24 4
gpt4 key购买 nike

文件

FROM node:alpine
COPY ./ ./
RUN npm install
CMD ["npm", "start"]
索引.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");
});
包.json
{
"dependencies": {
"express": "*"
},
"scripts": {
"start": "node index.js"
}
}
docker build 。
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 repo,提到了类似的错误 in this comment作为问题的一部分 npm not working when run outside a package directory .它似乎只与 node 的新版本有关和 npm (节点 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.

关于docker - 使用 docker 和 nodeJS 构建简单应用程序时如何修复错误 "npm ERR! could not detect node name from path or package"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64978200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com