PM2默认会在应用程序崩溃时自动重启,如果需要高级配置的话可以创建一个 ecosystem.config.js 文件来配置 PM2 如何管理你的应用程序。
module.exports = {
apps: [
{
name: "app",
script: "./app.js",
// 自动重启选项
watch: true, // 监视文件变化以自动重启
max_memory_restart: "200M", // 如果内存使用超过200M,重启应用
instances: "max", // 启动最大数量的实例(根据CPU核心数)
exec_mode: "cluster", // 使用集群模式
autorestart: true, // 启用自动重启
max_restarts: 10, // 最大重启次数
restart_delay: 5000, // 重启延迟(毫秒)
},
],
};
使用 watch 选项可以让 PM2 在检测到文件变化时自动重启应用程序。
如果是系统重启后恢复,可以使用 PM2 提供的 startup 命令。
pm2 startup
pm2 save