I always find myself googling the same things multiple times. Therefore it's good to have a place to store these things and maybe it's also useful for someone else googling it again.
For my Pi Project I want to run a node.js application always in the background. I found the perfect solution in the
systemd service which is part of every *nix system. There is also a command line tool called
systemctl which makes it kinda easy to control the daemon.
Create a .target file
First step is to create a target file in
/etc/systemd/system which contains the path to the executable and some other information. I called mine
[Unit] Description=piway After=network.target [Service] ExecStart=/usr/bin/node index.js WorkingDirectory=/home/pi/apps/pi-way/ StandardOutput=inherit StandardError=inherit Restart=always User=pi [Install] WantedBy=multi-user.target
Use systemctl to control the service
The next step is to start the service with
sudo systemctl start pi-way (replace pi-way with the name of your .target file)
The start command will run your service for the current session. If you want the service to survive a reboot, then you have to enable it by executing
sudo systemctl enable pi-way.