Goal
Dockerize NextJS application
Problem
Docker compose up
yields in the following error: Couldn't find a pages
directory. Please create one under the project root.
Application
Files & folders
docker-compose.yml
web
.next
pages
public
.dockerignore
dockerfile
[more nextjs files & folders here]
docker-compose
version: '3'
services:
web:
build:
context: web
dockerfile: dockerfile
ports:
- "3000:3000"
container_name: rughood_web
dockerfile
FROM node:16
WORKDIR /web
COPY package*.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "run", "dev"]
.dockerignore
Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.git
Note!
The NextJS application itself is working fine when I run npm run dev
within the web
directory (which invokes the script "dev": "next dev"
in package.json). I only have the error when trying to dockerize it. Moreover, in the docker-compose I also initiate a Redis cache, which is working fine too. Therefore I conclude the error must be how I try to combine Docker and NextJS. Thank you very much in advance :)
Update 1
How I got there
Using the tips from @HansKilian and Exploring Docker container's file system I did the following:
- Cd to the
web
directory - Built an image from the dockerfile
docker build .
- Explored the image with the following command
docker run --rm -it --entrypoint=/bin/bash name-of-image
- Once inside, execute
ls
orls -lsa
This gave me the following results:
What's in the derived image
dockerfile
next-env.d.ts
next.config.js
node_modules
package-lock.json
package.json
pages
public
tsconfig.json
[Among other files/folders]
So the pages folder actually seems to be in the root of the container, yet still I get the error (pages
is a directory in the container in which I can cd
and -ls
)
P.s. don't forget to delete your image if you're not going to using it anymore
Update 2
Building the image and running it from within the web
directory actually works, so it might actually have something to do with the docker-compose?
CodePudding user response:
Here is my working Dockerfile with nextjs:
FROM node:16.14.0
RUN npm install -g [email protected]
RUN mkdir -p /app
WORKDIR /app
COPY package*.json /app
RUN npm i
COPY . /app
EXPOSE 3000
RUN npm run build
CMD ["npm", "run", "dev"]
And docker-compose.yml :
version: "3.7"
services:
project-name:
image: project-name
build:
context: .
dockerfile: Dockerfile
container_name: project-name
restart: always
volumes:
- ./:/app
- /app/node_modules
- /app/.next
ports:
- "3000:3000"
CodePudding user response:
While I was trying every single line of code ever uploaded to the internet, I came back to my initial set-up (from the question) and suddenly it now does work. Source control confirming I didn't change a thing.
To be sure, I deleted all containers, images and volumes from Docker and ran docker compose up
. Yet still it worked. Tried many things to recreated the error, but I couldn't. Thank you all for helping and hopefully this may be come to use for someone else!