由于这篇文章在过去几年里受到了很多关注,所以我在文章的底部列出了每个平台的最佳解决方案。


原来的帖子:

我希望我的node.js服务器在后台运行,即:当我关闭我的终端时,我希望我的服务器继续运行。我在谷歌上搜索过这个,并提出了这个教程,但它并不像预期的那样工作。因此,我没有使用这个守护进程脚本,我认为我只是使用了输出重定向(2>&1 >>文件部分),但这也不退出-我在终端中得到一个空行,就像它在等待输出/错误一样。

我也尝试过把进程放在后台,但是只要我关闭终端,进程就会被杀死。

那么,当我关闭本地计算机时,如何让它继续运行呢?


高级解决方案:

Systemd (Linux) Launchd (Mac) node-windows (Windows) PM2 (node . js)


当前回答

我只是使用daemon npm模块:

var daemon = require('daemon');

daemon.daemonize({
    stdout: './log.log'
  , stderr: './log.error.log'
  }
, './node.pid'
, function (err, pid) {
  if (err) {
    console.log('Error starting daemon: \n', err);
    return process.exit(-1);
  }
  console.log('Daemonized successfully with pid: ' + pid);

  // Your Application Code goes here
});

最近,我还使用TJ Holowaychuk的mon(1)来启动和管理简单的节点应用程序。

其他回答

PM2是一个用于Node.js应用程序的生产进程管理器,具有内置的负载均衡器。它允许您让应用程序永远处于活动状态,在没有停机时间的情况下重新加载它们,并方便执行常见的系统管理任务。 https://github.com/Unitech/pm2

这个答案有点晚了,但是我发现最好的解决方案是编写一个同时使用screen -dmS和nohup命令的shell脚本。

screen -dmS newScreenName nohup node myserver.js >> logfile.log

我还在末尾添加了>>日志文件位,这样我就可以轻松地保存节点console.log()语句。

为什么我要使用shell脚本?我还添加了一个if语句,检查节点myserver.js进程是否已经在运行。

通过这种方式,我可以创建一个命令行选项,既可以让我保持服务器运行,也可以在我进行更改时重新启动服务器,这对开发非常有帮助。

2017年6月更新: Linux解决方案:(Red hat)。之前的评论对我不起作用。 这适用于我的亚马逊网络服务-红帽7。希望这对外面的人有用。

A. Create the service file 
sudo vi /etc/systemd/system/myapp.service
[Unit]
Description=Your app
After=network.target

[Service]
ExecStart=/home/ec2-user/meantodos/start.sh
WorkingDirectory=/home/ec2-user/meantodos/

[Install]
WantedBy=multi-user.target

B. Create a shell file
/home/ec2-root/meantodos/start.sh
#!/bin/sh -
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to 8080
npm start

then:
chmod +rx /home/ec2-root/meantodos/start.sh
(to make this file executable)

C. Execute the Following

sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl status myapp

(If there are no errors, execute below.  Autorun after server restarted.)
chkconfig myapp -add

我很惊讶居然没有人提到Guvnor

我一直在尝试,pm2,等等。但是,当谈到可靠的控制和基于网络的性能指标时,我发现Guvnor是迄今为止最好的。另外,它也是完全开源的。

编辑:但是,我不确定它是否在windows上工作。我只在linux上使用过。

当我在RHEL 8 AWS EC2实例上使用@mikemaccana的接受答案时,我收到了以下错误:(code=exited, status=216/GROUP)

这是由于使用用户/组设置为:'nobody'。

在谷歌上搜索,似乎使用用户/组作为'nobody'/'nogroup'对守护进程来说是不好的实践,就像在unix堆栈交换中回答的那样。

在我将用户/组设置为我的实际用户和组后,它工作得很好。

您可以输入whoai和组来查看可用的解决此问题的选项。

我的服务文件为mongodb的全堆栈节点应用程序:

[Unit]
Description=myapp
After=mongod.service

[Service]
ExecStart=/home/myusername/apps/myapp/root/build/server/index.js
Restart=always
RestartSec=30
User=myusername
Group=myusername
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/home/myusername/apps/myapp

[Install]
WantedBy=multi-user.target