我正在关注Node.js的"Intro to Docker" tutorial,并且当我运行npm start
时,该项目可以运行。当我运行docker run (options)
时,生成了构建,但是我会在日志中找到以下错误。该项目是一个简单,简单,直接的项目,我不确定这里缺少什么。我之前在生产中遇到了一个非常类似的错误(对于没有Docker的Heroku来说),本地运行看起来不错,实时部署也遇到了类似的错误。
我不确定我是否使用了过时的东西,但是我更新了npm,docker,并且不确定还有什么可能。
感谢您的帮助!
错误:
internal/modules/cjs/loader.js:969
throw err;
^
Error: Cannot find module '/usr/src/app/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
at Function.Module._load (internal/modules/cjs/loader.js:842:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
目录:
package.json:
{
"name": "SampleProject",
"version": "1.0.0",
"description": "Node.js on Docker",
"author": "First Last <first.last@example.com>",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dock": "docker run -p 1234:1234 -d <My>/<Info>"
},
"dependencies": {
"core-util-is": "^1.0.2",
"express": "^4.17.1"
}
}
Dockerfile
# I'm using Node.js -> Import it's image
FROM node:12
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Run on port 1234
EXPOSE 1234
CMD [ "node", "server.js" ]
server.js
'use strict';
const express = require('express');
// Constants
const PORT = 1234;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
运行:
npm run dock
注意:
我还通过运行以下命令清除了该项目:
rm -rf node_modules package-lock.json && npm install && npm start
已解决:
Dockerfile
# I'm using Node.js -> Import it's image
FROM node:12
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# * BEGIN SOLUTION *
# Bundle app source
COPY . .
# * END SOLUTION *
# Run on port 1234
EXPOSE 1234
CMD [ "node", "server.js" ]
答案 0 :(得分:1)
我认为您缺少以下重要部分,应该放在RUN npm install
之后:
要将应用程序的源代码捆绑在docker映像中,请使用COPY指令:
# Bundle app source
COPY . .
并强制执行Dockerfile中的每个步骤,
docker build --no-cache