由于依赖另一个容器,在 Docker 容器中构建 Next.js 13 失败

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

所以我在 Docker 中编写了 2 个容器,其中包括 Next.js 和 Nestjs 应用程序。这是我的

docker-compose.yml
:

version: '3.8'
services:
  api:
    container_name: api
    build:
      context: ./api
      dockerfile: Dockerfile
    ports:
      - '6900:6900'
    restart: always
    env_file:
      - ./api/.env
  web:
    container_name: web
    build:
      context: ./web
      dockerfile: Dockerfile
      args:
        - API_URL=http://api:6900
    environment:
      - API_URL=http://api:6900
    ports:
      - '3000:3000'
    restart: always
    depends_on:
      - api

然后这里是

Dockerfile
api

FROM node:18 as builder

WORKDIR /app

COPY package*.json ./
COPY prisma ./prisma/

RUN npm install

COPY . .

RUN npm run build

RUN npm run prisma:generate

FROM builder as runner

WORKDIR /app

COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/dist ./dist

EXPOSE 6900

CMD ["npm", "run", "start:prod"]

最后这里是

Dockerfile
web

FROM node:18 as builder

WORKDIR /app
COPY ./package*.json ./
RUN npm install
COPY . .

# here we are reading the value from the build args and inserting into the environment variables
ARG API_URL
ENV API_URL=${API_URL}

RUN npm run build

FROM builder as runner
ENV NODE_ENV production

RUN \
  addgroup --system --gid 1001 nodejs; \
  adduser --system --uid 1001 nextjs

COPY --from=builder --link /app/public ./public

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --link --chown=1001:1001 /app/.next/standalone ./
COPY --from=builder --link --chown=1001:1001 /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

CMD [ "npm", "start" ]

当我运行

docker compose up --build
时,
api
成功构建并运行。然而,当涉及到构建
web
时,尤其是在
npm run build
上,它总是在
Generating static pages
上失败。

它说

fetch failed
,错误原因是
Error: getaddrinfo ENOTFOUND api

api 容器已经启动并运行,但为什么我的 Next.js 应用程序在构建静态页面时无法从 api 获取数据?为什么我的 Next.js 容器无法连接到 Nest.js 容器?

我是否缺少任何步骤,请任何人帮助我。非常感谢~

docker next.js docker-compose nestjs production-environment
2个回答
0
投票

您可以使用下一个构建/启动命令创建入口点文件并将其包含在您的 Dockerfile 中。

入口点.sh

#!/bin/sh
# entrypoint.sh

set -e  # Exit immediately if a command exits with a non-zero status

# Install dependencies
npm i || exit 1

# Build the Next.js app
npm run build || exit 1

# Start the app
exec npm run start

比在 Dockerfile 添加

COPY entrypoint.sh /
RUN dos2unix ./entrypoint.sh && chmod +x ./entrypoint.sh
ENTRYPOINT ["/bin/sh", "/entrypoint.sh"]

这将在容器运行时运行 Next.js 构建。


-1
投票

您是否尝试输入容器的地址或名称而不是 localhost 或其他内容?可以解决问题

如果不起作用,请提供您的 NextJS 代码

此外,如果您不希望在构建期间加载页面,您可以添加:

导出常量动态='力动态'

在文件末尾

© www.soinside.com 2019 - 2024. All rights reserved.