如何将 node.js 应用程序作为后台服务运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4018154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I run a node.js app as a background service?
提问by Peter Kruithof
Since this post has gotten a lot of attention over the years, I've listed the top solutions per platform at the bottom of this post.
由于这篇文章多年来受到了很多关注,我在这篇文章的底部列出了每个平台的最佳解决方案。
Original post:
原帖:
I want my node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the 2>&1 >> filepart), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.
我希望我的 node.js 服务器在后台运行,即:当我关闭终端时,我希望我的服务器继续运行。我在谷歌上搜索了这个并想出了这个教程,但是它没有按预期工作。因此,我没有使用该守护程序脚本,而是认为我只是使用了输出重定向(2>&1 >> file部分),但这也没有退出 - 我的终端中有一个空行,就像它在等待输出/错误一样。
I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well.
我也尝试将进程置于后台,但是一旦我关闭终端,进程也会被终止。
So how can I leave it running when I shut down my local computer?
那么,当我关闭本地计算机时,如何让它继续运行呢?
Top solutions:
顶级解决方案:
- Systemd(Linux)
- Launchd(Mac)
- node-windows(Windows)
- PM2(Node.js)
采纳答案by mikemaccana
Copying my own answer from How do I run a Node.js application as its own process?
2015 answer: nearly every Linux distro comes with systemd, which means forever, monit, PM2, etc are no longer necessary - your OS already handles these tasks.
2015 年回答:几乎每个 Linux 发行版都带有 systemd,这意味着永远不再需要 monit、PM2 等 - 您的操作系统已经处理了这些任务。
Make a myapp.servicefile (replacing 'myapp' with your app's name, obviously):
制作一个myapp.service文件(显然,用您的应用程序名称替换“myapp”):
[Unit]
Description=My app
[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp
[Install]
WantedBy=multi-user.target
Note if you're new to Unix:/var/www/myapp/app.jsshould have #!/usr/bin/env nodeon the very first line.
请注意,如果您是 Unix 新手:/var/www/myapp/app.js应该#!/usr/bin/env node在第一行。
Copy your service file into the /etc/systemd/system.
将您的服务文件复制到/etc/systemd/system.
Start it with systemctl start myapp.
以systemctl start myapp.
Enable it to run on boot with systemctl enable myapp.
启用它以在启动时运行systemctl enable myapp。
See logs with journalctl -u myapp
查看日志 journalctl -u myapp
This is taken from How we deploy node apps on Linux, 2018 edition, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the .servicefile).
这取自我们如何在 Linux 上部署节点应用程序,2018 版,其中还包括生成 AWS/DigitalOcean/Azure CloudConfig 以构建 Linux/节点服务器(包括.service文件)的命令。
回答by muzz
You can use Forever, A simple CLI tool for ensuring that a given node script runs continuously (i.e. forever): https://www.npmjs.org/package/forever
您可以使用 Forever,一个简单的 CLI 工具来确保给定的节点脚本连续(即永远)运行:https: //www.npmjs.org/package/forever
回答by NG.
UPDATE- As mentioned in one of the answers below, PM2has some really nice functionality missing from forever. Consider using it.
更新- 正如下面的一个答案中提到的,PM2有一些非常好的功能永远缺失。考虑使用它。
Original Answer
原答案
Use nohup:
使用nohup:
nohup node server.js &
EDITI wanted to add that the accepted answer is really the way to go. I'm using forever on instances that need to stay up. I like to do npm install -g foreverso it's in the node path and then just do forever start server.js
编辑我想补充一点,接受的答案确实是要走的路。我在需要熬夜的实例上永远使用。我喜欢这样做npm install -g forever,它在节点路径中,然后就这样做forever start server.js
回答by Brent
This might not be the accepted way, but I do it with screen, especially while in development because I can bring it back up and fool with it if necessary.
这可能不是公认的方式,但我用 screen 来做,特别是在开发过程中,因为我可以在必要时把它带回来并愚弄它。
screen
node myserver.js
>>CTRL-A then hit D
The screen will detach and survive you logging off. Then you can get it back back doing screen -r. Hit up the screen manual for more details. You can name the screens and whatnot if you like.
屏幕将分离并在您注销后继续存在。然后你可以通过 screen -r 取回它。点击屏幕手册了解更多详情。如果您愿意,您可以命名屏幕等等。
回答by Corey
2016 Update:The node-windows/mac/linux series uses a common API across all operating systems, so it is absolutely a relevant solution. However; node-linux generates systemv init files. As systemd continues to grow in popularity, it is realistically a better option on Linux. PR's welcome if anyone wants to add systemd support to node-linux :-)
2016 更新:node-windows/mac/linux 系列使用跨所有操作系统的通用 API,因此它绝对是一个相关的解决方案。然而; node-linux 生成 systemv init 文件。随着 systemd 越来越流行,它实际上是 Linux 上更好的选择。如果有人想为 node-linux 添加 systemd 支持,欢迎 PR :-)
Original Thread:
原始线程:
This is a pretty old thread now, but node-windowsprovides another way to create background services on Windows. It is loosely based on the nssmconcept of using an exewrapper around your node script. However; it uses winsw.exeinstead and provides a configurable node wrapper for more granular control over how the process starts/stops on failures. These processes are available like any other service:
现在这是一个很老的线程,但是node-windows提供了另一种在 Windows 上创建后台服务的方法。它松散地基于在节点脚本周围nssm使用exe包装器的概念。然而; 它使用winsw.exe并提供了一个可配置的节点包装器,以便更精细地控制进程如何在失败时启动/停止。这些流程与任何其他服务一样可用:


