Thursday, November 6, 2014

NODEJS - RUNNING A NODEJS SERVER AS A SERVICE ON LINUX


1. Download the project for testing:


The user logged in was: root

Download the demo server here

[root@homepc opt]# wget https://github.com/vanduc1102/nodejs-example/archive/daemon-bauth.tar.gz

[root@homepc opt]# tar -zxvf daemon-bauth.tar.gz

[root@homepc opt]# cd nodejs-example-daemon-bauth/

[root@homepc nodejs-example-daemon-bauth]# npm install

[root@hompec nodejs-example-daemon-bauth]# node index.js


You can open browser and test the application at localhost:3000

We had nodejs-example folder placed in /opt/nodejs-example-daemon-bauth

2. Create a service file in systemd:


Create file below in folder : /etc/systemd/system/
nodejs-example-service.service

[Unit]
Description=The nodejs-example server start

[Service]
WorkingDirectory=/opt/nodejs-example-daemon-bauth
ExecStart=/usr/bin/node index.js
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-example-nodejs-server
User=root
Group=root

[Install]
WantedBy=multi-user.target

Load the service at first time:
#systemctl enable nodejs-example-service

Start service:
#systemctl start nodejs-example-service

View status of the service:
#systemctl status nodejs-example-service

Stop the service:
#systemctl stop nodejs-example-service

3. Testing the service:


[root@homepc system]# systemctl start  nodejs-example-service.service
[root@homepc system]# systemctl status nodejs-example-service.service
nodejs-example-service.service - The nodejs-example server start
Loaded: loaded (/etc/systemd/system/nodejs-example-service.service; enabled)
Active: active (running) since jeu 2014-11-06 19:18:02 ICT; 8s ago
Main PID: 3967 (node)
CGroup: name=systemd:/system/nodejs-example-service.service
└─3967 /usr/bin/node index.js
[root@homepc system]# ps -e | grep "node"
3967 ? 00:00:00 node
[root@homepc system]# kill 3967
[root@homepc system]# ps -e | grep "node"
4038 ? 00:00:00 node
[root@homepc system]# systemctl status nodejs-example-service.service
nodejs-example-service.service - The nodejs-example server start
Loaded: loaded (/etc/systemd/system/nodejs-example-service.service; enabled)
Active: active (running) since jeu 2014-11-06 19:18:02 ICT; 8s ago
Main PID: 4038 (node)
CGroup: name=systemd:/system/nodejs-example-service.service
└─4038 /usr/bin/node index.js
[root@homepc system]#

As you can see, After we kill the process, It will automatically create new one.

No comments:

Post a Comment