如何在服务器重新启动后运行Node.js

3

我建立了一个Nodejs项目,现在运行顺畅。 我使用forever服务来在后台运行文件,但如果服务器重新启动, 守护进程不会自动启动,需要手动启动。 我想要即使服务器重新启动也能运行守护进程。


你的服务器使用什么操作系统? - Raghav Garg
@RaghavGarg 我正在使用CentOS 7。 - ari ari
你尝试过forever, pm2, nodemon吗? - jonrsharpe
1
你应该与 systemd 集成,它有许多优点。 - dlmeetei
1个回答

7

您可以在.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分享链接。


2
这将只在你启动bash时启动服务器。最好与systemd集成或基于lsb编写init.d脚本。 - dlmeetei
@dlmeetei,我在Unix系统方面不是很擅长。你是建议将其制作成服务吗?如果不是,请分享一下如何使用systemd或init.d来完成,哪个更好? - Raghav Garg
1
也许这个链接可以帮助你:https://www.axllent.org/docs/view/nodejs-service-with-systemd/ - dlmeetei
@dlmeetei,这似乎是一个不错的方法,我还没有想过像服务一样启动一个节点应用程序。感谢分享链接。 - Raghav Garg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接