【发布时间】:2022-01-20 22:29:05
【问题描述】:
所以我试图在 docker-compose 中运行 NextJS 应用程序。
为了有一个 NextJS 样板 + 一个 Docker 镜像来构建容器,我按照the docker example of the NextJS official repo 中提供的步骤操作。
这里是提供的 Dockerfile:
# Install dependencies only when needed
FROM node:16-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 yarn.lock ./
RUN yarn install --frozen-lockfile
# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build
# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# 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/package.json ./package.json
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 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.
# ENV NEXT_TELEMETRY_DISABLED 1
CMD ["node", "server.js"]
从那里,我在应用程序的根目录创建了一个docker-compose.yml 文件,并尝试自己编写它以启动 NextJS 应用程序:
version: "3"
services:
web:
build:
context: .
dockerfile: Dockerfile
container_name: web
restart: always
volumes:
- ./:/app
- /app/node_modules
- /app/.next
ports:
- 3004:3000
但是,在运行 sudo docker-compose up --build 时,我收到以下错误:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module '/app/server.js'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
为什么找不到节点模块?我到底做错了什么?
【问题讨论】:
-
当您映射
./:/app时,您将当前主机目录映射到容器中的/app。当您这样做时,容器中 /app 中的任何内容都会被隐藏且无法访问。 -
@HansKilian 我明白了,谢谢!那我该怎么办?删除行
./:/app?刚试了,不行 -
尝试删除所有 3 个映射
-
这在我删除卷之后确实有效!谢谢你!但这优化了吗?我认为我需要这些来进行优化?
-
是的。当您进行热重载时,您将源映射到容器中,而不是复制它。您还可以在运行时而不是在构建时构建。
标签: docker docker-compose next.js