pm2 是什么
pm2 基本命令
首先我们先创建一个简单的 node 服务,新建文件夹执行npm init
,然后装 pm2
npm i pm2 -g
新建 index.js 和 index2.js,写两个简单的 http 服务,然后用 pm2 进行管理
//index.js
let http = require("http";
let server = http.createServer(;
server.on("request", function (req, res {
console.log("------------------enter";
res.write("hello juejin";
res.end(;
};
server.listen(3000, function ( {
console.log(`服务器启动成功,通过http://localhost:3000/进行访问`;
};
//index2.js
let http = require("http";
let server = http.createServer(;
server.on("request", function (req, res {
console.log("------------------enter2";
res.write("hello juejin2";
res.end(;
};
server.listen(3001, function ( {
console.log(`服务器启动成功,通过http://localhost:3001/进行访问`;
};
接下来我们将使用 pm2 的第一个命令: pm2 start index.js
和pm2 start index2.js
分别启动这两个个程序
pm2 start -n test index.js,如果你想监听文件改动可以加--watch
等等
http://localhost:3000/
pm2 log可以看到我们打印的日志
- 停止 1 个/多个/所有程序
- 杀死 1 个/多个/所有程序
pm2 delete id/id1 id2 id3/all
- 重启 1 个/多个/所有程序
pm2 restart id/id1 id2 id3/all
- 启动并查看日志
pm2 start api.js --attach
- 列出应用程序
pm2 list
- 查看监控面板
pm2 monit
- 查看程序数据
pm2 show [id]
pm2 stop id/id1 id2 id3/all
负载均衡
我们都知道 NodeJS 是一个异步单线程语言,倘若不做任何处理直接部署到服务器上,那么它也只能使用服务器的一个线程,这样是非常浪费性能的。
pm2 start index -i max,比如我的电脑是 10 核 20 线程,它就会开 20 个线程
pm2 start index -i 3
配置文件
我们直接使用命令pm2 init simple
即可生成一个简单的配置文件ecosystem.config.js
,修改一下让它指向我们的两个服务
module.exports = {
apps: [
{
name: "index",
script: "./index.js",
},
{
name: "index2",
script: "./index2.js",
},
],
};
然后我们将原先的进程都 kill 掉,执行pm2 start ecosystem.config.js
,同样的我们的两个服务都被启动了
ecosystem.config.js
module.exports = {
apps: [
{
name: "index", //name
script: "./index.js", //相对于pm2 start 的相对路径
cwd: "", //要启动的应用程序的目录
instances: 2, //要启动实例的数量,就是上面提到的负载
watch: true, //是否启动监听
env: { NODE_ENV: "development" }, // 将出现在您的应用程序中的 env 变量
env_xxx: {
NODE_ENV: "xxx", //使用pm2注入xxx变量进行切换
},
log_date_format: "YYYY-MM-DD HH:mm Z", //日志时间格式
error_file: "./log/index-error.log", //错误文件路径
out_file: "./log/index-out.log", //输出日志文件路径
max_restarts: 10, //最大重启数
restart_delay: 4000, //重启延迟时间ms
autorestart: true, //是否自动重启
cron_restart: "", //定时重启 使用cron表达式
},
{
name: "index2",
script: "./index2.js",
},
],
};
日志
日志对于后端排查错误是非常重要的,pm2 自带日志功能,比如我们在上面配置文件中配置了日志相关的参数
log_date_format: "YYYY-MM-DD HH:mm Z", //日志时间格式
error_file: "./log/index-error.log", //错误文件路径
out_file: "./log/index-out.log", //输出日志文件路径
当我们启动项目的时候,日志就会记录在 log 下
pm2-logrotate插件即可,注意这里是 pm2 install
pm2 install pm2-logrotate
然后执行 pm2 conf 可以看到相关配置
-
retain:保留的日志文件个数
-
rotateModule:是否把 pm2 本身的日志也进行分割,
-
rotateInterval:设置强制分割,默认值是 0 0 * * *,意思是每天晚上 0 点分割,这里使用的是 corn 表达式,不会的可以搜索一下
Compress:是否通过 gzip 压缩日志
pm2 set pm2-logrotate:max_size 1K
然后我们简单测试一下这个工具,我们先设置每个 log 文件最大 1kb
pm2 restart ecosystem.config.js
然后就会发现我们的日志被分割了
总结
关注公众号web前端进阶每日更新最新前端技术文章,你想要的都有!