Starting a Node.js App automatically on RapsberryPi

When developing Node.js apps, we often want them to start automatically and run in the background when the server (or, in this case RasperryPi) boots.

One of the easiest ways to achive this in Raspbian is using the systemctl service, which effectively allows us to turn our app into a service which runs on startup (and some other things, like stop and start from anywhere on the command line).

An Example Service

Let's say we have a Node App which interacts with Amazon's Alexa services, and we want this app to boot and connect to Alexa whenever the system boots.

Create the Service

First, create a new script which will form the service in the systemd directory: sudo nano /lib/systemd/system/alexa.service.

Configure the Service

Second, configure your service:

[Unit]
Description=Alexa Service
After=multi-user.target

[Service]
Type=idle
ExecStart=/bin/bash -c 'exec /usr/bin/node /home/pi/iot/aws_iot_thing.js >> /home/pi/iot/alexa.log 2>&1' # log console output to alexa.log
WorkingDirectory=/home/pi/iot # working directory picks up on relative paths
#Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

Enable the Service

Third, we want to set permissions and enable the service we've just created:

$ sudo chmod 644 /lib/systemd/system/alexa.service 
$ sudo systemctl daemon-reload
$ sudo systemctl enable alexa.service

Start the Service

Fourth, we want to start the newly created service:

$ sudo systemctl start alexa.service

Check the Status of the Service

Lastly, we want to check the status of the service using the command:

$ sudo systemctl status alexa.service

And that should be it! If you have any issues, remember there sholuld be a log file containing the redirected output of console.log if you have any issues with the Node.js app itself.

Extra Commands

There are a few extra commands you can use to control the service once it's up and running:

  • Stopping the Service: sudo systemctl stop yourservice.service
  • Starting the Service: sudo systemctl start yourservice.service
  • Restart the Service: sudo systemctl restart yourservice.service
  • Status of the Service: sudo systemctl status yourservice.service

If you want to make changes to the systemctl service file, remember to run systemctl daemon-reload to make sure the latest version is used when you restart your service after the changes.

Wrapping Up

We've seen an example of how to start long-running background Node.js processes on Raspberry Pi's Raspbian Operating System.

In the coming week's I'll dive into more detail on how to start hooking your Raspberry Pi into Alexa's Smart Home ecosystem, and how to integrate with the AWS IoT services.

Show Comments