javascriptdockernestjs

Cannot find module '@nestjs/core'


It does not run in the docker environment.

Dockerfile

FROM node:18.17.0 AS builder

WORKDIR /usr/src/app

RUN yarn global add @nestjs/cli

COPY package*.json yarn.lock ./
RUN yarn --prod

COPY . .

RUN yarn build

FROM node:18.17.0-alpine

WORKDIR /usr/src/app

COPY --from=builder /usr/src/app/package*.json ./package*.json
COPY --from=builder /usr/src/app/yarn.lock ./yarn.lock
COPY --from=builder /usr/src/app/dist ./dist

CMD ["node", "dist/main"]

Error Message

Error: Cannot find module '@nestjs/core'
Require stack:
| - /usr/src/app/dist/main.js
|     at Module.\_resolveFilename (node:internal/modules/cjs/loader:1077:15)
|     at Module.\_load (node:internal/modules/cjs/loader:922:27)
|     at Module.require (node:internal/modules/cjs/loader:1143:19)
|     at require (node:internal/modules/cjs/helpers:110:18)
|     at Object.\<anonymous\> (/usr/src/app/dist/main.js:3:16)
|     at Module.\_compile (node:internal/modules/cjs/loader:1256:14)
|     at Module.\_extensions..js (node:internal/modules/cjs/loader:1310:10)
|     at Module.load (node:internal/modules/cjs/loader:1119:32)
|     at Module.\_load (node:internal/modules/cjs/loader:960:12)
|     at Function.executeUserEntryPoint \[as runMain\] (node:internal/modules/run_main:81:12) {
|   code: 'MODULE_NOT_FOUND',
|   requireStack: \[ '/usr/src/app/dist/main.js' \]
| }
|
| Node.js v18.17.0

I tried adding this but nothing changed

RUN yarn add @nestjs/core

This error occurred after changing Dockerfile. I think there's probably a problem with the Dockerfile setting


Solution

  • It seems that Nest.js application is not able to find the required module because it's not installed in the production environment. In your Dockerfile, you are using the --prod flag with the yarn command during the build stage, which tells Yarn to install only production dependencies. This is likely the reason for the error.

    To resolve this issue, you should install both production and development dependencies during the build stage, and then prune the development dependencies in the final image to keep the image size smaller. You can do this by modifying your Dockerfile as follows:

    # Build stage
    FROM node:18.17.0 AS builder
    
    WORKDIR /usr/src/app
    
    # Install Nest.js CLI globally
    RUN yarn global add @nestjs/cli
    
    COPY package*.json yarn.lock ./
    RUN yarn install # Install both production and development dependencies
    
    COPY . .
    
    RUN yarn build
    
    # Production image
    FROM node:18.17.0-alpine
    
    WORKDIR /usr/src/app
    
    COPY --from=builder /usr/src/app/package*.json ./
    COPY --from=builder /usr/src/app/yarn.lock ./
    COPY --from=builder /usr/src/app/dist ./dist
    
    # Prune development dependencies
    RUN yarn install --production
    
    CMD ["node", "dist/main"]