【笔记】PM2学习笔记

前言

PM2 is a production process manager for Node.js/Bun applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.(Github)

下载依赖

1
npm install -g pm2

查看由PM2管理的守护进程列表

1
pm2 list

启动守护进程

  • 以守护进程的方式启动Nodejs

<file>.js:通过Nodejs运行的JS文件
<name>:进程名

1
pm2 start <file>.js --name <name>

停止守护进程

<id>:可以是进程id、进程名、配置文件ecosystem.config.js的任意一种

1
pm2 stop <id>

重启守护进程

1
pm2 reload <id>

删除守护进程

1
pm2 delete <id>

删除所有守护进程

1
pm2 delete all

配置文件

生成默认配置文件

1
pm2 init simple
1
File ecosystem.config.js generated

修改配置文件

单例

ecosystem.config.js
1
2
3
4
5
6
7
8
9
10
11
module.exports = {
app: [
{
name: "<name>",
script: ".output/server/index.mjs",
env: {
PORT: 8080
}
}
]
}

集群

exec_mode:执行模式

"cluster":集群模式,自动负载均衡

instance:指定实例数

"max":CPU有多少核心就启动多少实例

ecosystem.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
module.exports = {
app: [
{
name: "<name>",
script: ".output/server/index.mjs",
env: {
PORT: 8080
},
exec_mode: "cluster",
instance: 2
}
]
}

完成