Search code examples
reactjsdockernext.jsyarnpkg

Docker image build successfully but after docker run : Couldn't find the node_modules state file - running an install might help (findPackageLocation)


I have a Next JS project which uses yarn 3.5.1 by default (it was a template) I can build the project via docker build successfully without any error. here is my docker file for this project:

# Stage 1: Build
FROM node:18-alpine AS builder

WORKDIR /app

COPY .yarn ./.yarn
COPY .yarnrc.yml ./
COPY package.json yarn.lock ./

RUN yarn install --immutable

COPY . .

RUN yarn build

# Stage 2: Run
FROM node:18-alpine

WORKDIR /app

COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/.yarn ./.yarn
COPY --from=builder /app/.yarnrc.yml ./
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/yarn.lock ./yarn.lock

ENV NODE_ENV=production

EXPOSE 3000

CMD ["yarn", "start"]

but when I want to run this image container I get this error message:

$ sudo docker run --restart=always -p 8080:80 next1
Usage Error: Couldn't find the node_modules state file - running an install might help (findPackageLocation)

$ yarn run [--inspect] [--inspect-brk] [-T,--top-level] [-B,--binaries-only] <scriptName> ...

I found a similar question in SO based on that I tried to use a different node version but issue not resolved. any tips or idea would be kindly appreciated.


Solution

  • Looks like you haven't copied node_modules from build step. Add this like to your code

    COPY --from=builder /app/node_modules ./node_modules