如何在服务器重启时运行节点js

ari*_*ari 3 linux centos node.js server

我构建了一个Nodejs项目,现在它运行顺利.我使用forever服务在后台运行文件,但如果服务器重新启动,守护程序将不会自动启动,应该手动启动.我想运行守护进程甚至服务器重新启动

Rag*_*arg 6

您可以添加forever命令,.bash_profile以便每次服务器重新启动时,您的命令也将被执行.

nano ~/.bash_profile
forever start app.js # add this command to the file, or whatever command you are using.
source ~/.bash_profile # very important, else changes will not take effect
Run Code Online (Sandbox Code Playgroud)

下次,在服务器重新启动时,您的命令也将运行,从而创建节点脚本的守护程序.

注意:这可能不是最好的解决方案,而是我得到的解决方案.

更新

正如@dlmeetei建议的那样,您也可以像服务一样启动nodejs应用程序,以便我们可以使用linux服务提供的功能.

首先创建一个文件/etc/systemd/system,如:

touch /etc/systemd/system/[your-app-name].service
nano /etc/systemd/system/[your-app-name].service
Run Code Online (Sandbox Code Playgroud)

然后,根据您的相关性添加和编辑以下脚本.

[Unit]
Description=Node.js Example Server
#Requires=After=mysql.service # Requires the mysql service to run first

[Service]
ExecStart=/usr/local/bin/node /opt/nodeserver/server.js
# Required on some systems
# WorkingDirectory=/opt/nodeserver
Restart=always
# Restart service after 10 seconds if node service crashes
RestartSec=10
# Output to syslog
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-example
#User=<alternate user>
#Group=<alternate group>
Environment=NODE_ENV=production PORT=1337

[Install]
WantedBy=multi-user.target 
Run Code Online (Sandbox Code Playgroud)

启用该服务,它将标记启动时启动的服务.

systemctl enable [your-app-name].service
Run Code Online (Sandbox Code Playgroud)

管理服务

systemctl start [your-app-name].service
systemctl stop [your-app-name].service
systemctl status [your-app-name].service # ensure your app is running
systemctl restart [your-app-name].service
Run Code Online (Sandbox Code Playgroud)

参考: https ://www.axllent.org/docs/view/nodejs-service-with-systemd/

感谢@dlmeetei分享链接.

  • 这只会在您启动bash时启动服务器。更好地与`systemd`集成或基于lsb编写init.d脚本。 (2认同)