Linux 如何将 Node.js 作为后台进程运行并且永不消亡?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4797050/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 00:13:29  来源:igfitidea点击:

How to run Node.js as a background process and never die?

node.jslinuxbackground-process

提问by murvinlai

I connect to the linux server via putty SSH. I tried to run it as a background process like this:

我通过 putty SSH 连接到 linux 服务器。我试图将它作为这样的后台进程运行:

$ node server.js &

However, after 2.5 hrs the terminal becomes inactive and the process dies. Is there anyway I can keep the process alive even with the terminal disconnected?

但是,2.5 小时后终端变为非活动状态并且进程终止。无论如何,即使终端断开连接,我也可以保持进程活跃吗?



Edit 1

编辑 1

Actually, I tried nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.

实际上,我尝试过nohup,但是只要我关闭 Putty SSH 终端或拔下互联网,服务器进程就会立即停止。

Is there anything I have to do in Putty?

我需要在 Putty 中做些什么吗?



Edit 2 (on Feb, 2012)

编辑 2(2012 年 2 月)

There is a node.jsmodule, forever. It will run node.js server as daemon service.

有一个node.js模块,永远。它将作为守护程序服务运行 node.js 服务器。

采纳答案by MK.

Simple solution(if you are not interested in coming back to the process, just want it to keep running):

简单的解决方案(如果您对返回进程不感兴趣,只希望它继续运行):

nohup node server.js &

There's also the jobscommand to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1or kill %2with the number being the index of the process.

还有一个jobs命令可以查看这些后台进程的索引列表。您可以通过运行kill %1kill %2将数字作为进程的索引来终止后台进程。

Powerful solution(allows you to reconnect to the process if it is interactive):

强大的解决方案(如果它是交互式的,则允许您重新连接到进程):

screen

You can then detach by pressing Ctrl+a+d and then attach back by running screen -r

然后,您可以通过按 Ctrl+a+d 分离,然后通过运行重新附加 screen -r

Also consider the newer alternative to screen, tmux.

还可以考虑屏幕的更新替代品 tmux。

回答by S.Lott

Have you read about the nohupcommand?

你读过nohup命令吗?

回答by Daniel Gallagher

nohupwill allow the program to continue even after the terminal dies. I have actually had situations where nohupprevents the SSH session from terminating correctly, so you should redirect input as well:

nohup即使在终端死机后,也将允许程序继续。我实际上遇到过nohup阻止 SSH 会话正确终止的情况,因此您也应该重定向输入:

$ nohup node server.js </dev/null &

Depending on how nohupis configured, you may also need to redirect standard output and standard error to files.

根据nohup配置方式,您可能还需要将标准输出和标准错误重定向到文件。

回答by Yoichi

nohup node server.js > /dev/null 2>&1 &

nohup node server.js > /dev/null 2>&1 &

  1. nohupmeans: Do not terminate this process even when the stty is cut off.
  2. > /dev/nullmeans: stdout goes to /dev/null (which is a dummy device that does not record any output).
  3. 2>&1means: stderr also goes to the stdout (which is already redirected to /dev/null). You may replace &1 with a file path to keep a log of errors, e.g.: 2>/tmp/myLog
  4. &at the end means: run this command as a background task.
  1. nohup意思是:即使 stty 被切断,也不要终止这个过程。
  2. > /dev/null意味着:stdout 转到 /dev/null(这是一个不记录任何输出的虚拟设备)。
  3. 2>&1意味着:stderr 也会转到 stdout(已重定向到/dev/null)。您可以用文件路径替换 &1 以保留错误日志,例如:2>/tmp/myLog
  4. &最后意味着:将此命令作为后台任务运行。

回答by myururdurmaz

another solution disown the job

另一个解决方案否认这项工作

$ nohup node server.js &
[1] 1711
$ disown -h %1

回答by Alex Povar

You really should try to use screen. It is a bit more complicated than just doing nohup long_running &, but understanding screen once you never come back again.

你真的应该尝试使用screen. 它比仅仅做要复杂一些nohup long_running &,但是一旦你不再回来就理解屏幕。

Start your screen session at first:

首先开始您的屏幕会话:

user@host:~$ screen

Run anything you want:

运行任何你想要的:

wget http://mirror.yandex.ru/centos/4.6/isos/i386/CentOS-4.6-i386-binDVD.iso

Press ctrl+A and then d. Done. Your session keeps going on in background.

按 ctrl+A,然后按 d。完毕。您的会话在后台继续进行。

You can list all sessions by screen -ls, and attach to some by screen -r 20673.pts-0.srvcommand, where 0673.pts-0.srv is an entry list.

您可以通过 列出所有会话screen -ls,并通过screen -r 20673.pts-0.srv命令附加到某些会话,其中 0673.pts-0.srv 是条目列表。

回答by thiagowfx

