在docker中运行nextjs时使用除3000以外的任何端口

问题描述 投票:0回答:1

我有一个 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 中提供项目服务
  • 使用端口 3000 运行所有命令,包括 Dockerfile 中的
    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)

docker http next.js
1个回答
0
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.