The module also bakes in some event logging:
该模块还包含一些事件日志记录:


Daemonizing your script is accomplished through code. For example:
守护您的脚本是通过代码完成的。例如:
var Service = require('node-windows').Service;
// Create a new service object
var svc = new Service({
name:'Hello World',
description: 'The nodejs.org example web server.',
script: 'C:\path\to\my\node\script.js'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
// Listen for the "start" event and let us know when the
// process has actually started working.
svc.on('start',function(){
console.log(svc.name+' started!\nVisit http://127.0.0.1:3000 to see it in action.');
});
// Install the script as a service.
svc.install();
The module supports things like capping restarts (so bad scripts don't hose your server) and growing time intervals between restarts.
该模块支持限制重启(这样糟糕的脚本不会影响你的服务器)和增加重启之间的时间间隔之类的东西。
Since node-windows services run like any other, it is possible to manage/monitor the service with whatever software you already use.
由于 node-windows 服务像任何其他服务一样运行,因此可以使用您已经使用的任何软件来管理/监视服务。
Finally, there are no makedependencies. In other words, a straightforward npm install -g node-windowswill work. You don't need Visual Studio, .NET, or node-gyp magic to install this. Also, it's MIT and BSD licensed.
最后,没有make依赖关系。换句话说,直截了当的npm install -g node-windows工作。您不需要 Visual Studio、.NET 或 node-gyp 魔法来安装它。此外,它是 MIT 和 BSD 许可的。
In full disclosure, I'm the author of this module. It was designed to relieve the exact pain the OP experienced, but with tighter integration into the functionality the Operating System already provides. I hope future viewers with this same question find it useful.
完全公开,我是这个模块的作者。它旨在减轻 OP 所经历的确切痛苦,但更紧密地集成到操作系统已经提供的功能中。我希望未来有同样问题的观众觉得它很有用。
回答by Hutch
UPDATE: i updated to include the latest from pm2:
更新:我更新为包括来自 pm2 的最新消息:
for many use cases, using a systemd service is the simplest and most appropriate way to manage a node process. for those that are running numerous node processes or independently-running node microservices in a single environment, pm2 is a more full featured tool.
对于许多用例,使用 systemd 服务是管理节点进程的最简单、最合适的方法。对于那些在单个环境中运行多个节点进程或独立运行节点微服务的人来说,pm2 是一个功能更齐全的工具。
https://github.com/unitech/pm2
https://github.com/unitech/pm2
- it has a really useful monitoring feature -> pretty 'gui' for command line monitoring of multiple processes with
pm2 monitor process list withpm2 list - organized Log management ->
pm2 logs - other stuff:
- Behavior configuration
- Source map support
- PaaS Compatible
- Watch & Reload
- Module System
- Max memory reload
- Cluster Mode
- Hot reload
- Development workflow
- Startup Scripts
- Auto completion
- Deployment workflow
- Keymetrics monitoring
- API
- 它有一个非常有用的监控功能 -> 漂亮的“gui”,用于命令行监控多个进程
pm2 monit或进程列表pm2 list - 有组织的日志管理 ->
pm2 logs - 其他的东西:
- 行为配置
- 源地图支持
- PaaS 兼容
- 观看并重新加载
- 模块系统
- 最大内存重载
- 集群模式
- 热重载
- 开发工作流程
- 启动脚本
- 自动完成
- 部署工作流
- 关键指标监控
- 应用程序接口
回答by Lars Christensen
If you are running OSX, then the easiest way to produce a true system process is to use launchdto launch it.
如果您正在运行 OSX,那么生成真正系统进程的最简单方法是使用launchd启动它。
Build a plist like this, and put it into the /Library/LaunchDaemons with the name top-level-domain.your-domain.application.plist(you need to be root when placing it):
像这样构建一个plist,并把它放到/Library/LaunchDaemons 中,并命名为top-level-domain.your-domain.application.plist(放置时需要是root):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>top-level-domain.your-domain.application</string>
<key>WorkingDirectory</key>
<string>/your/preferred/workingdirectory</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/node</string>
<string>your-script-file</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
When done, issue this (as root):
完成后,发出此命令(以 root 身份):
launchctl load /Library/LaunchDaemons/top-level-domain.your-domain.application.plist
launchctl start top-level-domain.your-domain.application
and you are running.
你正在跑步。
And you will still be running after a restart.
并且您在重新启动后仍将运行。
For other options in the plist look at the man page here: https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html
有关 plist 中的其他选项,请查看此处的手册页:https: //developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html
回答by Xeoncross
If you simply want to run the script uninterrupted until it completes you can use nohupas already mentioned in the answers here. However, none of the answers provide a full command that also logs stdinand stdout.
如果您只想不间断地运行脚本,直到它完成,您可以使用nohup此处的答案中已经提到的方法。但是,没有一个答案提供一个完整的命令,同时记录stdin和stdout.
nohup node index.js >> app.log 2>&1 &
- The
>>means append toapp.log. 2>&1makes sure that errors are also send tostdoutand added to theapp.log.- The ending
&makes sure your current terminal is disconnected from command so you can continue working.
- 该
>>方法追加到app.log。 2>&1确保错误也发送到stdout并添加到app.log.- 结尾
&确保您当前的终端与命令断开连接,以便您可以继续工作。
If you want to run a node server (or something that should start back up when the server restarts) you should use systemd / systemctl.
如果你想运行一个节点服务器(或者当服务器重启时应该启动的东西)你应该使用systemd / systemctl。
回答by Himanshu Teotia
Try to run this command if you are using nohup -
如果您使用 nohup,请尝试运行此命令 -
nohup npm start 2>/dev/null 1>/dev/null&
You can also use forever to start server
您也可以使用永远启动服务器
forever start -c "npm start" ./
PM2 also supports npm start
PM2也支持 npm start
pm2 start npm -- start
回答by LoG
I am simply using the daemonnpm module:
我只是使用守护进程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
});
Lately I'm also using mon(1)from TJ Holowaychukto start and manage simple node apps.
最近我还使用星期一(1)从TJ Holowaychuk启动和管理简单节点的应用程序。

