如何将 node.js 应用程序作为后台服务运行? [英] How do I run a node.js app as a background service?

查看:35
本文介绍了如何将 node.js 应用程序作为后台服务运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这篇文章多年来受到了很多关注,我在这篇文章的底部列出了每个平台的最佳解决方案.

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.

原帖:

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

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 >> file part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.

我也尝试将进程置于后台,但是一旦我关闭终端,进程也会被终止.

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?

最佳解决方案:

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

推荐答案

Copying my own answer from 如何将 Node.js 应用程序作为自己的进程运行?

Copying my own answer from How do I run a Node.js application as its own process?

2015 年回答:几乎每个 Linux 发行版都带有 systemd,这意味着永远不再需要 monit、PM2 等 - 您的操作系统已经处理了这些任务.

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.

制作一个 myapp.service 文件(显然,用您的应用程序名称替换myapp"):

Make a myapp.service file (replacing 'myapp' with your app's name, obviously):

[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

请注意,如果您是 Unix 新手: /var/www/myapp/app.js 应该有 #!/usr/bin/env 节点 在第一行并打开可执行模式chmod +x myapp.js.

Note if you're new to Unix: /var/www/myapp/app.js should have #!/usr/bin/env node on the very first line and have the executable mode turned on chmod +x myapp.js.

将您的服务文件复制到/etc/systemd/system.

Copy your service file into the /etc/systemd/system.

使用 systemctl start myapp 启动它.

使用 systemctl enable myapp 使其在启动时运行.

Enable it to run on boot with systemctl enable myapp.

使用 journalctl -u myapp

这取自 我们如何在 Linux 上部署节点应用程序,2018 版,其中还包括生成 AWS/DigitalOcean/Azure CloudConfig 以构建 Linux/节点服务器的命令(包括 .service 文件).

这篇关于如何将 node.js 应用程序作为后台服务运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