I have this function in my shell rc file, based on @Yoichi's answer:

我的 shell rc 文件中有这个函数,基于@Yoichi 的回答:

nohup-template () {
    [[ "" = "" ]] && echo "Example usage:\nnohup-template urxvtd" && return 0
    nohup "" > /dev/null 2>&1 &
}

You can use it this way:

你可以这样使用它:

nohup-template "command you would execute here"

回答by Skynet

$ disown node server.js &

It will remove command from active task list and send the command to background

它将从活动任务列表中删除命令并将命令发送到后台

回答by Donald Derek

Nohup and screen offer great light solutions to running Node.js in the background. Node.js process manager (PM2) is a handy tool for deployment. Install it with npm globally on your system:

Nohup 和 screen 为在后台运行 Node.js 提供了很好的轻量级解决方案。Node.js 进程管理器 ( PM2) 是一个方便的部署工具。在您的系统上使用 npm 全局安装它:

npm install pm2 -g

npm install pm2 -g

to run a Node.js app as a daemon:

将 Node.js 应用程序作为守护程序运行:

pm2 start app.js

pm2 start app.js

You can optionally link it to Keymetrics.ioa monitoring SAAS made by Unitech.

您可以选择将其链接到Keymetrics.io由 Unitech 制作的监控 SAAS。

回答by Victor Schr?der

This is an old question, but is high ranked on Google. I almost can't believe on the highest voted answers, because running a node.js process inside a screen session, with the &or even with the nohupflag -- all of them -- are just workarounds.

这是一个老问题,但在谷歌上排名很高。我几乎无法相信投票最高的答案,因为在 screen 会话中运行 node.js 进程,带有&或什至带有nohup标志 - 所有这些 - 只是解决方法。

Specially the screen/tmux solution, which should really be considered an amateursolution. Screen and Tmux are not meant to keep processes running, but for multiplexing terminal sessions. It's fine, when you are running a script on your server and want to disconnect. But for a node.js server your don't want your process to be attached to a terminal session. This is too fragile. To keep things running you need to daemonize the process!

特别是 screen/tmux 解决方案,它真的应该被视为业余解决方案。Screen 和 Tmux 并不是为了保持进程运行,而是为了多路复用终端会话。没关系,当您在服务器上运行脚本并想要断开连接时。但是对于 node.js 服务器,您不希望您的进程附加到终端会话。这太脆弱了。为了保持运行,您需要守护进程!

There are plenty of good tools to do that.

有很多很好的工具可以做到这一点。

PM2: http://pm2.keymetrics.io/

PM2http: //pm2.keymetrics.io/

# basic usage
$ npm install pm2 -g
$ pm2 start server.js

# you can even define how many processes you want in cluster mode:
$ pm2 start server.js -i 4

# you can start various processes, with complex startup settings
# using an ecosystem.json file (with env variables, custom args, etc):
$ pm2 start ecosystem.json

One big advantage I see in favor of PM2 is that it can generate the system startup script to make the process persist between restarts:

我认为支持 PM2 的一大优势是它可以生成系统启动脚本以使进程在重新启动之间保持不变:

$ pm2 startup [platform]

Where platformcan be ubuntu|centos|redhat|gentoo|systemd|darwin|amazon.

哪里platform可以ubuntu|centos|redhat|gentoo|systemd|darwin|amazon

forever.js: https://github.com/foreverjs/forever

永远.js: https://github.com/foreverjs/forever

# basic usage
$ npm install forever -g
$ forever start app.js

# you can run from a json configuration as well, for
# more complex environments or multi-apps
$ forever start development.json

Init scripts:

初始化脚本

I'm not go into detail about how to write a init script, because I'm not an expert in this subject and it'd be too long for this answer, but basically they are simple shell scripts, triggered by OS events. You can read more about this here

我不会详细介绍如何编写 init 脚本,因为我不是这个主题的专家,这个答案太长了,但基本上它们是简单的 shell 脚本,由操作系统事件触发。您可以在此处阅读有关此内容的更多信息

Docker:

码头工人

Just run your server in a Docker container with -doption and, voilá, you have a daemonized node.js server!

只需在带有-d选项的 Docker 容器中运行您的服务器,,您就有了一个守护进程的 node.js 服务器!

Here is a sample Dockerfile (from node.js official guide):

这是一个示例 Dockerfile(来自 node.js官方指南):

FROM node:argon

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

Then build your image and run your container:

然后构建你的镜像并运行你的容器:

$ docker build -t <your username>/node-web-app .
$ docker run -p 49160:8080 -d <your username>/node-web-app

Hope this helps somebody landing on this page. Always use the proper tool for the job. It'll save you a lot of headaches and over hours!

希望这有助于有人登陆此页面。始终使用适合工作的工具。它会为您节省很多头痛和数小时的时间!