#nodejs ghost init.d service with forever.js

Oscar Brito

This post is a continuation of the last post where the migration from Blogger to Ghost was described.

After getting the ghost files on the hosting Linux machine you can run ghost by typing:


node index.js

This will run node on the port 2368.

The next step is to install ghost as a 'service' so that it can be be automatically started on boot time. To achieve this Forever.js is also used to keep ghost running continuously (sudo npm install forever -g).

Create /etc/init.d/blog with the content bellow.


#!/bin/sh

## BEGIN INIT INFO
# Provides:          blog
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO

USER="node"
APP="/var/www/blog/blog.divhide.com-0.0.2/package/Ghost-0.4.2/index.js"
LOG="/var/log/blog/ghost.log"

stop() {
        sudo su - $USER -c"NODE_ENV=production forever stop $APP"
}

start() {
        sudo su - $USER -c"NODE_ENV=production forever start --append -l $LOG -o $LOG -e $LOG $APP"
}

case "$1" in
  start)
    stop
    start
    ;;
  stop)
    stop
    ;;
  retart)
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
esac


This will run the ghost blog with the node user. On the top of the file you can find some configuration variables like logs directories, ...

Last step is to enable the script ( see below ).


sudo chmod +x /etc/init.d/blog
sudo update-rc.d blog defaults
sudo update-rc.d blog enable

If you're using Nginx as a reverse proxy you can add the following site configuration.


server {
    listen 0.0.0.0:80;
    server_name blog.divhide.com;
    access_log /var/log/blog/access.log;
    client_max_body_size 2M;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:2368;
        proxy_redirect off;
    }
}

Now if your server goes down the blog will start automatically along with nginx.