我正在尝试在 docker 文件内本地运行下一个 js 应用程序。当我运行容器时,除了图像文件无法在页面上呈现之外,一切都按预期工作。通过开发人员工具进行的检查表明对这些图像的网络请求失败(未指示 4XX 代码)。失败的请求如下所示:
当我构建 npm run build
并在本地运行应用程序 npm run start
时,我看到相同的请求成功运行。当我在开发模式下运行时,同样的成功故事 npm run dev
。
这是利用下一个图像模块的代码部分。 从“next/image”导入图像;
<Image
src="/images/computerStation.png"
alt=""
height={300}
width={600}
/>
还有我的公共(public)目录树:
root
│
└───public
│
└───images
│
└───computerStation.png
鉴于我的本地 build/dev-env 成功,我的想法是我的 docker 文件做错了。我几乎只是从 Next js 文档中抄袭了它,并将其调整为使用 npm 而不是yarn 运行。请参阅下面的 Dockerfile:
# Install dependencies only when needed
FROM node:alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install --frozen-lockfile
# Rebuild the source code only when needed
FROM node:alpine AS builder
WORKDIR /app
COPY . .
COPY --from=deps /app/node_modules ./node_modules
RUN npm run build
# Production image, copy all the files and run next
FROM node:alpine AS runner
WORKDIR /app
ENV NODE_ENV production
# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
RUN chown -R nextjs:nodejs /app/.next
USER nextjs
EXPOSE 3000
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
RUN npx next telemetry disable
CMD ["node_modules/.bin/next", "start"]
对此的任何帮助将不胜感激。谢谢!
最佳答案
您需要检查您的 docker Node 版本,应该是
FROM node:14-alpine AS deps
FROM node:14-alpine AS builder
FROM node:14-alpine AS runner
Next.js 在 Node 16 (node:alpine) 中存在一些问题。
关于reactjs - Next js 应用程序(在 Docker 容器内运行)无法加载位于公共(public)目录中的静态文件图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67641673/