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


原来的帖子:

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

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

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


高级解决方案:

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


当前回答

如果您只是想不间断地运行脚本,直到它完成,您可以使用nohup,就像这里的答案中提到的那样。但是,没有一个答案提供一个完整的命令来记录stdin和stdout。

nohup node index.js >> app.log 2>&1 &

>>表示追加到app.log。 2>&1确保错误也被发送到标准输出并添加到app.log中。 结束&确保您当前的终端与命令断开连接,以便您可以继续工作。

如果你想运行一个节点服务器(或者在服务器重新启动时重新启动),你应该使用systemd / systemctl。

其他回答

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

如果出于本地开发的目的,你需要启动多个NodeJS应用实例(express, fastify等),那么并发可能是一个选项。下面是一个设置:

先决条件

你的NodeJS应用(express, fastify等)被放置在/opt/mca/www/mca-backend/app路径下。 假设您使用的是通过brew install node@16安装的节点v.16

设置

Install concurrently: npm install -g concurrently Create a file ~/Library/LaunchAgents/mca.backend.plist <?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>mca.backend</string> <key>LimitLoadToSessionType</key> <array> <string>Aqua</string> <string>Background</string> <string>LoginWindow</string> <string>StandardIO</string> <string>System</string> </array> <key>ProgramArguments</key> <array> <string>/usr/local/bin/concurrently</string> <string>--names</string> <string>dev,prd</string> <string>--success</string> <string>all</string> <string>--kill-others</string> <string>--no-color</string> <string>MCA_APP_STAGE=dev node ./server.mjs</string> <string>MCA_APP_STAGE=prod node ./server.mjs</string> </array> <key>RunAtLoad</key> <true/> <key>EnvironmentVariables</key> <dict> <key>PATH</key> <string>/usr/local/opt/node@16/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin</string> </dict> <key>WorkingDirectory</key> <string>/opt/mca/www/mca-backend/app</string> <key>StandardErrorPath</key> <string>/opt/mca/www/mca-backend/err.log</string> <key>StandardOutPath</key> <string>/opt/mca/www/mca-backend/out.log</string> </dict> </plist> Load and run: launchctl bootstrap gui/`id -u` $HOME/Library/LaunchAgents/mca.backend.plist Get a status: launchctl print gui/`id -u`/mca.backend Stop: launchctl kill SIGTERM gui/`id -u`/mca.backend Start/Restart: launchctl kickstart -k -p gui/`id -u`/mca.backend Unload if not needed anymore: launchctl bootout gui/`id -u`/mca.backend

重要提示:一旦你用launchctl加载service,引导你在文件中所做的任何更改 ~ /图书馆/ LaunchAgents / mca.backend。Plist将不会在行动,直到你卸载服务(通过使用launchctl bootout) 然后再次加载它(通过使用launchctl bootstrap)。

故障排除

查看启动日志:/private/var/log/com.apple.xpc.launchd/launchd.log

如果您正在运行OSX,那么生成真正的系统进程的最简单方法是使用launchd来启动它。

像这样构建一个plist,并以top-level-domain.your-domain.application的名称将它放到/Library/LaunchDaemons中。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>

完成后,发出这个(作为根):

launchctl load /Library/LaunchDaemons/top-level-domain.your-domain.application.plist
launchctl start top-level-domain.your-domain.application

你在跑步。

重新启动后,您仍将运行。

关于plist中的其他选项,请查看这里的手册页:https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html

复制我自己的答案从我如何运行一个Node.js应用程序作为它自己的进程?

2015年的答案:几乎每个Linux发行版都带有systemd,这意味着forever、monit、PM2等不再需要——你的操作系统已经处理这些任务了。

制作一个myapp。服务文件(替换'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

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

将服务文件复制到/etc/systemd/system. conf文件中。

用systemctl Start myapp启动它。

使用systemctl Enable myapp启用它在引导时运行。

使用journalctl -u myapp查看日志

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

如果你在linux服务器上运行nodejs,我认为这是最好的方法。

创建业务脚本,拷贝到/etc/init/nodejs.conf目录下

Start service: sudo service nodejs Start

Stop service: sudo service nodejs Stop

服务脚本

description "DManager node.js server - Last Update: 2012-08-06"
author      "Pedro Muniz - pedro.muniz@geeklab.com.br"

env USER="nodejs" #you have to create this user 
env APPNAME="nodejs" #you can change the service name
env WORKDIR="/home/<project-home-dir>" #set your project home folder here
env COMMAND="/usr/bin/node <server name>" #app.js ?

# used to be: start on startup
# until we found some mounts weren't ready yet while booting:
start on started mountall
stop on shutdown

# Automatically Respawn:
respawn
respawn limit 99 5

pre-start script
    sudo -u $USER echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Starting" >> /var/log/$APPNAME.log
end script

script
    # Not sure why $HOME is needed, but we found that it is:
    export HOME="<project-home-dir>"  #set your project home folder here
    export NODE_PATH="<project node_path>"

    #log file, grant permission to nodejs user
    exec start-stop-daemon --start --make-pidfile --pidfile /var/run/$APPNAME.pid --chuid $USER --chdir $WORKDIR --exec $COMMAND >> /var/log/$APPNAME.log 2>&1
end script

post-start script
   # Optionally put a script here that will notifiy you node has (re)started
   # /root/bin/hoptoad.sh "node.js has started!"
end script

pre-stop script
    sudo -u $USER echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Stopping" >> /var/log/$APPNAME.log
end script