Node.js 作为 systemd dmon

systemd 是大多数 Linux 发行版中事实上的 init 系统。将 Node 配置为使用 systemd 运行后,可以使用 service 命令对其进行管理。

首先,它需要一个配置文件,让我们创建它。对于基于 Debian 的发行版,它将在/etc/systemd/system/node.service

[Unit]
Description=My super nodejs app

[Service]
# set the working directory to have consistent relative paths
WorkingDirectory=/var/www/app

# start the server file (file is relative to WorkingDirectory here)
ExecStart=/usr/bin/node serverCluster.js

# if process crashes, always try to restart
Restart=always

# let 500ms between the crash and the restart
RestartSec=500ms

# send log tot syslog here (it doesn't compete with other log config in the app itself)
StandardOutput=syslog
StandardError=syslog

# nodejs process name in syslog
SyslogIdentifier=nodejs

# user and group starting the app
User=www-data
Group=www-data

# set the environement (dev, prod…)
Environment=NODE_ENV=production

[Install]
# start node at multi user system level (= sysVinit runlevel 3) 
WantedBy=multi-user.target

现在可以分别启动,停止和重启应用程序:

service node start
service node stop
service node restart

要告诉 systemd 在启动时自动启动节点,只需输入:systemctl enable node

就是这样,节点现在作为一个守望者运行。