Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Packages and Services

Writing systemd Unit Files, Drop-ins and Timers

Create your own systemd service, override packaged units with drop-ins, add restart policies and sandboxing options, and schedule jobs with timers instead of cron.

Packages bring their own service files, but you will often need to run your own program as a service, or change how an existing one behaves. systemd units are simple text files, and getting them right gives you automatic restarts, clean logging, resource limits and sandboxing without writing a wrapper script.

Anatomy of a service unit

Custom units go in /etc/systemd/system/. Files shipped by packages live in /usr/lib/systemd/system/ and should not be edited.

INI
# /etc/systemd/system/myapp.service
[Unit]
Description=My application
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/myapp --port 8080
Restart=on-failure
RestartSec=5
Environment=APP_ENV=production
EnvironmentFile=-/etc/myapp/env

[Install]
WantedBy=multi-user.target

After creating or changing a unit file:

Terminal
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
systemctl status myapp

Key settings:

  • After= and Wants=/Requires= order and link units. After is only ordering; Wants pulls in a dependency softly, Requires hard.
  • Type=simple (the program stays in the foreground), forking (it daemonizes), oneshot (it does a job and exits), notify (it reports readiness to systemd).
  • ExecStart must use an absolute path. systemd does not run through a shell, so pipes and $VAR expansion do not work as in bash; use /bin/sh -c '...' if you really need it.
  • Restart=on-failure restarts after crashes, not after a clean stop; always restarts regardless.
  • A - before a path in EnvironmentFile=- means the file is optional.
  • [Install] decides what enable does; WantedBy=multi-user.target means start at normal boot.

Drop-in overrides

To change a packaged service without touching its file:

Terminal
sudo systemctl edit nginx

This opens an editor and saves /etc/systemd/system/nginx.service.d/override.conf. Only the lines you write change. To reset a list setting such as ExecStart, first assign an empty value, then the new one:

INI
[Service]
ExecStart=
ExecStart=/usr/sbin/nginx -g "daemon off;"

systemctl cat nginx shows the merged result; systemctl revert nginx removes your overrides.

Hardening options

systemd can sandbox a service with a few lines:

INI
[Service]
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp
CapabilityBoundingSet=
MemoryMax=512M

systemd-analyze security myapp scores a unit and suggests more options. Enable them one at a time and test, because a too-strict sandbox can break the program.

Timers instead of cron

A timer unit activates a service of the same name on a schedule.

INI
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
INI
# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup nightly

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
RandomizedDelaySec=10m

[Install]
WantedBy=timers.target
Terminal
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
systemctl list-timers
systemd-analyze calendar "Mon..Fri 08:00"     # preview a schedule

Persistent=true runs a missed job after the machine was off. Timers log to the journal, support dependencies and can run at boot time plus a delay (OnBootSec=), which cron cannot do as easily. Cron remains fine for simple jobs (Automation).

flowchart LR
    A["backup.timer"] -->|activates| B["backup.service"]
    B --> C["Journal log"]

A timer triggers the matching service.

Debugging a unit

Terminal
systemd-analyze verify /etc/systemd/system/myapp.service
systemctl status myapp
journalctl -u myapp -b
systemd-analyze blame        # slow boot units

Common causes of failure: a relative path in ExecStart, a user that does not exist, wrong file permissions, forgetting daemon-reload.

A stand-in: generate a unit file

This model builds a service unit from parameters. Review generated files before using them.

Python Stand-in: unit file generator

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.

A stand-in: when does a timer fire?

This model computes the next run times for a simple daily schedule, like OnCalendar=*-*-* 02:30:00.

Python Stand-in: next timer runs

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.

Common mistakes

  • Forgetting systemctl daemon-reload after editing a unit.
  • Using a relative path or shell syntax in ExecStart.
  • Editing packaged unit files; they are replaced on upgrade.
  • Running a service as root when a dedicated user would do (users).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should your own unit files go?

    /etc/systemd/system is for administrator-created units and overrides.
  2. 2. What must you run after editing a unit file?

    daemon-reload makes systemd re-read unit files.
  3. 3. What does Restart=on-failure do?

    It restarts for non-zero exit, signals or timeouts, not normal exits.
  4. 4. What does Persistent=true do in a timer?

    It catches up on runs missed while the system was down.

Summary

  • Custom units live in /etc/systemd/system; run daemon-reload after changes.
  • Use systemctl edit drop-ins instead of editing packaged files.
  • Restart policies and sandbox options make services resilient and safer.
  • Timers schedule services and log to the journal.

Next: Disks, Partitions and lsblk