使用PM2将egg.js部署到服务上

定时开启重启
pm2 start 2 --cron-restart="30 8 * * *"
pm2 stop 2 --cron-restart="30 18 * * *"

使用PM2将egg.js部署到服务上
服务器安装环境
Node.js
PM2
pm2部署步骤

npm install pm2 -g

  

egg.js 部署步骤

npm init egg --type=simple

  

修改默认端口
找到config目录下的config.default.js,添加如下代码:

config.cluster = { listen: { path: '', port: 8000, // xxx.xxx.xxx.xxx:8000 就是你接口的前置URL hostname: '0.0.0.0', } };

  


在eggjs根目录下新建server.js,并添加如下代码:

const egg = require('egg');

const workers = Number(process.argv[2] || require('os').cpus().length);
egg.startCluster({
workers,
baseDir: __dirname,
});

  

如果域名需要https

const path = require('path')

const egg = require('egg')

 

const workers = Number(process.argv[2] || require('os').cpus().length)

egg.startCluster({

workers,

baseDir: __dirname,

port: 5701,

https: {

key: path.join(__dirname, './ssl/xxx.key'), // https 证书绝对目录
cert: path.join(__dirname, './ssl/xxx.crt'), // https 证书绝对目录
ca: path.join(__dirname, './ssl/xxx.crt'), // https 证书绝对目录

},
})

  

把eggjs所在的项目文件夹复制到服务器中,再npm安装依赖

cnpm install --production // 安装依赖

用PM2启动程序

pm2 start server.js --name server_name // server_name为自定义文件名

​ PM简单使用介绍

pm2 start ... 启动项目
pm2 restart ... 重启项目
pm2 delete ... 删除项目
pm2 logs ... 查看日志(也可以直接打开文件查看)
pm2 gracefulReload ... 这个我用的比较少

  

pm2开机重启

全局安装pm2 Win自启包

npm install pm2-windows-startup -g 
安装配置包
pm2-startup install
启动项目
pm2 start 路径
#例如 pm2 start D:\myWork\yapi\my-yapi\vendors\server\app.js
重启项目
pm2 restart  路径
#例如 pm2 delete  D:\myWork\yapi\my-yapi\vendors\server\app.js
pm2 restart  路径 --name PM2进程名称
停止项目
pm2 stop路径
#例如 pm2 delete D:\myWork\yapi\my-yapi\vendors\server\app.js

 保存项目,才能开机自启动

pm2 save

  

扩展阅读

pm2 以 windows 服务运行

通过上面 pm2-windows-startup 的方式【推荐】,我们在windows 服务里面是找不到 pm2 相关服务的,它是基于 start-on-windows-boot 在注册表中将 PM2 设为自启动程序,从而实现自启动。

而 pm2-windows-service 基于 node-windows 将 PM2 注册为 Windows 服务。

两种方案经测试,只有 pm2-windows-startup 在 Windows Server 2012 上可行,故选择 pm2-windows-startup 作为解决 Node.js 应用开机自启动的方案。

所以,这里只顺带说说 pm2 以 windows 服务运行的操作步骤:

1、

npm i pm2 -g

2、

npm i pm2-windows-service -g

3、安装服务:

pm2-service-install -n myservice

 

 (安装后在windows服务中多了一个myservice的服务)

     卸载命令:

pm2-service-uninstall

 

4、设置环境变量:

PM2_SERVICE_SCRIPTS = PM2

 

的配置文件

5、windows 服务中重新启动 myservice 服务

  

posted @ 2022-12-23 17:26  不再犯错  阅读(719)  评论(0)    收藏  举报