node.js 系统重启时自动永久启动(节点)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13385029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:39:03  来源:igfitidea点击:

Automatically start forever (node) on system restart

node.jscentosforever

提问by kehers

I am using node's forever module to keep my node server running. Forever however terminates when there is a system restart. Is there any way I can automatically start the node server (with forever) when the system restarts?

我正在使用节点的永远模块来保持我的节点服务器运行。然而,当系统重新启动时,永远终止。有什么办法可以在系统重新启动时自动启动节点服务器(永远)?

回答by Julian Lannigan

I would suggest using crontab. It's easy to use.

我建议使用 crontab。它很容易使用。

How to

如何

  1. To start editing run the following replacing the "testuser" with your desired runtime user for the node process. If you choose a different user other than yourself, you will have to run this with sudo.

    $ crontab -u testuser -e
    
  2. If you have never done this before, it will ask you which editor you wish to edit with. I like vim, but will recommend nano for ease of use.

  3. Once in the editor add the following line:

    @reboot /usr/local/bin/forever start /your/path/to/your/app.js
    
  4. Save the file. You should get some feedback that the cron has been installed.

  5. For further confirmation of the installation of the cron, execute the following (again replacing "testuser" with your target username) to list the currently installed crons:

    $ crontab -u testuser -l 
    
  1. 要开始编辑,请运行以下命令,将“testuser”替换为节点进程所需的运行时用户。如果您选择的不是您自己的其他用户,则必须使用 sudo 运行它。

    $ crontab -u testuser -e
    
  2. 如果您以前从未这样做过,它会询问您希望使用哪个编辑器进行编辑。我喜欢 vim,但会推荐 nano 以便于使用。

  3. 在编辑器中添加以下行:

    @reboot /usr/local/bin/forever start /your/path/to/your/app.js
    
  4. 保存文件。你应该得到一些关于 cron 已经安装的反馈。

  5. 要进一步确认 cron 的安装,请执行以下命令(再次将“testuser”替换为您的目标用户名)以列出当前安装的 cron:

    $ crontab -u testuser -l 
    

Note that in my opinion, you should always use full paths when executing binaries in cron. Also, if the path to your forever script is not correct, run which foreverto get the full path.

请注意,在我看来,在 cron 中执行二进制文件时应始终使用完整路径。此外,如果您的永久脚本的路径不正确,请运行which forever以获取完整路径。

Given that forevercalls node, you may also want to provide the full path to node:

鉴于forever调用node,您可能还需要提供完整路径node

@reboot /usr/local/bin/forever start -c /usr/local/bin/node /your/path/to/your/app.js

Further Reading

进一步阅读

回答by arva

You can use forever-service for doing this.

您可以使用永久服务来执行此操作。

npm install -g forever-service
forever-service install test

This will provision app.js in the current directory as a service via forever. The service will automatically restart every time system is restarted. Also when stopped it will attempt a graceful stop. This script provisions the logrotate script as well.

这将通过永久将当前目录中的 app.js 作为服务提供。每次系统重新启动时,该服务将自动重新启动。此外,当停止时,它会尝试正常停止。此脚本也提供 logrotate 脚本。

Github url: https://github.com/zapty/forever-service

Github 网址:https: //github.com/zapty/forever-service

NOTE: I am the author of forever-service.

注意:我是永远服务的作者。

回答by NiLL

This case is valid for Debian.

这种情况对 Debian 有效。

Add the following to /etc/rc.local

将以下内容添加到 /etc/rc.local

/usr/bin/sudo -u {{user}} /usr/local/bin/forever start {{app path}}

/usr/bin/sudo -u {{user}} /usr/local/bin/forever start {{app path}}

  • {{user}}replaces your username.
  • {{app path}}replaces your app path. For example, /var/www/test/app.js
  • {{user}}替换您的用户名。
  • {{app path}}替换您的应用程序路径。例如,/var/www/test/app.js

回答by fsamuel

  1. Install PM2 globally using NPM

    npm install pm2 -g

  2. Start your script with pm2

    pm2 start app.js

  3. generate an active startup script

    pm2 startup

    NOTE: pm2 startup is for startting the PM2 when the system reboots. PM2 once started, restarts all the processes it had been managing before the system went down.

  1. 使用 NPM 全局安装 PM2

    npm install pm2 -g

  2. 用 pm2 启动你的脚本

    pm2 start app.js

  3. 生成一个活动的启动脚本

    pm2 startup

    注意:pm2 startup 用于在系统重新启动时启动 PM2。PM2 启动后,会重新启动系统崩溃之前它一直在管理的所有进程。

