Assuming that you have already installed Node.js on your system. If you haven't visit https://nodejs.org/en/download/package-manager/
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
After=network.target
means our service will start after the network is up and runningType=simple
specify that how our app launch itself.Simple
means it won't drop user priviligesUser=username
tells that our app will run as the unprivileged user unless you want to run it by rootExecStart=/usr/bin/node /home/username/mygreatestapp/mygreatestapp.js
tells systemd the location of our app and what command it should runRestart=on-failure
clearly says under what condition system restart our service. But if you stop the service it won't restart itself.WantedBy=multi-user.target
specify how our service should be enabled
Whenever you change a service file, systemd has to know it so that it no longer attempts to reference these files and reverts back to using the system copies. . You can do this by typing:
sudo systemctl daemon-reload
sudo systemctl start mygreatestapp
sudo systemctl status mygreatestapp
sudo systemctl stop mygreatestapp
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.
sudo nano /home/username/myrunscript.sh
cd /home/username/mygreatestapp; /usr/bin/node mygreatestapp.js
sudo chmod +x /home/username/myrunscript.sh
ExecStart=/bin/bash /home/username/myrunscript.sh
sudo systemctl daemon-reload