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

就是這樣,節點現在作為一個守望者執行。