In case you want to disable the automatic startup, simply use pm2 unstartup

如果您想禁用自动启动,只需使用 pm2 unstartup

If you want the startup script to be executed under another user, just use the -u <username>option and the --hp <user_home>:

如果您希望在另一个用户下执行启动脚本,只需使用-u <username>选项和--hp <user_home>:

回答by Emre

An alternative crontab method inspired by thisanswer and thisblog post.

另一种方法crontab的灵感来自这个答案,这个博客帖子。

1. Create a bash script file (change bob to desired user).

1. 创建一个 bash 脚本文件(将 bob 更改为所需用户)。

vi /home/bob/node_server_init.sh

2. Copy and paste this inside the file you've just created.

2. 将其复制并粘贴到您刚刚创建的文件中。

#!/bin/sh

export NODE_ENV=production
export PATH=/usr/local/bin:$PATH
forever start /node/server/path/server.js > /dev/null

Make sure to edit the paths above according to your config!

确保根据您的配置编辑上面的路径!

3. Make sure the bash script can be executed.

3. 确保 bash 脚本可以执行。

chmod 700 /home/bob/node_server_init.sh

4. Test the bash script.

4. 测试 bash 脚本。

sh /home/bob/node_server_init.sh

5. Replace "bob" with the runtime user for node.

5. 将“bob”替换为节点的运行时用户。

crontab -u bob -e

6. Copy and paste (change bob to desired user).

6. 复制和粘贴(将 bob 更改为所需的用户)。

@reboot /bin/sh /home/bob/node_server_init.sh

Save the crontab.

保存 crontab。

You've made it to the end, your prize is a reboot (to test) :)

你已经完成了,你的奖品是重启(测试):)

回答by Vikash Rajpurohit

Copied answer from the attached question.

从附加问题复制答案。

You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.

您可以使用PM2,它是具有内置负载均衡器的 Node.js 应用程序的生产流程管理器。

Install PM2

安装 PM2

$ npm install pm2 -g

Start an application

启动应用程序

$ pm2 start app.js

If you using express then you can start your app like

如果您使用快递,那么您可以像这样启动您的应用程序

pm2 start ./bin/www --name="app"

Listing all running processes:

列出所有正在运行的进程:

$ pm2 list

It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.

它将列出所有进程。然后,您可以通过以下命令使用应用程序的 ID 或名称来停止/重新启动您的服务。

$ pm2 stop all                  
$ pm2 stop 0                    
$ pm2 restart all               

To display logs

显示日志

$ pm2 logs ['all'|app_name|app_id]

回答by Hector Correa

You need to create a shell script in the /etc/init.d folder for that. It's sort of complicated if you never have done it but there is plenty of information on the web on init.d scripts.

为此,您需要在 /etc/init.d 文件夹中创建一个 shell 脚本。如果您从未这样做过,这会有点复杂,但网络上有大量关于 init.d 脚本的信息。

Here is a sample a script that I created to run a CoffeeScript site with forever:

这是我创建的一个脚本示例,用于永久运行 CoffeeScript 站点:

#!/bin/bash
#
# initd-example      Node init.d 
#
# chkconfig: 345 
# description: Script to start a coffee script application through forever
# processname: forever/coffeescript/node
# pidfile: /var/run/forever-initd-hectorcorrea.pid 
# logfile: /var/run/forever-initd-hectorcorrea.log
#
# Based on a script posted by https://gist.github.com/jinze at https://gist.github.com/3748766
#


# Source function library.
. /lib/lsb/init-functions


pidFile=/var/run/forever-initd-hectorcorrea.pid 
logFile=/var/run/forever-initd-hectorcorrea.log 

sourceDir=/home/hectorlinux/website
coffeeFile=app.coffee
scriptId=$sourceDir/$coffeeFile


start() {
    echo "Starting $scriptId"

    # This is found in the library referenced at the top of the script
    start_daemon

    # Start our CoffeeScript app through forever
    # Notice that we change the PATH because on reboot
    # the PATH does not include the path to node.
    # Launching forever or coffee with a full path
    # does not work unless we set the PATH.
    cd $sourceDir
    PATH=/usr/local/bin:$PATH
    NODE_ENV=production PORT=80 forever start --pidFile $pidFile -l $logFile -a -d --sourceDir $sourceDir/ -c coffee $coffeeFile

    RETVAL=$?
}

