Node 程式上線之後,總不希望每次伺服器重啟都要手動登入再敲一次 forever start。最省事的做法,是寫一支 SysV init 風格的啟動腳本放進 /etc/init.d,再交給 chkconfig 管理開機行為。下面這份腳本以 forever 作為守護進程工具,可以直接套用。
#!/bin/bash
### BEGIN INIT INFO
# Provides: xiyoulib
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable service provided by daemon.
### END INIT INFO
# chkconfig: 345 88 08
# description: Forever for Node.js
DEAMON=/home/wwwroot/default/im/chat.js #這裡填寫你自己的 Node 專案啟動檔
LOG=/home/wwwroot/default/im/log/log #可選,日誌檔位置
PID=/home/wwwroot/default/im/log/pid #必填,用來記錄 forever 的進程號
export PATH=$PATH:/usr/local/bin #Node 可執行檔所在目錄
export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules #Node 套件庫路徑
#往下的內容就不用修改了
node=node
forever=forever
case "$1" in
start)
$forever start -l $LOG --pidFile $PID -a $DEAMON
;;
stop)
$forever stop --pidFile $PID $DEAMON
;;
stopall)
$forever stopall --pidFile $PID
;;
restartall)
$forever restartall --pidFile $PID
;;
reload|restart)
$forever restart -l $LOG --pidFile $PID -a $DEAMON
;;
list)
$forever list
;;
*)
echo "Usage: /etc.init.d/node {start|stop|restart|reload|stopall|restartall|list}"
exit 1
;;
esac
整份腳本真正需要修改的只有最上面幾行:
至於 ### BEGIN INIT INFO 那段註解,是 Debian/Ubuntu 系統用來宣告服務依賴與執行階層的標準 metadata;# chkconfig: 那行則是 RHEL/CentOS 系列在讀取。兩段都留著,跨發行版都能正常工作。
chmod 755 /etc/init.d/node chkconfig /etc/init.d/node on
第一行給予執行權限,第二行把它掛進開機流程。之後就能像操作其他服務一樣使用:
/etc/init.d/node start /etc/init.d/node restart /etc/init.d/node list
小提醒:若你的系統用的是 systemd(如 CentOS 7 以後、Ubuntu 16.04 以後),更推薦寫成 systemd unit 檔,在依賴管理與自動重啟策略上都比 init.d 更可靠。上述腳本仍然可用,只是屬於相容性方案。