Start your node.js applications when your Raspberry Pi boots
/If you’ve got an application (perhaps one that lives inside a red telephone) which you want to run when your machine boots there is a really good way to do this. You turn your application into a service. You can make your application start when the Pi boots and you can also start and stop the application from the command line.
We can use the systemd
to this for us. This orchestrates the startup and management of services. To use it with a Node.js application, we create a systemd service unit file.
Start your editor of choice and create a file named redserver.service
(if you’re controlling a red telephone - otherwise use a more meaningful name) within the /etc/systemd/system/
directory. This file defines a service for systemd to manage.
[Unit]
Description=Red Phone Server/home/rob/RaspberryPi-DialTelephone
After=network.target
[Service]
ExecStart=/usr/bin/node /home/rob/RaspberryPi-DialTelephone/redserver.js
WorkingDirectory=/home/rob/RaspberryPi-DialTelephone
Restart=on-failure
User=rob
[Install]
WantedBy=multi-user.target
Note that the file sets the working directory for the application and specifies the command that starts the service. You can now enable and start your service with the following commands:
sudo systemctl enable redserver
sudo systemctl start redserver
The service will now run each time the Pi boots. You can use systemctl
to stop the service. This is useful if you want to debug the service - things don’t normally go well if you have two copies of the thing running…
sudo systemctl stop redserver
If you want to restart the service you just start it again.
sudo systemctl start myapp
If you ever want to disable the service completely and stop it running when the system boots you can use this:
sudo systemctl disable myapp
I’ve found this very useful. So useful that I’ve made a blog post so that I can find it again later…