restart() {
    echo -n "Restarting $scriptId"
    /usr/local/bin/forever restart $scriptId
    RETVAL=$?
}

stop() {
    echo -n "Shutting down $scriptId"
    /usr/local/bin/forever stop $scriptId
    RETVAL=$?
}

status() {
    echo -n "Status $scriptId"
    /usr/local/bin/forever list
    RETVAL=$?
}


case "" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        restart
        ;;
    *)
        echo "Usage:  {start|stop|status|restart}"
        exit 1
        ;;
esac
exit $RETVAL

I had to make sure the folder and PATHs were explicitly set or available to the root user since init.d scripts are ran as root.

由于 init.d 脚本以 root 身份运行,因此我必须确保文件夹和 PATH 已明确设置或可供 root 用户使用。

回答by Vishnu Mishra

Use the PM2

使用PM2

Which is the best option to run the server production server

哪个是运行服务器生产服务器的最佳选择

What are the advantages of running your application this way?

以这种方式运行您的应用程序有什么优势?

  • PM2 will automatically restart your application if it crashes.

  • PM2 will keep a log of your unhandled exceptions - in this case, in a file at /home/safeuser/.pm2/logs/app-err.log.

  • With one command, PM2 can ensure that any applications it manages restart when the server reboots. Basically, your node application will start as a service.

  • 如果您的应用程序崩溃,PM2 将自动重新启动它。

  • PM2 将保留未处理异常的日志 - 在这种情况下,保存在 /home/safeuser/.pm2/logs/app-err.log 的文件中。

  • 通过一个命令,PM2 可以确保它管理的任何应用程序在服务器重新启动时重新启动。基本上,您的节点应用程序将作为服务启动。

ref: https://www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps

参考:https: //www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps

回答by Vince Yuan

crontabdoes not work for me on CentOS x86 6.5. @reboot seems to be not working.

crontab在 CentOS x86 6.5 上对我不起作用。@reboot 似乎不起作用。

Finally I got this solution:

最后我得到了这个解决方案:

Edit:/etc/rc.local

编辑:/etc/rc.local

sudo vi /etc/rc.local

Add this line to the end of the file. Change USER_NAMEand PATH_TO_PROJECTto your own. NODE_ENV=productionmeans the app runs in production mode. You can add more lines if you need to run more than one node.js app.

将此行添加到文件末尾。改变USER_NAMEPATH_TO_PROJECT你自己的。NODE_ENV=production意味着应用程序在生产模式下运行。如果您需要运行多个 node.js 应用程序,您可以添加更多行。

su - USER_NAME -c "NODE_ENV=production /usr/local/bin/forever start /PATH_TO_PROJECT/app.js"

Don't set NODE_ENVin a separate line, your app will still run in development mode, because forever does not get NODE_ENV.

不要NODE_ENV在单独的行中设置,您的应用程序仍将在开发模式下运行,因为永远不会得到NODE_ENV.

# WRONG!
su - USER_NAME -c "export NODE_ENV=production"

Save and quit vi (press ESC : w q return). You can try rebooting your server. After your server reboots, your node.js app should run automatically, even if you don't log into any account remotely via ssh.

保存并退出 vi(按ESC : w q return)。您可以尝试重新启动服务器。在您的服务器重新启动后,您的 node.js 应用程序应该会自动运行,即使您没有通过 ssh 远程登录任何帐户。

You'd better set NODE_ENVenvironment in your shell. NODE_ENVwill be set automatically when your account USER_NAMElogs in.

你最好NODE_ENV在你的 shell 中设置环境。NODE_ENV将在您的帐户USER_NAME登录时自动设置。

echo export NODE_ENV=production >> ~/.bash_profile

So you can run commands like forever stop/start /PATH_TO_PROJECT/app.jsvia ssh without setting NODE_ENVagain.

因此,您可以/PATH_TO_PROJECT/app.js通过 ssh运行诸如永远停止/启动之类的命令,而无需NODE_ENV再次设置。

回答by snez

Forever was not made to get node applications running as services. The right approach is to either create an /etc/inittab entry (old linux systems) or an upstart (newer linux systems).

Forever 并不是为了让节点应用程序作为服务运行。正确的方法是创建一个 /etc/inittab 条目(旧的 linux 系统)或一个新贵(新的 linux 系统)。

Here's some documentation on how to set this up as an upstart: https://github.com/cvee/node-upstart

以下是有关如何将其设置为新贵的一些文档:https: //github.com/cvee/node-upstart