Next.js项目部署,使用Nginx和pm2

概述

请添加图片描述
只有一台服务器,所以上图服务都都在一个云服务器上。其中Nginx 分别在用户和Next服务之间代理、在Next和后台之间代理。

常规的前台页面不需要这样做,例如Vue中直接把build之后的dist文件拷贝到nginxhtml目录并配置nginx指向即可,但是Next可以做到服务端渲染(SSR)所以Next的前台页面实际上是一个nodejs服务,所以nginx在这里是代理用户请求,proxy_pass到这个nodejs服务上。
而前后台之间的nginx代理属于反向代理,一般也通过proxy_passrewrite路径进行代理,我没配置这个。

Next.js配置

在需要SSRpage中需要添加 getStaticPropsgetStaticProps这些function只能写在page文件夹中,不可以在components中用),注意可以设置revalidate定时重新build页面,这样页面也可以定期更新,如下:


export async function getStaticProps() {
	//后台取数据
    const result = await queryTimelineList()
    // console.log(result)
    return {
        props: {
            timelineData: result.data,
        },
        // 重新绘制页面时长 1200 ,单位秒
        revalidate: 1200
    };
}

另外,注意在动态路由的page中,需要设置fallbacktrue,且页面中要增加对fallbackfalse的处理,否则build的时候会报错,如下 一个名为 [postId].js的page:

const PostId = ({postId, postDetail, recentPosts,curTags}) => {


    const router = useRouter()
	// 注意,这里要处理
    if (router.isFallback) {
        return <div>Loading...</div>
    }
    ...
}


// Fetch data at build time
export async function getStaticProps(context) {
    const postId = context.params.postId

    const
        [postDetailResult,
            recentPostsResult,
            curPostTagsResult] = await Promise.all([
                queryPostDetailByPostId(postId),
                queryRecentPostList(),
                queryTagListByPostId(postId)
            ]
        )
    return {
        props: {
            postId: postId,
            postDetail: postDetailResult?.data,
            recentPosts: recentPostsResult?.data,
            curTags: curPostTagsResult?.data
        },
        revalidate: 300
    };
}

// Specify dynamic routes to pre-render pages based on data.
// The HTML is generated at build time and will be reused on each request.
export async function getStaticPaths() {
    const postIdsResult = await queryPostIdList();
    const postIdList = postIdsResult.data

    return {
        paths: postIdList.map((postId) => {
        	// 这里如果传的是数字会报错,必须转为字符串
            return {params: {postId: postId.toString()}}
        }),
        // 设置为true
        fallback: true,
    };
}

Nginx配置

完整的nginx.conf配置文件如下:


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    

    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  btyhub.site, www.btyhub.site;
		# ssl两个文件,放在 nginx的conf目录中
        ssl_certificate      btyhub.site_bundle.pem;
        ssl_certificate_key  btyhub.site.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;
		# 代理到Next的服务,默认3000端口,也可以在start的时候指定
        location / {
            proxy_pass    http://127.0.0.1:3000/;
        }
		
    }
    # 监听普通http请求,重写至https
	server{
		listen 80;
		server_name btyhub.site, www.btyhub.site;
		rewrite ^(.*)$ https://$host$1 permanent;
	}

}

pm2启动

ps:除了使用pm2启动Next服务外,也可以npm run build之后直接nohup npm run start
pm2官网文档

首先要安装node环境,安装完了将命令添加到全局bin中:

# /usr/local/node是我的node安装目录
ln -s /usr/local/node/bin/npm /usr/local/bin/
ln -s /usr/local/node/bin/npx /usr/local/bin/
ln -s /usr/local/node/bin/node /usr/local/bin/

其次,全局安装pm2 并加入全局bin:

npm install -g pm2
ln -s /usr/local/node/bin/pm2 /usr/local/bin/

测试,是否安装成功:

pm2 -version

运行next服务

  1. 需要将项目源文件上传至云服务器:
    在这里插入图片描述

  2. 运行npm run build

  3. 运行pm2 start --name yourappname npm -- start

后记:
域名配置完要隔几天才可以给网站备案,备案之后才可以通过域名访问,在这之前可以先用ip地址测试。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
使用nginx部署next.js,首先需要修改nginx.conf文件。可以将location /的proxy_pass指令修改为代理到运行next.js项目的端口,例如http://127.0.0.1:800。这样当访问hongbin.xyz时,nginx会将请求代理到指定的端口上。 另外,还可以通过修改nginx的配置文件来实现代理功能。在server块中,可以设置listen指令监听指定的端口(例如80),并设置server_name指令为需要访问的域名(例如hongbin.xyz)。然后,将location /的proxy_pass指令修改为代理到运行next.js项目的端口(例如http://127.0.0.1:800)。这样就可以通过访问hongbin.xyz来访问next.js项目了。 另外,如果需要修改next.js项目运行的端口,可以通过修改项目的package.json文件中的scripts字段来实现。在scripts字段中,可以设置start指令为next start -p指定的端口(例如8888)。这样,在运行npm start启动next.js项目时,项目将会在指定的端口上运行。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Linux 使用Nginx部署Next项目,并使用pm2进程守护](https://blog.csdn.net/weixin_43233914/article/details/126287099)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [在Ubuntu 上使用 NginxPM2 部署 Nextjs](https://blog.csdn.net/printf_hello/article/details/124979521)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T.Y.Bao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值