Next.js 学习笔记(三)- 部署服务器

530 阅读2分钟

通过别人的服务和网站部署代码 - vercel

部署默认 SSR 服务

1.先 注册 ,然后用 Github 验证登录

2.登录 Vecel 成功后打开 vercel.com/import/git 页面,chrome 浏览器的记得点击地址栏的云允许弹出链接, 选择安装全部仓库

3.合并开发分支到主分支,如果直接主分支开发的则不用

4.选择要部署的 nextjs 仓库,点进 import, 点击 deploy 即可,稍等片刻,部署成功,点击左侧预览就可以跳转过去了,我的博客示例

image.png

自己部署到自己的服务器

阿里云优惠

部署默认 SSR 服务

  1. 进入自己的服务器控制台 git clone 你的 github 仓库 http 链接
  2. 安装依赖
pnpm i

3.构建

pnpm build
  1. 使用pm2管理项目进程

标准方式

pm2 start npm --name yourName -- run server --watch

如果命令有问题的话,用下面这种方式

根目录增加文件 ecosystem.config.js

module.exports = {
  apps: [
    {
      name: 'next-blog',
      script: './node_modules/next/dist/bin/next',
      args: 'start -p 7777',
    },
  ],
};

直接

pm2 start --watch

自动重启

pm2 startup

保存 pm2 启动命令 下次可以直接使用

pm2 save

直接使用上次 pm2 命令

pm2 resurrect
# 查看所有进程,以及对应的端口
netstat -tunlp
  1. nginx 配置反向代理,将域名指向 nextjs 开启的端口号,默认 localhost:3000 , 如果你修改了那就要修改端口号

配置nginx.conf 文件


user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {

    include       /etc/nginx/mime.types;
  
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
    	listen  443 ssl;

	ssl_certificate xinwangblog.cn_bundle.crt;

	ssl_certificate_key xinwangblog.cn.key;

	 server_name xinwangblog.cn www.xinwangblog.cn;

	 location / {
       
       
	proxy_pass http://127.0.0.1:7777; 

	 proxy_set_header X_FORWARDED_PROTO https;
              proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header  Host $http_host;
              proxy_set_header  X-Url-Scheme $scheme;
              proxy_redirect    off;
              proxy_max_temp_file_size 0;
       
      }
 
    } 


    server{
	listen 80;
		
        server_name xinwangblog.cn www.xinwangblog.cn;

	location / {
		proxy_pass http://127.0.0.1:7777;
	}
	
	}
}

这里还要检查你的 ssl 证书,要删掉 443 那个

检查 文件合法

nginx -t

重启 nginx

nginx -s reload

只部署静态服务

  1. 进入自己的服务器控制台 git clone 你的 github 仓库 http 链接
  2. 安装依赖
pnpm i

3.构建

pnpm build
  1. 导出文件 这里可能有问题,图片优化需要在 start 情况下才启动,直接 export 会报错,这里要配置下next.config.js
const nextConfig = {
  reactStrictMode: true,
  images: {
    loader: "akamai",
    path: "",
  },
  exportPathMap: async function (
    defaultPathMap,
    { dev, dir, outDir, distDir, buildId }
  ) {
    return {
      "/": { page: "/" },
    };
  },
};

module.exports = nextConfig;

注意:这里配置了之后,打包的时间会特别得久,要是实在不喜欢可以删掉这个加载器,并且禁用优化,确实也没啥用

再执行

pnpm export

index.html 文件会导出在项目根目录下的 out 文件夹中,可以直接启动