Systemd Unit Files Everything You Need to Know

Systemd Unit Files Everything You Need to Know

systemd is the mother of daemons. Daemons are services running in the background without user interaction. As an initialization system, systemd is the first service to be started when the system boots up. It then starts other resources.

systemd often refers to the rest of the resources as units. Units are resources that systemd knows how to control, whereas unit files are configuration files defining units.

This tutorial walks you through the essentials of unit files. By the end of the tutorial, you should know how to distinguish unit files, describe their structures and manage them.

Let’s start by listing down the most typical unit files.

Types of Unit Files

There are 11 main types of unit files. Most unit types work together to add functionality to your Linux system. You can inspect the types on your system using the systemctl and help commands with the -t option.

Input
systemctl -t help
Output
Available unit types:
service
mount
swap
socket
target
device
automount
timer
path
slice
scope
Notes/ByteXD Articles/Systemd Unit Files Everything You Need to Know/List resource types.png

Here is what each resource does.

  • service: determines the starting, restarting or stopping of services and their dependencies.
  • mount: determines the mount points to attach systemd-controlled filesystems.
  • swap: determines the system swap space.
  • socket: describes local inter-process communication sockets or FIFO buffers used by the systemd for socket-based activation.
  • target: handles synchronization of unit files during the boot process.
  • device: dictates the devices to be exposed to systemd by udev and sysfs filesystems.
  • automount: avails automount capabilities.
  • timer: schedules the activation of other units. A matching unit file gets started when the timer is reached.
  • path: describes paths that activate other units when a file’s path gets modified.
  • slice: creates hierarchical tree out of group processes and daemons.
  • scope: manages externally created processes.

Apart from the types and roles, it would help to know the structure of unit files.

The Structure of Unit Files

Unit files are divided into sections. Each section has a portion to declare variables (directives) and assign them values. A section extends to the beginning of the next section or the end of a file.

A section’s name is case-sensitive and is often enclosed within a square bracket []. An equal sign = separates a directive and its value.

[Section]
Directive1=value
Directive2=value

Systemd allows for flexible configuration of the directives. For example, you can reset it,

Directive1=

or assign it a boolean expression like true, false, 1, 0,on, or off.

Most unit files have [Unit] as their first section. The [Unit] section stores the unit’s metadata and configures its relationship with other units.

Examples of directives in the [Unit] section are Description= for describing the unit’s name and fundamental functionality; Requires=, specifying the units that the current unit depends on.

The last section of a unit file is mostly the [Install] section. The optional section specifies whether a unit is enabled or disabled. It has directives like WantedBy= for determining how the unit file should be enabled and Alias= for allowing the unit to be enabled under another name.

Between the [Unit] and [Install] sections are unit-specific sections like [Service], [Socket], [Mount], and [Timer]. Unit types that lack unit-specific directives do not have associated sections for their types. Examples of such units are device, snapshot, scope, and target.

You can create multiple instances of units using template unit files. Unlike regular unit files, template unit files could be meaningless on their own. Such files are called using a special format. For example, you can call a service as follows.

<service_name>@<argument>.service

The argument is a string that determines how systemd deals with the specified instance of the unit file.

systemd can dynamically substitute appropriate information from a unit definition according to the operating environment. It replaces specific unit file directive values with template specifiers (starting with a percentage sign %). For example, %n allows the insertion of the resulting unit name in its place.

Where Are Unit Files Located?

Unit files are spread in various locations depending on priorities and implications. For example, /lib/systemd/system holds the system’s copy of unit files. A newly software-installed unit file gets to the directory.

On the other hand, /run/systemd/system stores runtime unit definitions. systemd uses this location to hold files dynamically created at runtime. Since the changes in the directory last per session, they get lost during a system reboot.

Managing Units

You will mostly interact with the .service unit files as follows.

Check the Status of a unit

The status command helps us check whether a service is active, inactive, enabled or disabled. An active service is running, while an inactive service is dead at the time of checking its status.

Active and inactive units
sudo systemctl status
Active units only
sudo systemctl list-units -t [unit file type]
Enabled and disabled unit files
sudo systemctl list-unit-files
One unit
sudo systemctl list-unit-files | grep [unit name]
Notes/ByteXD Articles/Systemd Unit Files Everything You Need to Know/List enabled and disabled units.png

Start a service

We can turn a service’s status from inactive to active using the start command.

Input
sudo systemctl start apache2
sudo systemctl status apache2
Output
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-10-16 09:34:49 EAT; 8s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 5922 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
   Main PID: 5926 (apache2)
      Tasks: 55 (limit: 4625)
     Memory: 5.0M
        CPU: 69ms
     CGroup: /system.slice/apache2.service
             ├─5926 /usr/sbin/apache2 -k start
             ├─5927 /usr/sbin/apache2 -k start
             └─5928 /usr/sbin/apache2 -k start

