I will start a simple node server, which if you kill, monit is gonna restart it again and you will get an email too if set up correctly.
location /home/xxx/monitoring/nodejs
File: node-server.js
var http = require('http');
var port = 8002;
var fs = require('fs');
var logStream = fs.createWriteStream(port+"_log.txt", {'flags':'a'});
var count = 0;
http.createServer(function(req, res){
var output = (++count) + ' Request received in '+port+' @ ' + new Date()+'\n';
console.log(output);
logStream.write(output);
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.end('From '+port+' @ ' + new Date());
}).listen(port);
console.log('Server running @ ' + port)
FILE: server.sh
#!/bin/bash
process=$1
PID_FILE="/home/xxx/monitoring/nodejs/file.pid"
case $process in
start)
echo "STARTING node js server in port 8002"
nohup /usr/sbin/node /home/xxx/monitoring/nodejs/node-server.js > /home/xxx/monitoring/nodejs/server.log 2>&1 &
echo $! > $PID_FILE
;;
stop)
kill -9 $(cat $PID_FILE)
rm $PID_FILE
;;
*)
echo "INVALID OPTION"
;;
esac
LOCATION: /etc/monit/monitrc (for ubuntu)
set mail-format {
from: monit@TEST
subject: monit alert -- XXX-PROD $EVENT $SERVICE
message: $EVENT Service $SERVICE
Date: $DATE
Action: $ACTION
Host: $HOST
Description: $DESCRIPTION
Your faithful employee,
}
set mailserver smtp.gmail.com port 587 username "[email protected]" password "xxx" using tlsv1
set alert [email protected]
check process nodejs-server with pidfile /home/xxx/monitoring/nodejs/file.pid
start program = "/home/xxx/monitoring/nodejs/server.sh start"
stop program = "/home/xxx/monitoring/nodejs/server.sh stop
"
Once the server runs, hit the browser http://localhost:8002/. It will display some result. Now kill the process by finding its process id either from 'monit status' or from any other means. You will get a mail saying the process does not exists but again after some time, the server will run and you will get a mail saying 'process started again'.
But please remember, if you stop the process from monit command like
monit stop nodejs-server
then it will not get restarted. And you get a mail saying that ur process has been stopped.