Setup Systemd for Nodejs Application/Process

Write a sample nodejs app, for example an app that pings a server every 5 seconds and prints the output:


var ping = require ("net-ping");

var session = ping.createSession ();
var target = "8.8.8.8";

var pinger = function(){
session.pingHost(target, function (error, target) {
if (error)
console.log (target + ": " + error.toString ());
else
console.log (target + ": Alive");
setTimeout(pinger,5000);

});
}

setTimeout(pinger,5000);

Output:

[[email protected] node-pinger]# node pinger.js
8.8.8.8: Alive
8.8.8.8: Alive
8.8.8.8: Alive

Create a systemd file in location: /etc/systemd/system/pinger.service

Contents of the file should be:

[Unit]
Description=Node Ping service

[Service]
ExecStart=/root/node-pinger/pinger.js
Restart=always
RestartSec=10 # Restart service after 10 seconds if node service crashes
StandardOutput=syslog # Output to syslog
StandardError=syslog # Output to syslog
SyslogIdentifier=nodejs-example
[Install]
WantedBy=multi-user.target

Enable the service and start it:

[[email protected] node-pinger]# vim /etc/systemd/system/pinger.service
[[email protected] node-pinger]# systemctl enable pinger.service
Created symlink from /etc/systemd/system/multi-user.target.wants/pinger.service to /etc/systemd/system/pinger.service.
[[email protected] node-pinger]# systemctl start pinger
[[email protected] node-pinger]# systemctl status pinger

Leave a Reply

Your email address will not be published. Required fields are marked *