Systemd – The anatomy of a unit file

A unit is a resource that systemd can manage. There are different types of units:

$ systemctl -t help
Available unit types:
service
socket
busname
target
snapshot
device
mount
automount
swap
timer
path
slice
scope   

These units are represented in the form of files, referred ‘unit files’. These files are located in /usr/lib/systemd/system directory. These files are named after the type of unit they represent.The structure of a unit file varies slightly from one unit file to another, but in general it looks something like this:

cat /usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSH server daemon
After=network.target sshd-keygen.service    # these units must be activated before this unit
Wants=sshd-keygen.service                 # systemd will attempt to start this at the same time as this unit. 
                                          # but can still function without it.  

[Service]
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

The WantedBy directive is particularly important. That’s because it tells systemctl which “target” it should make responsible for starting up the resource during boot time (if this unit is enabled).

You can find documentation about these directives here:

$ man systemd.unit

However you can view more details info about a particular unit type (e.g. service) like this:

$ man systemd.service

Note you can override a unit file, by creating a unit file of the same name, and placing it in /etc/systemd/system.

Also see:

https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files

Take the RHCSA Quiz

This article is part of our RHCSA Study guide (click on the yellow tab on the far left). By the end of this article you should be able to answer the following questions:


Which directory houses all the unit files?

/usr/lib/systemd/system

Where can you find help info about units?

$ man systemd.unit

Where can you find help info about the service unit type?

$ man systemd.service

How do you override some settings in the postfix.server unit file?

$ cp /usr/lib/systemd/system/postfix.service /etc/systemd/system/postfix.service
# then use vim to customise the copied file accordingly.