如何让 Node.js 作为后台进程运行并且永不死掉?

发布于 2024-10-13 18:54:18 字数 477 浏览 8 评论 0原文

我通过 putty SSH 连接到 linux 服务器。我尝试将其作为后台进程运行,如下所示:

$ node server.js &

但是,2.5 小时后,终端变为非活动状态,进程终止。即使终端断开连接,我是否也可以使进程保持活动状态?


编辑1

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

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


编辑2(2012年2月)

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

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

$ 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?


Edit 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.

Is there anything I have to do in Putty?


Edit 2 (on Feb, 2012)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

蔚蓝源自深海 2024-10-20 18:54:18

nohup 节点 server.js > /dev/null 2>&1 &

  1. nohup 表示:即使 stty 被切断,也不要终止此进程
    关闭。
  2. > /dev/null 表示:stdout 转到 /dev/null (这是一个虚拟的
    不记录任何输出的设备)。
  3. 2>&1 表示:stderr 也会转到 stdout(已重定向到 /dev/null< /代码>)。您可以将 &1 替换为文件路径以保留错误日志,例如: 2>/tmp/myLog
  4. 末尾的 & 表示: 将此命令作为后台任务运行。

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

  1. nohup means: Do not terminate this process even when the stty is cut
    off.
  2. > /dev/null means: stdout goes to /dev/null (which is a dummy
    device that does not record any output).
  3. 2>&1 means: 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.
不交电费瞎发啥光 2024-10-20 18:54:18

简单的解决方案(如果您不想返回该流程,只是希望它继续运行):

nohup node server.js &

还有 jobs 命令来查看后台的索引列表流程。您可以通过运行 kill %1kill %2 来终止后台进程,其中数字是进程的索引。

强大的解决方案(允许您重新连接到交互式进程):

screen

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

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

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 jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

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

Also consider the newer alternative to screen, tmux.

蓝天白云 2024-10-20 18:54:18

这是一个老问题,但在谷歌上排名很高。我几乎不敢相信得票最高的答案,因为在屏幕会话中运行 node.js 进程,使用 & 甚至使用 nohup 标志 -所有这些都只是解决方法。

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

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

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

我的一大优势PM2 的优势在于它可以生成系统启动脚本,使进程在重新启动之间持续存在:

$ pm2 startup [platform]

其中 platform 可以是 ubuntu|centos|redhat|gentoo|systemd|darwin|amazon< /代码>。

forever.jshttps://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

初始化脚本

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

Docker

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

这是一个示例 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" ]

然后构建您的映像并运行您的容器:

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

始终使用适合该工作的正确工具。它会帮你省去很多头痛和几个小时的时间!

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 nohup flag -- all of them -- are just workarounds.

Specially the screen/tmux solution, which should really be considered an amateur solution. 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!

There are plenty of good tools to do that.

PM2: http://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 startup [platform]

Where platform can be ubuntu|centos|redhat|gentoo|systemd|darwin|amazon.

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

Docker:

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

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

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

Always use the proper tool for the job. It'll save you a lot of headaches and over hours!

沧桑㈠ 2024-10-20 18:54:18

您确实应该尝试使用screen。这比仅仅执行 nohup long_running & 稍微复杂一些,但是一旦你再也不会回来就了解屏幕。

首先启动屏幕会话:

user@host:~$ screen

运行您想要的任何内容:

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

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

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

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.

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.

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

厌味 2024-10-20 18:54:18

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

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

another solution disown the job

$ nohup node server.js &
[1] 1711
$ disown -h %1
尴尬癌患者 2024-10-20 18:54:18

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

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

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

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

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

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

晌融 2024-10-20 18:54:18

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

npm install pm2 -g

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

pm2 start app.js

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

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:

npm install pm2 -g

to run a Node.js app as a daemon:

pm2 start app.js

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

污味仙女 2024-10-20 18:54:18
$ disown node server.js &

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

$ disown node server.js &

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

伪装你 2024-10-20 18:54:18

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

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

你可以这样使用它:

