Nodejs as a service with SYSTEMD

Recently working on MEAN (MONGODB, EXPRESSJS, ANGULAR, NODEJS) Stack environment. I enjoy to wotked on application how its eco friendly with web. After finishing my app I want to run on server mongodb and angular was fine to me but question arise how to run nodejs in background as I am using debian10.

So I start with a system service for a Nodejs application to run as long as system is up. In linux system “Systemd” is a service manager which start, stop restart programs.

Create a file nodejsapp.service with the following content on /usr/lib/systemd/system.


[Unit]

Description=Node.js ContactList Http Server[Service]

User=Alok Sah

Group=Alok Group

Restart=always

KillSignal=SIGQUIT

[Service]

WorkingDirectory=/root/contactlist/

Restart=on-failure

ExecStart=/usr/bin/node  /root/contactlist/app.js

[Install]

WantedBy=multi-user.target

assuming my nodejs file is in /root/contactlist/app.js.

Now using systemctl to control our app with the following commands


//whenever any service file is changes use daemon-reload 

sudo systemctl daemon-reload

// enabling this service at machines start

sudo systemctl enable nodejsapp

sudo systemctl disable nodejsapp

// to start the app.js service

sudo systemctl start nodejsapp

sudo systemctl stop nodejsapp

sudo systemctl restart nodejsapp

//check the status of service active 

sudo systemctl status nodejsapp

Once the Nodejs service is started successfully with no configuration errors, launch the web browser and check your application its running without npm start :).

Leave a Reply

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