forever 是 Node.js 社群常用的 CLI 工具,提供進程守護、日誌管理、自動重啟、開機自啟腳本產生等功能,適合中小型專案;大型生產環境建議改用 PM2、systemd 或容器編排。
npm install -g forever
forever start test.js
forever list
forever stop test.js
/etc/init.d/node-app#!/bin/bash
### BEGIN INIT INFO
# Provides: node-app
# Required-Start: $network $remote_fs $syslog
# Required-Stop: $network $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Node.js app via forever
# Description: Start/stop Node.js application using forever
### END INIT INFO
# chkconfig: 345 88 12
# description: Forever daemon for Node.js
APP_DIR="/opt/nodejs/myapp"
ENTRY_POINT="bin/www" # 專案啟動檔(相對 APP_DIR)
LOG_DIR="/var/log/nodejs"
PID_DIR="/var/run/nodejs"
NODE_BIN="/usr/local/bin/node"
FOREVER_BIN="/usr/local/bin/forever"
export PATH=$PATH:/usr/local/bin
export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules
# 建立必要目錄
mkdir -p "$LOG_DIR" "$PID_DIR"
chown -R nodeuser:nodeuser "$LOG_DIR" "$PID_DIR" "$APP_DIR"
case "$1" in
start)
su -s /bin/bash -c "$FOREVER_BIN start -l $LOG_DIR/app.log --pidFile $PID_DIR/app.pid -a $APP_DIR/$ENTRY_POINT" nodeuser
;;
stop)
su -s /bin/bash -c "$FOREVER_BIN stop --pidFile $PID_DIR/app.pid $APP_DIR/$ENTRY_POINT" nodeuser
;;
restart)
su -s /bin/bash -c "$FOREVER_BIN restart -l $LOG_DIR/app.log --pidFile $PID_DIR/app.pid -a $APP_DIR/$ENTRY_POINT" nodeuser
;;
status|list)
su -s /bin/bash -c "$FOREVER_BIN list" nodeuser
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit 0
chmod +x /etc/init.d/node-app
chkconfig --add node-app
chkconfig --level 35 node-app on
# CentOS 7+ / Ubuntu 16.04+ 建議改用 systemd 服務單元(見下文)
/etc/systemd/system/node-app.service[Unit]
Description=Node.js Application
After=network.target
[Service]
Type=simple
User=nodeuser
WorkingDirectory=/opt/nodejs/myapp
Environment=NODE_ENV=production
ExecStart=/usr/local/bin/forever start -l /var/log/nodejs/app.log --pidFile /var/run/nodejs/app.pid -a bin/www
ExecStop=/usr/local/bin/forever stop --pidFile /var/run/nodejs/app.pid bin/www
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable --now node-app
systemctl status node-app
750,擁有者為執行用戶,避免權限問題。systemd,/etc/init.d 腳本仍可運作但會有 LSB 警告;優先用 systemd。forever 內建 forever-service 可自動產生 init.d/systemd 腳本:npm install -g forever-service && forever-service install node-app -s bin/www。