节点在dockerized node app中找不到node_modules

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

我是码头工人的新手。我试图将现有节点应用程序停靠。在docker-compose期间,应用程序抛出错误,指出它无法找到node_modules。

这是错误

dockerised-yelpcamp | > [email protected] start /usr/src/app
dockerised-yelpcamp | > node app.js
dockerised-yelpcamp | 
dockerised-yelpcamp | internal/modules/cjs/loader.js:584
dockerised-yelpcamp |     throw err;
dockerised-yelpcamp |     ^
dockerised-yelpcamp | 
dockerised-yelpcamp | Error: Cannot find module 'express'
dockerised-yelpcamp |     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
dockerised-yelpcamp |     at Function.Module._load (internal/modules/cjs/loader.js:508:25)
dockerised-yelpcamp |     at Module.require (internal/modules/cjs/loader.js:637:17)
dockerised-yelpcamp |     at require (internal/modules/cjs/helpers.js:22:18)
dockerised-yelpcamp |     at Object.<anonymous> (/usr/src/app/app.js:1:77)
.
.
.
dockerised-yelpcamp |     at Function.Module._load (internal/modules/cjs/loader.js:531:3)
dockerised-yelpcamp | npm ERR! code ELIFECYCLE
dockerised-yelpcamp | npm ERR! errno 1
dockerised-yelpcamp | npm ERR! [email protected] start: `node app.js`
dockerised-yelpcamp | npm ERR! Exit status 1
dockerised-yelpcamp | npm ERR! 
dockerised-yelpcamp | npm ERR! Failed at the [email protected] start script.
dockerised-yelpcamp | npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
dockerised-yelpcamp | npm WARN Local package.json exists, but node_modules missing, did you mean to install?
dockerised-yelpcamp | 
dockerised-yelpcamp | npm ERR! A complete log of this run can be found in:
dockerised-yelpcamp | npm ERR!     /root/.npm/_logs/2019-04-17T11_14_17_109Z-debug.log
dockerised-yelpcamp exited with code 1

泊坞窗,compose.yml

version: "3"
services:
  main_app:
    container_name: dockerised-yelpcamp
    restart: always
    build: .
    ports:
      - 80:3000
    links:
      - mongo
    volumes: ["./:/usr/src/app"]
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - 27017:27017

Dockerfile

FROM node:10

WORKDIR /usr/src/app

COPY package.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

我的docker文件包含npm install,它在构建图像时成功执行。

node.js docker docker-compose dockerfile
2个回答
0
投票

你的volumes:指令隐藏了Dockerfile对本地系统内容所做的一切。如果您没有node_modules目录或其架构或库堆栈与容器中的内容不兼容,则此设置将无法正常工作。

常见的解决方法似乎是声明第二个匿名卷来保存node_modules,这将一直有效,直到你更改你的package.json文件。

我的建议是完全删除volumes:指令。无需Docker即可在本地开发应用程序。一旦它工作并且你已经测试过它,使用这个Dockerfile来重建图像。这两者都为您提供了一个更简单的非Docker开发设置,并复制了您在生产环境中的环境(除了包含它的Docker镜像之外,您不会复制应用程序代码)。


0
投票

您只复制package.json,因此您需要创建node_modules文件夹:

dockerised-yelpcamp | npm WARN Local package.json exists, but node_modules missing, did you mean to install?

如果我的记忆力很好,默认情况下docker容器不能回答是。因此,他跳过创建文件夹并且node_modules保持缺失状态。

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