You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Elastic Beanstalk中Node应用崩溃后无法自动重启求助

AWS Elastic Beanstalk Node应用崩溃不自动重启的解决办法

一、别用nodemon了,换pm2的正确配置

nodemon是开发工具,崩溃后默认只会等文件改动才重启,完全不适合生产环境的自动重启需求。按下面步骤配置pm2:

  1. 安装pm2到项目依赖
    在项目根目录执行:

    npm install pm2 --save
    
  2. 创建pm2配置文件
    项目根目录新建ecosystem.config.js,内容如下:

    module.exports = {
      apps: [{
        name: "你的应用名称",
        script: "./app.js",
        interpreter: "babel-node",
        args: "--expose-gc --max-old-space-size=4096",
        instances: 1,
        autorestart: true, // 开启崩溃自动重启
        watch: false, // 生产环境关掉文件监听
        max_memory_restart: "4G", // 内存超4G自动重启
        env: {
          NODE_ENV: "production"
        }
      }]
    };
    
  3. 修改package.json的start脚本
    必须用pm2-runtime启动,让pm2保持前台运行——EB会监控主进程,要是主进程后台运行,EB会以为进程退出直接终止容器:

    "scripts": {
      "start": "pm2-runtime start ecosystem.config.js"
    }
    
  4. Procfile保持原来的就行

    web: npm start
    

二、之前pm2/forever失效的原因排查

之前换pm2/forever没用,大概率是这几个坑:

  • 用了pm2 start而非pm2-runtime:前者会让pm2后台跑,EB的监控进程会判定主进程(npm start)已退出,直接干掉容器,根本轮不到自动重启。
  • 没开autorestart:虽然pm2默认开,但如果配置里手动关了就不会触发。
  • 权限问题:别全局装pm2,一定要装到项目依赖里,避免EB运行用户没权限执行。

三、可选:加EB进程监控配置

要是还不行,给EB加个监控配置文件强制兜底。项目根目录建.ebextensions/process-monitor.config,内容如下:

commands:
  01_install_monit:
    command: sudo yum install -y monit
    ignoreErrors: true
files:
  "/etc/monit.d/node-app.monit":
    mode: "000644"
    owner: root
    group: root
    content: |
      check process node-app with pidfile /var/app/current/node_modules/pm2/pids/你的应用名称-0.pid
        start program = "/usr/bin/npm start" with timeout 60 seconds
        stop program = "/usr/bin/npm stop"
        if failed port 8080 for 5 cycles then restart
        if 3 restarts within 5 cycles then timeout

记得把你的应用名称换成pm2配置里的名字,端口改成你的应用监听端口。

四、测试重启机制

部署完手动杀进程验证:

  1. 连到EB实例:eb ssh
  2. 看pm2进程列表:pm2 list
  3. 删除进程:pm2 delete 你的应用名称
  4. 看pm2日志:pm2 logs,确认是不是自动重启了。

内容的提问来源于stack exchange,提问作者itdeeps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:28:22