nodejs 最近比较火,多实例配合nginx的反向代理,速度杠杠的。


最近项目上有用到nodejs,顺便弄了个启动脚本


1、安装 rpmdevtools,它可以方便的生成/etc/init.d/下面的启动脚本

yum install rpmdevtools
cd /etc/init.d/
rpmdev-newinit node
mv node.init node
chmod 755 node


这样的话,会在当前目录生成一个node.init 的示例脚本。

如果你熟悉的话,也可以拷贝/etc/init.d/下的任意一个脚本进行修改


2、安装nodejs

yum install nodejs* npm --enablerepo=epel


3、给启动脚本添加内容,具体启动选项需要定制,大致如下:


#!/bin/sh
#
# node - Server-side JavaScript
#
# chkconfig:   <default runlevel(s)> <start> <stop>
# description: <description, split multiple lines with \
#              a backslash>
# http://fedoraproject.org/wiki/FCNewInit/Initscripts
### BEGIN INIT INFO
# Provides:
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop:
# Short-Description:
# Description:
### END INIT INFO
# Source function library.
. /etc/rc.d/init.d/functions
exec="/usr/bin/node"
prog=$(basename $exec)
js=/tmp/test.js
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
lockfile=/var/lock/subsys/$prog
start() {
    echo -n $"Starting $prog: "
    # if not running, start it up here, usually something like "daemon $exec"
        /bin/su -l nginx -c "$prog $js --port=8081 --dir=/tmp >/dev/null 2>&1"
        /bin/su -l nginx -c "$prog $js --port=8082 --dir=/tmp >/dev/null 2>&1"
        /bin/su -l nginx -c "$prog $js --port=8083 --dir=/tmp >/dev/null 2>&1"
        /bin/su -l nginx -c "$prog $js --port=8084 --dir=/tmp >/dev/null 2>&1"
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    # stop it here, often "killproc $prog"
        killproc $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    stop
    start
}
case "$1" in
    start|stop|restart)
        $1
        ;;
    status)
        status $prog
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart}"
        exit 2
esac


node启动需要几个选项,js文件、端口和上传目录,请根据需要定制,


对比网上的其它脚本,本脚本的特点

1、上文中nodejs以nginx用户身份运行,这个是很有必要的,使用root等于裸奔

2、node 完全在后台运行,不在屏幕上进行任何输入输出

3、支持chkconfig 开机启动