NodeJS TypeScript - Docker 镜像构建但无法运行

时间:2021-01-05 08:10:46

标签: node.js typescript docker dockerfile

对 docker 来说很新,所以我不知道我的配置在哪里缺少,所以我有一个 NodeJS TypeScript 项目,我正在尝试对其进行 dockerize。

面临的问题

  • 当我运行 docker build -t server . 时,它会成功构建所有内容
  • 现在,当我运行 docker run -p 4000:5000 server 时,出现以下错误
node:internal/modules/cjs/loader:928
  throw err;
  ^

Error: Cannot find module '/dist/server.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

这是我的 Dockerfile:

FROM node

WORKDIR /usr/app

COPY package.json ./

RUN npm i

COPY . .

RUN npm run build

COPY .env ./dist/

WORKDIR /dist

EXPOSE 5000

CMD node server.js

如果这也有助于破解问题,这里也是我的 tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist",
    "baseUrl": ".",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "allowJs": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "forceConsistentCasingInFileNames": false,
    "target": "ES6",
    "strict": true,
    "noImplicitAny": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "src/**/*"
  ]
}

最后是我的 package.json 脚本和主要内容:

"main": "dist/server.js",
"scripts": {
  "build": "tsc -b",
  "start": "node dist/server.js",
  "dev": "nodemon --exec ts-node src/server.ts"
},

0 个答案:

没有答案