最近開始用 nodejs 做一些事情,最後希望變成系統服務來執行,所以紀錄一下作法
 
5d7a90bcbd73c19060b45fb6e37ca20b.png
  • forever
    為了確保程式死掉後會自動重新執行,所以先安裝這套 forever
    用途如其名,就是讓你的程式永遠執行
    npm install forever -g
  • 執行程式
    forever start index.js
  • 撰寫 service script
    接下來,就是要寫一個 linux service 的 script,然後執行 forever 讓你的服務自動啟動,而且萬一掛調會自動跑起來
    把檔案改成你要的服務名稱,並放到 /etc/init.d 即可 
    裡面的參數要自己改喔!~~
     
    #!/bin/sh
    
    ### BEGIN INIT INFO
    # Provides:          
    # Required-Start:    my-service
    # Required-Stop:     my-service
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: My Linux Service
    ### END INIT INFO
    
    set -e
    
    SERVICE_NAME=`basename $0`
    PIDFILE=/var/run/myserv.pid
    LOGPATH="/var/log/${SERVICE_NAME}"
    FOREVER_BIN=`which forever`
    APP_PATH="/var/share/work-js/app.js"
    
    case $1 in
    	start)
    		if [ -e "${PIDFILE}" ]; then
    			PID=`cat ${PIDFILE}`
    			echo "Service is running already. (PID=${PID})"
    			exit 1
    		fi
    		if [ ! -d "${LOGPATH}" ]; then
    			mkdir -p "${LOGPATH}"
    		fi
    		PID=`ps aux | grep ${APP_PATH} | head -n1 | awk '{print $2}'`
    		${FOREVER_BIN} start ${APP_PATH} -l "${LOGPATH}/service.log" -o "${LOGPATH}/out.log" -e "${LOGPATH}/error.log" > "${LOGPATH}/start.log"
    		rm -rf ${PIDFILE}
    		echo "${PID}" > ${PIDFILE}
    		echo "Service ${SERVICE_NAME} start. PID=${PID}"
    		;;
    	stop)
    		if [ ! -e "${PIDFILE}" ]; then
    			echo "Service is not running."
    		else
    			PID=`cat ${PIDFILE}`
    			kill ${PID} || true
    			rm -rf ${PIDFILE}
    			echo "Service ${SERVICE_NAME} stop. PID=${PID}"
    		fi
    		;;
    	restart)
    		$0 stop
    		sleep 1
    		$0 start
    		;;
    	status)
    		if [ -e "${PIDFILE}" ]; then
    			PID=`cat ${PIDFILE}`
    			echo "Service is running. (PID=${PID})"
    		else
    				echo "Service is not running."
    		fi
    		;;
    	*)
    		echo "Usage: ${0} {start|stop|restart|status}"
    		exit 1
    		;;
    esac
  • Log rotate
    因為 log 太多會爆炸,所以最好加入 logrotate。
    vi /etc/logrotate.d/forever
    並放入以下內容
    /root/.forever/*.log {
        daily
        create 0644 root root
        rotate 12
        delaycompress
        missingok
        notifempty
        sharedscripts
        delaycompress
        postrotate
            forever restartall
        endscript
    }
    
    路徑就看你的設定囉~ 
     
    最後可以用 
    cd /etc/logrotate.d
    logrotate --force forever
    強制執行一下!
Facebook 討論區載入中...