【问题标题】:How NodeJS server running for everNode JS 服务器如何永远运行
【发布时间】:2014-10-11 23:23:54
【问题描述】:

我使用腻子。 当我用“node X.js”启动服务器时,腻子启动服务器运行。 如果我从腻子退出服务器停止。 如何在重启或重启服务器(计算机)后使其保持运行并使其默认运行?

我有 centos 5.10。 谢谢!

【问题讨论】:

    标签: node.js centos


    【解决方案1】:

    有几种方法,我个人永远喜欢。

    sudo npm install -g forever
    forever start app.js &
    

    请注意,以 & 结尾会将进程分叉到后台。

    您可以稍后检查该过程

    forever list
    

    要在系统重新启动时运行它,您可以添加到 cron

    @reboot forever start app.js  &> /dev/null
    

    记得指向app.js的绝对位置

    【讨论】:

    • 如果我的电脑重启,NodeJS服务器永远会自动启动吗?谢谢!
    • 是的。 Forever 将创建两个进程。一个负责运行“node app.js”,另一个负责监控第一个并在需要时重新启动
    • 这并没有回答关于重启的问题。因为在那种情况下,两个进程都死了。
    • Forever 将在每次重启后自行运行。这就是 cron 中的 @reboot 条目所做的。
    【解决方案2】:

    我用pm2来做

    安装 pm2

    sudo npm install -g pm2
    

    生成启动脚本

    pm2 startup ubuntu(centos in your case)
    

    然后pm2会提示你运行的命令,在我的情况下,就像

    PM2 You have to run this command as root
    PM2 Execute the following command :
    PM2 sudo env PATH=$PATH:/usr/bin pm2 startup ubuntu -u USERNAME
    

    然后你可以运行

    sudo env PATH=$PATH:/usr/bin pm2 startup ubuntu -u USERNAME
    

    然后你可以看到

    PM2 Generating system init script in /etc/init.d/pm2-init.sh
    PM2 Making script booting at startup...
    PM2 -ubuntu- Using the command su -c "chmod +x /etc/init.d/pm2-init.sh && update-rc.d pm2-init.sh defaults"
    Adding system startup for /etc/init.d/pm2-init.sh ...
       /etc/rc0.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
       /etc/rc1.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
       /etc/rc6.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
       /etc/rc2.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
       /etc/rc3.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
       /etc/rc4.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
       /etc/rc5.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
    
    PM2 Done.
    

    一旦您启动了应用程序并希望在服务器重启时保留它们,请执行以下操作:

     pm2 save
    

    您可以参考https://github.com/Unitech/pm2#startup-script中的启动脚本部分

    【讨论】:

    • 应用列表是自动更新还是需要pm2 save调用?
    • pm2 save 会让 PM2 保存进程。当系统启动备份时,它将重新启动这些。
    • 我的意思是,当我开始一个新进程时,列表会自动保存吗?
    • 是的,第一次pm2保存运行后自动保存
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2023-03-27
    • 2020-11-08
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多