Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Linux on the Pi

Running Programs at Boot with systemd Services

Turn a Python script into a systemd service on the Pi: write a unit file, enable it at boot, restart on failure, read logs with journalctl, and avoid rc.local.

A Pi project is only useful if it starts by itself. When you power the board in a greenhouse, the weather logger must come up with no keyboard attached. On Raspberry Pi OS the right tool is systemd, the program that starts everything after the kernel. You describe your program in a small text file called a unit, and systemd starts it at boot, restarts it if it crashes, and collects its output in the log.

Systemd cannot run on this website, so unit files and commands are read-only, and the runnable blocks model how a supervisor restarts a failing program.

Why not rc.local or a terminal tab?

Old tutorials suggest /etc/rc.local, .bashrc lines or a screen session. They have no restart on failure, no logs, no ordering ("start after the network is up") and they run as whatever user happens to log in. A service fixes all four.

A first unit file

Imagine /home/ana/weather/logger.py reads a sensor every minute. Create /etc/systemd/system/weather.service:

INI
[Unit]
Description=Weather logger
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=ana
WorkingDirectory=/home/ana/weather
ExecStart=/usr/bin/python3 /home/ana/weather/logger.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

The three sections have clear jobs:

  • [Unit] describes the service and its ordering. After= says "start me later than that", Wants= asks for it to be started too.
  • [Service] says how to run it: which user, which folder, which command. Use absolute paths in ExecStart, because there is no shell and no PATH lookup of your home directory.
  • [Install] says what enabling means: WantedBy=multi-user.target is "start in normal multi-user boot".

Then tell systemd about the file and start it:

Terminal
sudo systemctl daemon-reload          # re-read unit files
sudo systemctl enable --now weather   # start now AND at every boot
systemctl status weather              # state, PID, last log lines
sudo systemctl restart weather
sudo systemctl stop weather
sudo systemctl disable weather        # stop starting at boot

enable creates a symlink so the service starts at boot; start runs it right now. enable --now does both. After you edit the unit file, run daemon-reload again.

Restart policies

Restart=on-failure restarts the program when it exits with a non-zero code or is killed by a signal, but not after a clean exit 0. Restart=always restarts it even on a clean exit, which suits a daemon that should never stop. RestartSec=5 waits five seconds so a crash loop does not hog the CPU. To stop an endless loop of fast failures, systemd also has start limits: by default, a service that restarts too often in a short window is marked failed.

This model shows the behavior: a program that fails twice and then works, supervised with on-failure.

Python Stand-in: a supervisor restarting a program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Change the policy to "always" to see what happens when a program keeps being restarted even after a clean exit.

Reading logs with journalctl

Everything your program prints to standard output and standard error lands in the journal, with timestamps and the service name. That means you can debug with plain print:

Terminal
journalctl -u weather               # all logs for the service
journalctl -u weather -f            # follow live, like tail -f
journalctl -u weather --since "1 hour ago"
journalctl -u weather -p err        # only errors
journalctl -b                       # everything since this boot

Python buffers stdout when it is not a terminal, so lines can appear late. Add Environment=PYTHONUNBUFFERED=1 to the [Service] section, or use print(..., flush=True).

Python Stand-in: filtering a log like journalctl

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dependencies and timing

A common bug is a service that starts before Wi-Fi is connected, fails to reach a server and gives up. After=network-online.target fixes the order. Other useful directives: ExecStartPre= (a command to run first), Environment= or EnvironmentFile= (settings and secrets kept out of the script), and TimeoutStopSec= (how long to wait before forcing a stop).

flowchart LR
    A["Kernel"] --> B["systemd (PID 1)"]
    B --> C["network-online.target"]
    C --> D["weather.service"]
    D -->|"crash"| E["Restart after RestartSec"]
    E --> D

systemd starts services in dependency order and restarts them on failure.

Common mistakes

  • Relative paths in ExecStart or in the script (the working directory is not your home). Set WorkingDirectory= and use absolute paths.
  • Forgetting daemon-reload after editing the file.
  • Running as root when the gpio group is enough; use User=.
  • A script that ends immediately (like one that only starts a thread); the service looks "inactive". Keep the main program running.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does systemctl enable do?

    enable creates the boot-time link; use --now to start it immediately too.
  2. 2. Which Restart value restarts only after crashes or failures?

    on-failure restarts on non-zero exit or signals, not after a clean exit.
  3. 3. How do you follow a service's live output?

    journalctl -u NAME -f follows the journal for that unit.
  4. 4. After editing /etc/systemd/system/weather.service you must run:

    systemd caches unit files; daemon-reload makes it read the change.

Summary

  • systemd starts, supervises and logs your program; write a unit file in /etc/systemd/system.
  • [Unit] orders it, [Service] runs it (absolute paths, User=, Restart=), [Install] hooks it to boot.
  • Use enable --now, status, restart, and daemon-reload after edits.
  • stdout and stderr go to the journal; read them with journalctl -u NAME.
  • Order after network-online.target for anything that needs the network.

Next: Temperature, Throttling and Performance