Making Node.js service always alive on Ubuntu Server

Tigran Bayburtsyan
HackerNoon.com
4 min readMar 15, 2017

--

Forever Module is good, but you don’t need another software to control background processes on your server!

One of the challenges in production is how to

  1. run Node.js services in background
  2. automatically restart them if they are crashing
  3. collect output/error logs for analyzing them later or watching them in a real time.

All of them are similar to every long running application on server side, so the Linux community have that kind of tools natively integrated into almost every linux distribution. One of the latest tools for handling and processing long running background tasks/services is called SystemD , which is developed by Linux Foundation and now it became standard for Linux distributions. We will be focusing only on Ubuntu Server because it’s really easy to get started with it.

What is actually a SystemD ?

SystemD is an init system used in Linux distributions to bootstrap the user space and manage all processes subsequently — from Wikipedia

This means that SystemD is actually developed to manage and execute User Space processes/services. You can schedule a job, start/stop/restart it and collect it using system logs.

Base command to get started with it is systemctl which have all sub commands to manage existing services or to add exiting ones.

Stop Talking! Let’s setup a project!

To make this experiment more realistic, making very basic node.js hello world http listener.

Take a look on the first line of our server.js file, using that line we are just letting know that using current user environment we will run this file with node executable.

Saving that file to ~/hello_world/server.js and making it as an executable

It’s time to make SystemD Service

Making file /etc/systemd/system/hello_world.service , this would be the main file as a configuration to SystemD service

After saving this file, we can enable this service, to start using it over SystemD

That’s it! Now you have Node.js service as a background service, it will be restarted when something goes wrong and you can view all output logs using very simple command

Conclusion

After all this setup kind of things now you got very easy way to manage your service

So you actually don’t need modules like forever for managing Node.js background services, it all could be done using Linux native tools, which are more performant and more reliable! (hope so).

So if you learned something from this, just Recommend This for letting to learn others too.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

--

--