Onk 16 09:34:48 hostname systemd[1]: Starting The Apache HTTP Server...
Onk 16 09:34:48 hostname apachectl[5925]: AH00558: apache2: Could not reliably determine the server's fully qual>
Onk 16 09:34:49 hostname systemd[1]: Started The Apache HTTP Server.

Apache is now active.

Active: active (running) since Sun 2022-10-16 09:34:49 EAT; 8s ago

What if a service fails to start?

There could be errors preventing the service from starting. Since most systemd operations don’t print errors on the foreground, it may be hard to notice the errors. That is where the logs tool (journalctl) comes in.

Here is how to use it.

Is the journal active?
sudo systemctl is-active systemd-journald
Restart the journal
sudo systemctl restart systemd-journald
Check the logs
sudo journalctl -xe

Stop a Service

Stopping a service makes it dead.

stop apache2
sudo systemctl stop apache2
Is the journal active?
sudo systemctl is-active apache2
Output
inactive

You can reactivate the service using the restart command.

Restart a Service

A restart takes the system down while updating settings. On the other hand, a reload applies new settings while the system is running. Besides, you can use the restart-or-reload command when you want the system to decide whether to reload or restart after configurations.

restart
sudo systemctl restart apache2
reload
sudo systemctl reload apache2
reload-or-restart
sudo systemctl reload-or-restart apache2

Enable a Service

Enabling a service means programming it to start automatically during the next boot.

Check whether apache2 is enabled.
sudo systemctl is-enabled apache2
OR
sudo systemctl status apache2
Output
disabled
Enable the service
sudo systemctl enable apache2
Output
Synchronizing state of apache2.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable apache2
Created symlink /etc/systemd/system/multi-user.target.wants/apache2.service → /lib/systemd/system/apache2.service.
Enable and start a service immediately
sudo systemctl enable --now apache2
Check whether apache2 is enabled
sudo systemctl is-enabled apache2
Output
enabled

Disable a service

Disabling a service stops it from starting during the next boot.

Disable apache2
sudo systemctl disable apache2
Output
Synchronizing state of apache2.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install disable apache2
Removed /etc/systemd/system/multi-user.target.wants/apache2.service.
user@hostname:~$ sudo systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; disabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-10-16 09:45:17 EAT; 7min ago
       Docs: https://httpd.apache.org/docs/2.4/
   Main PID: 6054 (apache2)
      Tasks: 55 (limit: 4625)
     Memory: 5.0M
        CPU: 353ms
     CGroup: /system.slice/apache2.service
             ├─6054 /usr/sbin/apache2 -k start
             ├─6185 /usr/sbin/apache2 -k start
             └─6186 /usr/sbin/apache2 -k start

Onk 16 09:45:17 hostname systemd[1]: Starting The Apache HTTP Server...
Onk 16 09:45:17 hostname apachectl[6053]: AH00558: apache2: Could not reliably determine the server's fully qual>
Onk 16 09:45:17 hostname systemd[1]: Started The Apache HTTP Server.
Onk 16 09:45:27 hostname systemd[1]: Reloading The Apache HTTP Server...
Onk 16 09:45:27 hostname apachectl[6119]: AH00558: apache2: Could not reliably determine the server's fully qual>
Onk 16 09:45:27 hostname systemd[1]: Reloaded The Apache HTTP Server.
Onk 16 09:45:37 hostname systemd[1]: Reloading The Apache HTTP Server...
Onk 16 09:45:37 hostname apachectl[6184]: AH00558: apache2: Could not reliably determine the server's fully qual>
Onk 16 09:45:37 hostname systemd[1]: Reloaded The Apache HTTP Server.
Check the status of apache2
sudo systemctl status apache2
Notes/ByteXD Articles/Systemd Unit Files Everything You Need to Know/apache2 disabled.png

Summary

In this tutorial, you learned the following:

  • What are unit files?
  • Types and roles of unit files
  • The structure of unit files
  • Where unit files are located
  • How to manage unit files with the systemctl command

Now it is your turn to apply the knowledge.

0 Shares:
Subscribe
Notify of
guest
Receive notifications when your comment receives a reply. (Optional)
Your username will link to your website. (Optional)

0 Comments
Inline Feedbacks
View all comments
You May Also Like
Bash Printf Command
Read More

Bash Printf Command

The bash printf command prints the formatted strings in the shell. It stands for print formatted. The command…