Next 使用 Docker 进行部署的方法

22 min read

要将对Docker的支持添加到现有项目中,只需将下面的Dockerfile 复制到项目的根目录中,并将以下内容添加到next.config.js文件中:

// next.config.js
module.exports = {
  // ... rest of the configuration.
  output: 'standalone',
}

这将在Docker映像中构建作为独立应用程序的项目。

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

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi


# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# 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 during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN yarn build

# If using npm comment out above and use below instead
# RUN npm run build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

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

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

# 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

CMD ["node", "server.js"]
  1. 如果存在 "yarn.lock" 文件,则执行 "yarn --frozen-lockfile" 命令。

  2. 如果存在 "package-lock.json" 文件,则执行 "npm ci" 命令。

  3. 如果存在 "pnpm-lock.yaml" 文件,则执行 "yarn global add pnpm && pnpm i --frozen-lockfile" 命令。

  4. 否则,打印一条消息 "Lockfile not found." 并退出状态为1。

  5. 使用 "addgroup" 命令创建一个名为 "nodejs" 的系统组,并将其组 ID 设置为 1001

  6. 使用 "adduser" 命令创建一个名为 "nextjs" 的系统用户,并将其用户 ID 设置为 1001,这些命令用于在 Docker 容器中为应用程序创建一个独立的用户空间,以限制该应用程序对容器内部资源的访问权限。这有助于提高容器内部数据和资源的安全性。

  7. 使用 1001 作为组和用户 ID 是一种惯例,是用于避免与其他系统组和用户的冲突。

    在 Linux 操作系统中,一些特定的用户 ID 和组 ID 被保留用于系统级的用户和组。例如,用户 ID 和组 ID 小于 1000 的一般被认为是系统级的。因此,在使用非标准的用户和组时,通常会选择一个大于 1000 的 ID 以避免冲突。

    当然,可以使用任何未使用的 ID,但 1001 在实践中被广泛使用,因此也成为了惯例。

  8. "yarn --frozen-lockfile" 是一个 Yarn 命令行选项,用于在安装依赖关系时保持锁定的依赖关系版本不变。如果您希望更改依赖关系版本,可以在删除 "yarn.lock" 文件后再次运行 "yarn" 命令。