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