gpt4 book ai didi

node.js - 如何在服务器重启时运行 Node js

转载 作者:搜寻专家 更新时间:2023-10-31 23:34:26 24 4
gpt4 key购买 nike

我搭建了一个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

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

注意:这可能不是最好的解决方案,但我已经找到了。

更新

正如@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 分享链接。

关于node.js - 如何在服务器重启时运行 Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45780626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com