Raspberry Pi 3 Node Server & systemd (part 5)

Run a simple Node server. Create the file and path,

/opt/nodeserver/server.js

const http = require('http');
const hostname = '0.0.0.0'; // listen on all ports
const port = 8080;
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello people, I am a server \n' + new Date().toISOString());
}).listen(port, hostname, () => {
console.log('Server running at http://' + hostname + ':' + port);
});

Run this,

$ node server.js

But this will stop running if you ctrl-c. Therefore we will use Systemd to create a service which will run this server continuously and also start it again in the case of any interruption.

Change directory to

$ cd /etc/systemd/system

Create the file nodeserver.service

$ sudo nano nodeserver.service

and add the following [Unit], [Service] and [Install] as follows,

[Unit]
Description=Node.js Example Server
#Requires=After=mysql.service # Requires the mysql service to run first

[Service]

ExecStart=/usr/bin/node /opt/nodeserver/server.js
Restart=always
RestartSec=10 # Restart service after 10 seconds if node service crashes
StandardOutput=syslog # Output to syslog
StandardError=syslog # Output to syslog
SyslogIdentifier=nodejs-example
User=pi
Group=root
Environment=NODE_ENV=production PORT=8080

[Install]
WantedBy=multi-user.target

You may need to change to ‘User’ and ‘Group’. Make sure the PORT=8080 is the same port as in server.js

Next we need to ‘enable’ and ‘start’ the service

$ sudo systemctl enable nodeserver.service
$ sudo systemctl start nodeserver.service

You can also use ‘restart’, ‘stop’ and ‘status’ to check that the service is running.

$ sudo systemctl restart nodeserver.service
$ sudo systemctl stop nodeserver.service
$ sudo systemctl status nodeserver.service

You will need to reload the daemon with

$ sudo systemctl daemon-reload

After ‘reload’ you will need ‘restart’ the service.

$ sudo systemctl restart nodeserver.service

Most of the information here is from the excellent tutorial at nodejs service with systemd
Another good source,
Deploying nodejs applications with systemd

You can check this in your browser with,

curl http://0.0.0.0:8080

If you’ve set up port-forwarding and noip.com you’ll be able to go to any browser on the internet and see the output.