我有一个 nextJS 项目,我试图在 3000 以外的端口上运行,更具体地说,8080。当我正常运行服务器时,使用命令
next dev -p 8080
,我可以在 localhost:8080
访问它。但是,我无法让它在 Docker 中工作。
这是 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"]
这是
package.json
中的命令:
"scripts": {
"dev": "next dev -p 8080",
"build": "next build",
"start": "next start -p 8080",
"lint": "next lint",
},
更多信息:
npx next dev -8080
在 localhost:8080 中提供项目服务EXPOSE
和 ENV
。npx next start -p 8080
也可以使用,该页面可以在 localhost:8080 中访问唯一的问题是在 docker 容器内部,当使用 3000 以外的任何端口时。
为什么会发生这种情况以及如何解决这个问题?
编辑:
以下是与 Docker 相关的命令:
docker build -t demo-nextjs:$(TAG) -f Dockerfile.nextjs .
docker run -it demo-nextjs:$(TAG)
EXPOSE
指令(docs.docker.com
)“[...]实际上并没有发布端口。”因此,如果我们想要发布容器的端口,我们需要使用docker run
命令。
--publish
参数 (docs.docker.com
)。在我们的例子中,我们可以使用:
docker run \
--publish 8080:8080 \
--interactive `#same as -i` \
--tty `#same as -it` \
demo-nextjs:$(TAG)