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

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

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

1
npm install pm2 -g

  

egg.js 部署步骤

1
npm init egg --type=simple

  

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

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

  


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

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

  

如果域名需要https

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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安装依赖

1
cnpm install --production // 安装依赖

用PM2启动程序

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

​ PM简单使用介绍

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

  

pm2开机重启

全局安装pm2 Win自启包

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

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

1
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、

1
npm i pm2 -g

2、

1
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 @   不再犯错  阅读(583)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2019-12-23 sqlserver 时间格式 取年月日时分
2016-12-23 js版弹力球实例
点击右上角即可分享
微信分享提示