繁体   English   中英

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

[英]How to run node js even on server restart

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

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

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

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

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

更新

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

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

touch /etc/systemd/system/[your-app-name].service
nano /etc/systemd/system/[your-app-name].service

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

[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 

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

systemctl enable [your-app-name].service

管理服务

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

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

感谢@dlmeetei分享链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM