I have a nextJS project that I'm trying to run on a port other than 3000, more specifically, 8080. When I run the server normally, with the command next dev -p 8080
, I can access it at localhost:8080
. However, I can't get that to work in Docker.
Here's the Dockerfile:
# Use the official Node.js 18 image as base
# Build stage
FROM node:18-alpine AS build
WORKDIR /app/
COPY ./nextjs/package.json ./nextjs/package-lock.json ./
RUN npm install
COPY ./nextjs .
RUN npm run build
# Run stage
FROM node:18-alpine
WORKDIR /app/
ENV NEXT_TELEMETRY_DISABLED 1
ENV NODE_ENV production
# Copy only the built app from build image
COPY --from=build /app/public ./public
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/.next ./.next
COPY --from=build /app/node_modules ./node_modules
EXPOSE 8080
ENV PORT 8080
CMD ["npm", "run", "start"]
And here are the commands in package.json
:
"scripts": {
"dev": "next dev -p 8080",
"build": "next build",
"start": "next start -p 8080",
"lint": "next lint",
},
More info:
npx next dev -8080
serves the project in localhost:8080EXPOSE
and ENV
in the Dockerfile works.npx next start -p 8080
also works, the page being accessible in localhost:8080The only problem is inside a docker container, when using any port other than 3000.
Why is this happening and how can I fix this?
EDIT:
Here are the commands relating to Docker:
docker build -t demo-nextjs:$(TAG) -f Dockerfile.nextjs .
docker run -it demo-nextjs:$(TAG)
The EXPOSE
instruction (docs.docker.com
) "[...] doesn't actually publish the port." Thus, if we want to publish the port of a container, we need to specify this with the docker run
command.
To publish a port, we use the --publish
parameter (docs.docker.com
). In our case, we can use:
docker run \
--publish 8080:8080 \
--interactive `#same as -i` \
--tty `#same as -t` \
demo-nextjs:$(TAG)