Introduction
Occasionally, we need to configure an application to autostart after Raspberry Pi or Linux boot up. The application may be the executable application downloaded from internet, or it can be the application compiled from your source code.
There are various ways to accomplish this, I will introduce my three preferred methods here:
1. Script Method
-
Write a script to start the application
Create a new file
autostart.sh
in/home/pi
folder:$ sudo nano /home/pi/autostart.sh
and write the follwing line (point to the application location):
/home/pi/your_application
-
Configure to autostart the script
$ sudo nano /etc/rc.local
add the following lines before
exit 0
:/home/pi/autostart.sh
-
Lastly, make the script exectuable
$ sudo chmod +x /home/pi/autostart.sh
2. Desktop File Method
-
Create autostart folder in
/home/pi/.config
:cd /home/pi/.config mkdir autostart cd autostart
-
Write a desktop file
-
$ sudo nano application_name.desktop
A new window will open, write the following lines:
[Desktop Entry] Name=application_name Exec=lxterminal –e “home/pi/your_application” Type=Application
After typing, press “Ctrl + O” to save and press “Ctrl + X” to quit nano.
Note:
-
[Desktop Entry]
is MUST in the first line. -
Name: Specific name of the application.
-
Type: This specification defines 3 types of desktop entries: Application (type 1), Link (type 2) and Directory (type 3).
-
Exec: Application to execute, possibly with arguments.
-
lxterminal –e “home/pi/your_application”
means you want to use LXTerminal open the application that stored inhome/pi/your_application
, your_application is an executable file.
3. PM2 Method
PM2 is a daemon process manager that will help us manage and keep the application online 24/7. You can autostart multiple types of applications by using PM2.
- Install the Software
$ sudo apt install nodejs
$ sudo apt install npm
$ sudo npm install pm2 -g
- Start the application, we use a Python script as an example here. Other languages and shell script are ok.
$ pm2 start my_program.py --name MyProgram --interpreter python3
- Configure to Autostart
# save current pm2 job
$ pm2 save
# lock dump.pm2 file, very important! You may ignore this in other Linux machines.
$ sudo chattr +i /home/pi/.pm2/dump.pm2
# let pm2 autostart when os reboot (just run "sudo pm2 startup" in other Linux machines.)
$ sudo pm2 startup systemd -u pi --hp /home/pi
# Done. Now you can reboot your machine to check it.
Using any of the above three methods, the application will autostart after Raspberry Pi start up.