Running a nodejs app as a systemd service is pretty simple. But the downside to this approach is that if the app dies straight away (e.g. a config file is malformed), then systemd remains unaware.
An alternative is to switch to using notify:
[Service] Type=notify ExecStart=/var/www/app_name/app.js Restart=always ...
There are various ways to notify systemd that your service is ready; but the simplest is to use systemd-notify, a console wrapper around sd_notify.
this.start = function(port) { var deferred = Q.defer(); server = app.listen(port, '127.0.0.1', function(error) { if (error) { deferred.reject(new Error(error)); } else { logger.info('Listening on port %d', port); exec('systemd-notify --ready'); deferred.resolve(); } }); return deferred.promise; }; };
If the process that calls systemd-notify is not the one in ExecStart (e.g. you are using cluster), you will also need to set NotifyAccess to “all”.
Now when you use systemctl to start your service, it will wait for the notification before deeming the start process complete.
Like always, there’s an npm module for this, so you don’t have to fork.
`require(‘sd-daemon’).notifyReady()`