这是我参与「第五届青训营 」笔记创作活动的第13天
在linux上部署Nextjs项目 两种部署方式,Nextjs部署
最近在学Nextjs,开发的最后一步自然是部署Nextjs。根据自己这几天的Nextjs部署经验,整理了一下Nextjs部署
- 通过Vercel部署
- 通过pm部署
- 通过docker部署
- 手动部署
静态生成
通过next build && next export输出Nextjs静态文件,默认输出在out文件夹,这种形式,网站的动态部分会404
通过vercel部署
国内用处不大,由于网络问题,难以访问。
部署到nodejs服务器
安装nodejs
切换淘宝镜像
通过某种方法传输文件到服务器(node_modules除外)
安装依赖
执行npm i
执行next build && next start启动nextjs服务
配置nginx反向代理
将域名访问反响代理到nextjs运行的端口
这里以localhost:3000为例
location / {
proxy_pass http://localhost:3000/
}
接着重启nginx服务,就能使用绑定的域名访问了
Docker部署
官方镜像
不建议使用
# 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 yarn.lock ./
RUN yarn 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 yarn build && yarn install --production --ignore-scripts --prefer-offline
# Production image, copy all the files and run next
FROM node: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 --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
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_modules/.bin/next", "start"]
编写dockerfile
FROM node:lastest
RUN mkdir -p /var/www/next
ADD . /var/www/next
WORKDIR /var/www/next
ENV HOST 0.0.0.0
ENV PORT 3000
EXPOSE 3000
CMND ["npm","start"]
构建镜像
docker build
运行容器
docker run
nginx配置反向代理
将反向代理配置到localhost:3000