Linux Labs

Packages, services, and logs / Stage 8 of 13

Your own service unit and applying changes

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 7 · theory · 6 min

What a unit file is made of

A unit file is settings for systemd, not a shell script. This step covers its sections and main lines.

Here is the whole lab-worker file:

ini
[Unit]
Description=Linux Labs worker

[Service]
Type=exec
User=student
ExecStart=/usr/bin/sleep 86400
Restart=no

[Install]
WantedBy=multi-user.target

The lines are grouped into sections:

Section What it holds
[Unit] the service description and its start order among other units
[Service] how to start the program: Type, User, ExecStart, Restart
[Install] which target enable attaches the service to: WantedBy

User is the user to start the program as; without this line a system service runs as root. For your own service you usually create a separate account that cannot log in: sudo useradd -r -s /usr/sbin/nologin myapp (useradd). Type=exec means the start has succeeded once the program has begun to run.

systemd runs ExecStart itself, without a shell. That is why the program path in it is a full one, and |, >, & and ~ do not work there: the program gets them as ordinary words.

Check yourself 1 question

A service unit says ExecStart=/usr/bin/echo ready > /tmp/ready. What happens once the service starts?

  • systemd neither parses nor objects to >: it starts /usr/bin/echo and hands it every word of the line.

  • > is understood by a shell, and systemd starts the program without one: echo gets > and /tmp/ready as ordinary words.

  • A service has no terminal: what the program prints, systemd writes into the service journal.

systemd starts the program from ExecStart without a shell, so > and the path reach echo as words, and it prints them into the service journal. When a shell is really needed, it is called explicitly: ExecStart=/bin/sh -c '…'.

Key points

  • The [Service] section says how to start: ExecStart is the program, run without a shell, User says as whom, Restart says when to start it again.
  • [Install] is there for enable: WantedBy names the target the service gets attached to.
Ubuntu 24.04
Loading…