Невозможно найти модуль index.js в Google Cloud VM Docker

Я столкнулся с ошибкой, из-за которой докер-контейнер не может запуститься после развертывания на виртуальной машине GCP Cloud Compute Engine. Тем не менее, он может нормально запускаться на моем локальном компьютере с чипом Mac M3.

Ошибка связана с невозможностью найти модуль index.js.

Node.js v22.3.0

> [email protected] start
> node build/src/index.js

node:internal/modules/cjs/loader:1215
  throw err;
  ^

Error: Cannot find module '/app/build/src/index.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1212:15)
    at Module._load (node:internal/modules/cjs/loader:1038:27)
    at wrapModuleLoad (node:internal/modules/cjs/loader:212:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:158:5)
    at node:internal/main/run_main_module:30:49 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Это мой докер-файл:

FROM node:22

# Create and change to the app directory.
WORKDIR /app

COPY package*.json ./

# Install production dependencies.
RUN npm install

# Copy local code to the container image.
COPY . .

EXPOSE 3000
# Run the web service on container startup.
CMD [ "npm", "run", "build" ]
CMD [ "npm", "run", "start" ]

Это мой package.json

{
    "name": "test-fastify",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
        "build": "tsc -p tsconfig.json",
        "dev": "ts-node-dev --respawn src/index.ts",
        "start": "node build/src/index.js",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": "",
    "dependencies": {
        "@fastify/cookie": "^9.3.1",
        "@fastify/cors": "^9.0.1",
        "@fastify/mysql": "^4.3.0",
        "@fastify/session": "^10.9.0",
        "@fastify/type-provider-typebox": "^4.0.0",
        "@sinclair/typebox": "^0.32.30",
        "dotenv": "^16.4.5",
        "fastify": "^4.27.0",
        "firebase": "^10.12.2",
        "firebase-admin": "^12.1.1",
        "kysely": "^0.27.3",
        "mysql2": "^3.9.7",
        "nodemon": "^3.1.0",
        "pino": "^9.1.0",
        "short-uuid": "^5.2.0",
        "uninstall": "^0.0.0",
        "@fastify/swagger": "^8.14.0",
        "@fastify/swagger-ui": "^3.0.0"
    },
    "devDependencies": {
        "@fastify/autoload": "^5.8.2",
        "@types/node": "^20.12.11",
        "@typescript-eslint/eslint-plugin": "^7.11.0",
        "@typescript-eslint/parser": "^7.11.0",
        "eslint": "^8.57.0",
        "eslint-config-prettier": "^9.1.0",
        "prettier": "^3.2.5",
        "ts-node-dev": "^2.0.0",
        "typescript": "^5.4.5"
    }
}

Я попытался создать образ локально как таковой: docker build -t gcr.io/some-project-id/fastify-backend-v1 . и попробовал запустить его локально, но он работает. Однако при развертывании на виртуальной машине GCP это не удалось.

tsconfig.json:

{
    "compilerOptions": {    
        /* Language and Environment */
        "target": "es2017" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
        /* Modules */
        "module": "commonjs" /* Specify what module code is generated. */,
        "rootDir": "./" /* Specify the root folder within your source files. */,
        // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
        "baseUrl": "./" /* Specify the base directory to resolve non-relative module names. */,    
        "outDir": "./build" /* Specify an output folder for all emitted files. */,        
        "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,        
        "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

        /* Type Checking */
        "strict": true /* Enable all strict type-checking options. */,        
        "skipLibCheck": true /* Skip type checking all .d.ts files. */
    }
}

🤔 А знаете ли вы, что...
Node.js может быть использован для создания микросервисов и масштабируемых приложений.


1
72
1

Ответ:

Решено

Нашел решение изменить следующее:

# This runs during container building i.e docker build
RUN npm run build

# This runs when we perform docker start
# Running CMD [NPM, RUN, START] doesnt work
CMD ["node", "build/src/index.js"]

Следовательно, во время сборки контейнера мы уже компилируем код. Возможно, из-за того, что NPM не установлен (т. е. используется NVM) во время процесса CMD, команда NPM RUN START не работает.