node.jsをAmazonLinuxでサービス化する

yum -y install nodejs npm --enablerepo=epel

mkdir -p /opt/nodejs/welcome
cd /opt/nodejs/welcome

vi package.json
{
  "name": "welcome",
  "description": "welcome page",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.x",
    "ejs": "*"
  }
}
npm install

vi server.js
var express = require('express');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');

app.get('/', function(req, res){
  res.render('index', {title: "Welcome"});
});

var server = app.listen(8080, function() {
    console.log('Listening on port %d', server.address().port);
});
mkdir views
vi views/index.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title><%= title %></title>
<style type=”text/css”> body { padding: 50px; font: 13px Helvetica, Arial, sans-serif; } </style>
</head>
<body>
    <p>Welcome to node.js</p>
    <p>Please edit following setting file to create your application service.</p>
</body>
</html>
mkdir /etc/nodejs
vi /etc/nodejs/daemon
ROOT_DIR="/opt/nodejs/welcome"
SERVER="$ROOT_DIR/server.js"
vi /etc/init.d/nodejs
#!/bin/sh

#
# chkconfig: 35 99 99
# description: Node.js
# processname: node
# config: /etc/nodejs/daemon
# pidfile: /var/run/nodejs.pid

. /etc/rc.d/init.d/functions

USER="root"
PROCESS="/usr/bin/node"

if [ -f /etc/nodejs/daemon ]; then
  source /etc/nodejs/daemon
fi

if [ "${ROOT_DIR}" = "" ]; then
  echo "please specify ROOT_DIR in /etc/nodejs/daemon"
  exit 1
fi

if [ "${SERVER}" = "" ]; then
  SERVER="$ROOT_DIR/app.js"
fi

if [ "${LOG_FILE}" = "" ]; then
  LOG_FILE="$ROOT_DIR/app.js.log"
fi

prog="nodejs"
lockfile="/var/lock/subsys/${prog}"
pidfile="/var/run/${prog}.pid"

do_start() {
    [ -x $PROCESS ] || exit 5
    echo -n $"Starting $SERVER: "
    runuser -l "$USER" -c "$PROCESS $SERVER >> $LOG_FILE &" && echo_success || echo_failure
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    ps -aefw | grep "$PROCESS $SERVER" | grep -v " grep " | awk '{print $2}' > $pidfile
    return $retval
}

do_stop() {
    echo -n $"Stopping $SERVER: "
    killproc -p $pidfile $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

case "$1" in
        start)
                do_start
                ;;
        stop)
                do_stop
                ;;
        restart)
                do_stop
                do_start
                ;;
        status)
                status ${prog}
                ;;

        *)
                echo "Usage: $0 {start|stop|restart}"
                RETVAL=1
esac

exit $RETVAL
chmod +x /etc/init.d/nodejs