A step-by-step guide to effectively dockerizing the development and production environments for a Next.js 13 application directory

My development Dockerfile is set up as follows:

FROM node:18-alpine

WORKDIR /app

# Installing dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i; \
  else echo "Warning: Lockfile not found. It is recommended to commit lockfiles to version control." && yarn install; \
  fi

COPY .

# Starting Next.js in development mode using the preferred package manager
CMD \
  if [ -f yarn.lock ]; then yarn dev; \
  elif [ -f package-lock.json ]; then npm run dev; \
  elif [ -f pnpm-lock.yaml ]; then pnpm dev; \
  else yarn dev; \
  fi

In addition, here is my docker-compose.yml configuration:

services:
  docker-prod:
    container_name: docker-prod
    build:
      context: .
      dockerfile: dev.Dockerfile
    ports:
      - "3000:3000"
    volumes:
      - .:/app
      

After running docker-compose up, I encountered the following error:

docker-prod  | Error: Cannot find module '/app/node_modules/next/dist/bin/next'
docker-prod  |     at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)
docker-prod  |     at Module._load (node:internal/modules/cjs/loader:920:27)
docker-prod  |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
docker-prod  |     at node:internal/main/run_main_module:23:47 {
docker-prod  |   code: 'MODULE_NOT_FOUND',
docker-prod  |   requireStack: []
docker-prod  | }

I have attempted various path changes and adjustments to the COPY command. What could potentially be wrong with my Dockerfile setup?

Answer №1

After struggling with the same issue for hours (I'm new to using nextjs + pnpm in a Docker project, so I was feeling pretty lost), I finally found the solution.

The reason behind the error message is actually due to the absence of a .dockerignore file in your project. You can check out this link for reference.

If the link breaks, here are the contents you should have in that file:

Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.next
.git

Update: The key entry you need in this file is node_modules!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

What happens if ChainId is not defined in the OpenSea 2.0 clone created with Next.js, Replit, thirdweb, and tailwind CSS?

Recently, I came across a tutorial on YouTube that caught my attention. It's about creating an Open Sea 2.0 clone with Next.js, Replit, thirdweb, Infura, and Tailwind CSS. The video used Rinkeby Network, but since it's not stable anymore, I switc ...

Unsuitable data types in GraphQL - is the configuration faulty?

I'm currently facing an issue that's giving me some trouble. In my datamodel.prisma, I added a new type called Challenge: type Challenge { id: ID! @id createdAt: DateTime! @createdAt updatedAt: DateTime! @updatedAt completed: Bo ...

error message indicating that a static file could not be found following deployment as it is not located within the root directory

When deploying my Next.js web app in a directory other than the root, such as '/next' instead of '/', the static files in the public folder cannot be found. This is because the requested URL is not http://example.com/next/a.png, but rat ...

`The challenge of language translation with i18next`

Transitioning from a single file containing all languages to individual files per language using i18next. The content of the translation.json file is as follows: { "section":{ "title":"wello world" } } This c ...

Is there a way to access a component's props within the getServerSideProps() method?

Is there a way to pass parameters to a React component and then access the values of those parameters within the getServerSideProps function of the component? I am utilizing the next framework in React JS. <Menu name={menuName} /> In this example, ...

Generate a list of items in typescript, and then import them into a react component dynamically

I have a variable that stores key/value pairs of names and components in a TypeScript file. // icons.tsx import { BirdIcon, CatIcon } from 'components/Icons'; interface IconMap { [key: string]: string | undefined; } export const Icons: IconM ...

What is the best way to restore a component's state to its default settings when it receives new props?

I have a Next.js project in development with a custom Layout already set up. I want the header component to reset whenever a new page is navigated to, so that the menu reverts back to its default state. Does anyone know how I can achieve this? import { F ...

The issue with the NextJS Layout component is that it is failing to display the page content, with an error message indicating that objects cannot be used

I am embarking on my first project using Next JS and after watching several tutorial videos, I find the Layout component to be a perfect fit for my project! However, I am encountering an issue where the page content does not display. The Menu and Footer a ...

Mapping prop passed to client component in NEXT 13: A step-by-step guide

Hello, I'm currently navigating through the Next 13 APP directory and have encountered a scenario where everything functions smoothly when I integrate the server component as shown below: const Tasks = async () => { const { tasks } = await getAll ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

Changes trigger the re-rendering of inputs

My modal is causing all inputs to be re-rendered with every change I make while typing. I have a Formik object set up like this: const formik = useFormik({ enableReinitialize: true, initialValues: { sp_id: data?.id, ...

Sending environmental variable values to an Angular application from a Docker file

I am currently facing a challenge with my Angular application where I am attempting to define the environment variable from an external source, specifically from a docker compose file. For reference, I found an article that addresses this issue: docker-c ...

Guide on dynamically caching a Server Side Rendered Page in Next.js with Dynamic Routes

I am in the process of deploying a Next.js Application on AWS using ECS/Fargate because I have specific requirements that prevent me from using Amplify for custom logging and monitoring purposes. My application utilizes api-routes and dynamic-routes with S ...

Using the useState hook in React, you can manipulate a deeply nested object by changing its values, adding new fields,

The structure of the nested state object is as follows: key1: { key2: [ { field1: "value", field2: ["value", "value"], field3: [ { ff1: "val", ...

What causes styled-components to apply styles in a unique way to its descendants?

My parent component has some specific styling: > * { width: initial; } Within this parent component, I have two separate child components: <Component1/> and <Component2/> Both of these components are div elements with a width of 200 ...

Integrate the retrieved information into a new object and then proceed to export it

Hey there! I'm looking to retrieve data from an API and merge it with some existing data in an array of objects. The goal is to then export this combined data for use in another part of my web application. Check out the following code example: //expo ...

Misplacing a cookie while trying to request it from one subdomain to another subdomain

Recently, I've been encountering a strange issue involving the disappearance of cookies. In the past, I utilized AWS for both my frontend and backend infrastructure. View previous setup Due to deployment complications (specifically prolonged fronte ...

Having trouble building server-side code in Next.js with App Router because of node.js dependencies in Turborepo

I recently started moving my Next.js projects into a Turborepo monorepo setup. Within the Next.js projects, I'm utilizing the latest App Router and have server-side routes and components. These elements all compiled successfully outside of Turborepo, ...

An unexpected error occurred while attempting to retrieve data from Firebase and display it in another component

An error occurred: Unhandled Runtime Error Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components) but got undefined. This could be due to forgetting to export your component from the defi ...