centos利用forever把nodejs做成系统服务


1.首先下载forever

https://github.com/foreverjs/forever

安装forever:

npm install forever -g
2.编写启动脚本:
vim /etc/init.d/forever

#!/bin/bash
# chkconfig: 345 88 08
# description: Forever for Node.js

DEAMON=/opt/nodejs/app.js
LOG=/opt/nodejs/logs/forever.log
PID=/root/.forever/pids/forever.pid

export PATH=$PATH:/usr/bin/node/bin
export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules

node=/usr/local/bin/node
forever=/usr/local/bin/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
给脚本执行权限
chmod 755 /etc/init.d/forever
chkconfig --add forever
chkconfig forever on
建立测试文件
vim /opt/nodejs/app.js
var http = require("http");
http.createServer(function(request, response) {
    response.writeHead(200, {
        "Content-Type" : "text/plain" // 输出类型
    });
    response.write("Hello World");// 页面输出
    response.end();
}).listen(8100); // 监听端口号
console.log("nodejs start listen 8102 port!");
启动测试:
service forever start
[[email protected] ~]# service forever start
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info:    Forever processing file: /opt/nodejs/app.js
[[email protected] ~]# netstat -napl |grep node
tcp        0      0 :::8100                     :::*                        LISTEN      16646/node          
unix  2      [ ACC ]     STREAM     LISTENING     136666622 16645/node          /root/.forever/sock/worker.1437989208261WtQ.sock
unix  3      [ ]         STREAM     CONNECTED     136666616 16646/node          
unix  3      [ ]         STREAM     CONNECTED     136666615 16645/node          
unix  3      [ ]         STREAM     CONNECTED     136666614 16646/node          
unix  3      [ ]         STREAM     CONNECTED     136666613 16645/node          
unix  3      [ ]         STREAM     CONNECTED     136666612 16646/node          
unix  3      [ ]         STREAM     CONNECTED     136666611 16645/node          
unix  2      [ ]         STREAM     CONNECTED     136666601 16645/node  
QQ截图20150727173619      
QQ截图20150727173526


Whatever is worth doing is worth doing well.