nohup-template "command you would execute here"

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

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

You can use it this way:

nohup-template "command you would execute here"
戏剧牡丹亭 2024-10-20 18:54:18

您是否了解过 nohup 命令?

Have you read about the nohup command?

强辩 2024-10-20 18:54:18

要使用 sysv init 在 debian 上将命令作为系统服务运行:

复制骨架脚本并根据您的需要进行调整,可能您所要做的就是设置一些变量。您的脚本将从 /lib/init/init-d-script 继承默认值,如果某些内容不符合您的需求 - 在您的脚本中覆盖它。如果出现问题,您可以在源代码 /lib/init/init-d-script 中查看详细信息。强制变量是 DAEMONNAME。脚本将使用 start-stop-daemon 来运行您的命令,在 START_ARGS 中您可以定义要使用的 start-stop-daemon 的附加参数。

cp /etc/init.d/skeleton /etc/init.d/myservice
chmod +x /etc/init.d/myservice
nano /etc/init.d/myservice

/etc/init.d/myservice start
/etc/init.d/myservice stop

这就是我为我的 wikimedia wiki 运行一些 python 东西的方式:

...
DESC="mediawiki articles converter"
DAEMON='/home/mss/pp/bin/nslave'
DAEMON_ARGS='--cachedir /home/mss/cache/'
NAME='nslave'
PIDFILE='/var/run/nslave.pid'
START_ARGS='--background --make-pidfile --remove-pidfile --chuid mss --chdir /home/mss/pp/bin'

export PATH="/home/mss/pp/bin:$PATH"

do_stop_cmd() {
    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
        $STOP_ARGS \
        ${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    rm -f $PIDFILE
    return $RETVAL
}

除了设置变量之外,我还必须覆盖 do_stop_cmd 因为 python 替换了可执行文件,所以服务没有正确停止。

To run command as a system service on debian with sysv init:

Copy skeleton script and adapt it for your needs, probably all you have to do is to set some variables. Your script will inherit fine defaults from /lib/init/init-d-script, if something does not fits your needs - override it in your script. If something goes wrong you can see details in source /lib/init/init-d-script. Mandatory vars are DAEMON and NAME. Script will use start-stop-daemon to run your command, in START_ARGS you can define additional parameters of start-stop-daemon to use.

cp /etc/init.d/skeleton /etc/init.d/myservice
chmod +x /etc/init.d/myservice
nano /etc/init.d/myservice

/etc/init.d/myservice start
/etc/init.d/myservice stop

That is how I run some python stuff for my wikimedia wiki:

...
DESC="mediawiki articles converter"
DAEMON='/home/mss/pp/bin/nslave'
DAEMON_ARGS='--cachedir /home/mss/cache/'
NAME='nslave'
PIDFILE='/var/run/nslave.pid'
START_ARGS='--background --make-pidfile --remove-pidfile --chuid mss --chdir /home/mss/pp/bin'

export PATH="/home/mss/pp/bin:$PATH"

do_stop_cmd() {
    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
        $STOP_ARGS \
        ${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    rm -f $PIDFILE
    return $RETVAL
}

Besides setting vars I had to override do_stop_cmd because of python substitutes the executable, so service did not stop properly.

空城缀染半城烟沙 2024-10-20 18:54:18

除了上面很酷的解决方案之外,我还提到了 Supervisord 和 monit 工具,它们允许启动进程、监视其存在并在进程死机时启动它。使用“monit”,您还可以运行一些主动检查,例如检查进程是否响应 http 请求

Apart from cool solutions above I'd mention also about supervisord and monit tools which allow to start process, monitor its presence and start it if it died. With 'monit' you can also run some active checks like check if process responds for http request

橘寄 2024-10-20 18:54:18

对于 Ubuntu,我使用这个:

(exec PROG_SH &> /dev/null &)

问候

For Ubuntu i use this:

(exec PROG_SH &> /dev/null &)

regards

山有枢 2024-10-20 18:54:18

尝试这个简单的解决方案

cmd &出口

Try this for a simple solution

cmd & exit

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文