Docker - 在 docker 容器日志中找不到模块

Posted

技术标签:

【中文标题】Docker - 在 docker 容器日志中找不到模块【英文标题】:Docker - Cannot find module in docker container log 【发布时间】:2021-10-08 21:48:28 【问题描述】:

我在 docker 容器日志中的 docker 桌面中收到此错误。

我在 vs code 的终端运行这个命令 docker compose up

这是错误:

> tracking-system@1.0.0 dev /usr/src/server

> nodemon -r esm -L server.js


[nodemon] 2.0.7

[nodemon] to restart at any time, enter `rs`

[nodemon] watching path(s): *.*

[nodemon] watching extensions: js,mjs,json

[nodemon] starting `node -r esm server.js server.js`

[nodemon] app crashed - waiting for file changes before starting...


Error: Cannot find module '/usr/src/server/server.js'

at internal/main/run_main_module.js:17:47 

code: 'MODULE_NOT_FOUND',

requireStack: []


这是我项目中的所有文件

app (folder)
node_modules (folder)
.dockerignore
.gitignore
Dockerfile
Dockerfile.prod
package.json
package-lock.json
server.js

这是我的代码:

server.js:

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import passport from 'passport';
import morgan from 'morgan';
import socketio from 'socket.io';
import http from 'http';
import  success, error  from 'consola';
import  db_connection  from './app/config';

const app = express();
const server = http.createServer(app);
const io = socketio(server);
const PORT = process.env.SERVER_PORT || 8861;

var corsOptions = 
    origin: '*',
    optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    credentials: true,
;

app.use(cors(corsOptions));
app.use(express.json());
app.use(passport.initialize());
app.use(morgan('dev'));

import passport_init from './app/middleware/passport';
import userRoute from './app/routes/user.route';
import authRoute from './app/routes/auth.route';
passport_init(passport);
app.use('/api/users', userRoute);
app.use('/api/auth', authRoute);

const startDatabase = async () => 
    try 
        await mongoose.connect(db_connection, 
            useNewUrlParser: true,
            useFindAndModify: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            dbName: 'tracking-system',
        );

        success(
            message: `Successfully connected with the database on $db_connection`,
            badge: true,
        );
     catch (err) 
        error(
            message: `Unable to connected with the database $err`,
            badge: true,
        );
        setTimeout(startDatabase, 5000);
    
;

startDatabase();

server.listen(PORT, () => 
    success( message: `Server started on PORT $PORT`, badge: true );
);

io.on('connection', socket => 
    console.log(`Connected: $socket.id`)

    socket.on('disconnect', () => 
        console.log(`Disconnected: $socket.id`)
    )

    socket.on('update-worksheet', function () 
        io.sockets.emit('update-landing-page')
    )
)

Dockerfile:

FROM node:lts-buster
WORKDIR /project/server
COPY ./server/package*.json ./
RUN npm install
COPY ./.env ../.env
CMD ["npm", "run", "dev"]

package.json:


  "name": "tracking-system",
  "version": "1.0.0",
  "description": "for tracking device repairation",
  "main": "server.js",
  "scripts": 
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node -r esm server.js",
    "dev": "nodemon -r esm -L server.js"
  ,
  "author": "",
  "license": "ISC",
  "dependencies": 
    "bcrypt": "5.0.1",
    "colors": "^1.4.0",
    "consola": "^2.15.3",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "esm": "^3.2.25",
    "express": "^4.17.1",
    "express-session": "^1.17.2",
    "http-server": "^0.12.3",
    "jsonwebtoken": "^8.5.1",
    "moment-timezone": "^0.5.33",
    "mongoose": "^5.13.5",
    "morgan": "^1.10.0",
    "passport": "^0.4.1",
    "passport-jwt": "^4.0.0",
    "socket.io": "^4.1.3"
  ,
  "devDependencies": 
    "nodemon": "^2.0.7"
  

如果您能提供帮助,谢谢。我的朋友帮不上忙。

这是我的 docker 版本:

Docker version 20.10.7, build f0df350

这是我的码头工人信息:

Client:
 Context:    default
 Debug Mode: false
 Plugins:
  buildx: Build with BuildKit (Docker Inc., v0.5.1-docker)
  compose: Docker Compose (Docker Inc., v2.0.0-beta.6)
  scan: Docker Scan (Docker Inc., v0.8.0)

Server:
 Containers: 4
  Running: 4
  Paused: 0
  Stopped: 0
 Images: 4
 Server Version: 20.10.7
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: d71fcd7d8303cbf684402823e425e9dd2e99285d
 runc version: b9ee9c6314599f1b4a7f497e1f1f856fe433d3b7
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 5.10.16.3-microsoft-standard-WSL2
 Operating System: Docker Desktop
 OSType: linux
 Architecture: x86_64
 CPUs: 12
 Total Memory: 12.43GiB
 Name: docker-desktop
 ID: LASO:BRSF:IIDP:3W6O:4TRG:CRIF:H54G:WWN3:EFAP:6NLU:MMSS:OHG5
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No blkio throttle.read_bps_device support
WARNING: No blkio throttle.write_bps_device support
WARNING: No blkio throttle.read_iops_device support
WARNING: No blkio throttle.write_iops_device support

我使用的是 Windows 10 专业版

【问题讨论】:

【参考方案1】:

在 Dockerfile 的第 3 行中,您只复制项目的 package.json,但从不复制应用程序的源代码。

FROM node:lts-buster
WORKDIR /project/server
COPY ./server/package*.json ./
RUN npm install
COPY ./.env ../.env
CMD ["npm", "run", "dev"]

所以,您可以尝试使用这个 Dockerfile(我更改了工作目录,现在它复制了所有源代码):

FROM node:lts-buster
WORKDIR /usr/src/server
COPY . .
RUN npm install
CMD ["npm", "run", "dev"]

参考:Dockerizing a Node.js web app

【讨论】:

不行,又出现这个错误Error: Cannot find module '/usr/src/server/server.js' at internal/main/run_main_module.js:17:47 code: 'MODULE_NOT_FOUND', requireStack: [] 我编辑了答案,请检查使用此 Dockerfile 构建容器。

以上是关于Docker - 在 docker 容器日志中找不到模块的主要内容,如果未能解决你的问题,请参考以下文章

Python 脚本在 docker 容器中找不到使用 CRON 运行的 ENV 变量

在 docker php 容器中找不到 MySQLi

lsb_release:在最新的 Ubuntu Docker 容器中找不到命令

Docker容器启动时在jar中找不到api-rest的主类

运行docker容器时出错:启动容器进程导致“exec:”python “:$ PATH中找不到可执行文件”:未知

docker容器日志存储多久