How to Auto Start Program on Raspberry Pi Boot Easily
To auto start a program on Raspberry Pi boot, create a
systemd service file or add your command to /etc/rc.local. The systemd method is preferred for modern Raspberry Pi OS versions as it offers better control and reliability.Syntax
There are two common ways to auto start a program on Raspberry Pi boot:
- systemd service: Create a service file in
/etc/systemd/system/with commands to start your program. - rc.local script: Add your program's start command before the
exit 0line in/etc/rc.local.
systemd service files have sections like [Unit], [Service], and [Install] to define how and when the program runs.
ini
[Unit] Description=My Program Service After=network.target [Service] ExecStart=/usr/bin/python3 /home/pi/myprogram.py Restart=always User=pi [Install] WantedBy=multi-user.target
Example
This example shows how to create a systemd service to auto start a Python script named myprogram.py located in the /home/pi/ directory.
After creating the service file, you enable and start it so it runs on boot.
bash
[Unit] Description=My Python Script Service After=network.target [Service] ExecStart=/usr/bin/python3 /home/pi/myprogram.py Restart=always User=pi [Install] WantedBy=multi-user.target # Commands to enable and start the service: sudo systemctl daemon-reload sudo systemctl enable myprogram.service sudo systemctl start myprogram.service
Output
Created symlink /etc/systemd/system/multi-user.target.wants/myprogram.service → /etc/systemd/system/myprogram.service.
Common Pitfalls
- Not setting the correct
Userin the service file can cause permission issues. - Forgetting to run
sudo systemctl daemon-reloadafter creating or editing the service file means changes won't apply. - Using relative paths instead of full paths in
ExecStartcan cause the program not to start. - Adding commands after
exit 0in/etc/rc.localwill not run them.
bash
# Wrong way in /etc/rc.local (won't run):
exit 0
/usr/bin/python3 /home/pi/myprogram.py &
# Right way in /etc/rc.local:
/usr/bin/python3 /home/pi/myprogram.py &
exit 0Quick Reference
| Method | File/Location | Key Command | Notes |
|---|---|---|---|
| systemd service | /etc/systemd/system/myprogram.service | sudo systemctl enable myprogram.service | Preferred, reliable, supports restart |
| rc.local script | /etc/rc.local | Add command before exit 0 | Simple but less flexible |
| cron @reboot | crontab -e | @reboot /usr/bin/python3 /home/pi/myprogram.py | Alternative, runs as user |
Key Takeaways
Use systemd service files for reliable auto start on Raspberry Pi boot.
Always use full paths and set the correct user in service files.
Run 'sudo systemctl daemon-reload' after creating or editing service files.
In /etc/rc.local, place commands before 'exit 0' to ensure they run.
cron @reboot is another option but less commonly used than systemd.