【问题标题】:MODULE_NOT_FOUND error in Docker-Swarm for NodeJS ApplicationNodeJS 应用程序的 Docker-Swarm 中的 MODULE_NOT_FOUND 错误
【发布时间】:2020-04-12 19:15:46
【问题描述】:

我在 NodeJS 中编写了一个简单的 Hello World 应用程序,并尝试将其部署在单节点 Docker-Swarm 集群上。 但是,在(一个)主节点上,命令

docker service create --with-registry-auth --name test-backend --env APP_HOST=0.0.0.0 --env APP_PORT=3000 --network custom-overlay-net registry.example.com/<user>/<image>:latest test-backend

产生以下错误:

internal/modules/cjs/loader.js:985
   throw err;
   ^

 Error: Cannot find module '/home/node/test-backend'
     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:982:15)
     at Function.Module._load (internal/modules/cjs/loader.js:864:27)
     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
     at internal/main/run_main_module.js:18:47 {
   code: 'MODULE_NOT_FOUND',
   requireStack: []
 }

我想知道的是,当我将映像作为独立的 docker 容器或通过 docker-compose 运行时,一切都按预期运行。 另外,当我用--entrypoint "/bin/bash -c \"node ./index.js\"" 覆盖“docker service create”命令中的入口点时,一切正常。

index.js 的内容:

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});
if (!process.env.APP_HOST) {
        console.error('Please specify the APP_HOST environment variable');
}

if (!process.env.APP_PORT) {
    console.error('Please specify the APP_PORT environment variable');
}

server.listen(parseInt(process.env.APP_PORT), process.env.APP_HOST, () => {
  console.log(`Server running at http://${process.env.APP_HOST}:${process.env.APP_PORT}/`);
});

Dockerfile 的内容:

FROM node:12.16.1

WORKDIR /home/node/

# copy all resources
COPY . .

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

文件结构:

  • index.js
  • Dockerfile
  • package.json

当然,我可以简单地覆盖入口点以使事情正常运行,但我想了解为什么使用默认入口点脚本会导致问题。

感谢您的帮助!提前致谢。

【问题讨论】:

  • test-backend 对应什么?它是你项目的一部分吗?
  • 这是 npm 项目和容器的名称,所以没什么特别的。

标签: node.js docker docker-compose docker-swarm


【解决方案1】:

您不需要test-backend 作为参数,因为您已经使用--name 指定了服务。

以下就足够了:

docker service create --with-registry-auth --name test-backend --env APP_HOST=0.0.0.0 --env APP_PORT=3000 --network custom-overlay-net registry.example.com/<user>/<image>:latest

注意:正如@Dmytro Sirant 指出的那样,当附加test-backend 时 - 将其视为CMD ["test-backend"],这将导致上述错误。

【讨论】:

  • 只是更多的信息发生了什么。命令中的最后一个“test-backend”转换为 CMD,而不是从 Dockerfile 运行 CMD,而是运行您在 FROM 中使用 CMD ["test-backend"] 使用的映像的 ENTRYPOINT
  • 感谢您的解释 - 这很有效。没想到答案这么简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 2018-12-05
  • 2023-02-03
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多