这是一个 Next.js 专门生成用于部署的精简版本(用于容器部署 / Docker),特点:
- 只包含运行所需的最小 Node.js 文件(没有源码、没有 webpack 依赖)
- 可以像普通 Node 项目一样启动:
node server.js
- 与
.next/static
、.next/cache
不同,它适合用于部署
standalone使用
开启standalone模式,next.config.js:
// next.config.js
module.exports = {
output: 'standalone',
}
构建时:
next build
会创建一个.next/standalone
目录
容器构建
之前是复制 .next
下的内容,例如:
COPY --from=builder /app/web/.next ./.next
COPY --from=builder /app/web/public ./public
COPY --from=builder /app/web/package.json ./package.json
只需要替换.next
这行,如下:
# COPY --from=builder /app/web/.next ./.next
COPY --from=builder /app/web/.next/standalone ./ # 改为standalone
变更后的目录:
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
注意:运行时通过
node server.js
命令,因为生成的node_modules
中不包含.bin
目录,所以没法通过pnpm run start
启动(可以通过node_modules/.bin
和依赖命令原理了解.bin
的作用)。