Create a linux service to run Node.js
Nearly every Linux distro comes with systemd, which means forever, monit, PM2, etc are no longer necessary — your OS already handles these tasks.
Let’s go!
We need to create a service file to introduce our service.
$ sudo nano /lib/systemd/system/mygreatestapp.service
Put the following contents in it:
—
[Unit]
Description=mygreatest node.js app to make the world great again!
Documentation=https://www.mygreatestapp.com
After=network.target
[Service]
Type=simple
User=username
ExecStart=/usr/bin/node /home/username/mygreatestapp/mygreatestapp.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
—
Now you have your service file in /lib/systemd/system folder.
Whenever you change a service file, systemd has to know it so that it no longer attempts to reference. You can do this by typing:
$ sudo systemctl daemon-reload
What’s coming after is to launch our app with:
$ sudo systemctl start mygreatestapp
You can use following commands to check service status and stop it
$ sudo systemctl status mygreatestapp sudo systemctl stop mygreatestapp
Following commands can be used to do same
$ service mygreatestapp start
$ service mygreatestapp status
$ service mygreatestapp stop
There is a good trick for some situations (e.g. working directory issues if you use modules like TesseractJs) to use in ExecStart is using bash script.
Open an .sh file to write our script
$ sudo nano /home/username/myrunscript.sh
Than put the script you want to run in it
$ cd /home/username/mygreatestapp; /usr/bin/node mygreatestapp.js
You have to make your script file executable. To do so:
$ sudo chmod +x /home/username/myrunscript.sh
Now you have your executable script and it can be used in ExecStart as seen below
“ExecStart=/bin/bash /home/username/myrunscript.sh”
As mentioned above you have to let systemd know if you change anything in there
sudo systemctl daemon-reload