Linux - Linux systemd Service and Unit Management
Introduction
systemd is the modern system and service manager used by many Linux distributions, including Ubuntu, Debian, Fedora, Red Hat Enterprise Linux, CentOS Stream, and Arch Linux. It is responsible for bringing the system into an operational state during boot and managing services and other system resources while the operating system is running.
The main purpose of systemd is to start, stop, restart, monitor, and organize system services. Instead of manually launching programs whenever the computer starts, administrators can define them as systemd units and allow systemd to manage their entire lifecycle.
For example, a web server such as Apache or Nginx can be configured as a service. systemd can automatically start it during boot, restart it when requested, stop it during shutdown, and provide information about whether it is currently running.
What Is a Service?
A service is a background program that performs a particular task without requiring continuous interaction from the user.
Common examples include:
-
Web servers
-
Database servers
-
SSH servers
-
Network management services
-
Logging services
-
Scheduled background applications
-
Monitoring applications
For example, the OpenSSH server provides remote login capabilities. On a Linux system managed by systemd, it can be controlled through commands such as:
sudo systemctl start ssh
sudo systemctl stop ssh
sudo systemctl restart ssh
sudo systemctl status ssh
The exact service name can differ between distributions. For example, some systems use ssh, while others use sshd.
What Is a Unit?
A unit is an object that systemd knows how to manage. Services are only one type of unit. systemd supports several different unit types for managing different resources and activities.
Important unit types include:
| Unit Type | Purpose |
|---|---|
.service |
Manages system services |
.socket |
Manages network or IPC sockets |
.target |
Groups units into a particular system state |
.timer |
Schedules tasks |
.mount |
Manages filesystem mount points |
.automount |
Manages automatic mounting |
.path |
Activates units when filesystem paths change |
.device |
Represents devices recognized by the kernel |
.swap |
Manages swap devices and files |
A unit file contains instructions that tell systemd how a particular resource should be managed.
For example, a simplified service unit could look like:
[Unit]
Description=Example Application
[Service]
ExecStart=/usr/local/bin/example-app
Restart=on-failure
[Install]
WantedBy=multi-user.target
This tells systemd what the application is, how to start it, what to do if it fails, and which system target should use the service.
Understanding systemctl
systemctl is the primary command-line utility used to communicate with systemd.
The general syntax is:
systemctl [command] [unit]
For example:
systemctl status nginx
This requests the current status of the Nginx service.
Starting a Service
To start a service immediately:
sudo systemctl start nginx
Starting a service does not necessarily mean that it will automatically start the next time the computer boots.
This distinction is important because start controls the service's current state, while enable controls whether it is automatically activated during boot.
Stopping a Service
To stop a running service:
sudo systemctl stop nginx
The service stops immediately, but this does not necessarily change its boot configuration.
Restarting a Service
When configuration changes have been made, a service may need to be restarted:
sudo systemctl restart nginx
This stops and starts the service again.
Restarting is commonly used after modifying application configuration files.
Reloading a Service
Some applications support configuration reloading without completely stopping the service:
sudo systemctl reload nginx
A reload asks the service to reread its configuration while attempting to keep the existing process running.
This can be preferable to a restart when uninterrupted connections or service availability are important.
Not every service supports reload operations.
Checking Service Status
The status command provides information about a service:
systemctl status nginx
The output can show whether the service is:
-
Loaded
-
Enabled or disabled
-
Active or inactive
-
Running or failed
-
When it was started
-
The process ID
-
Recent log messages
A typical status may contain information similar to:
Active: active (running)
This indicates that the service is currently running.
If the output shows:
Active: failed
the service encountered a problem and requires investigation.
Enabling a Service at Boot
To configure a service to start automatically during system boot:
sudo systemctl enable nginx
This creates the appropriate relationship between the service and the relevant boot target.
To enable and start a service immediately, many systems support:
sudo systemctl enable --now nginx
This is useful when you want the service to run now and also start automatically during future boots.
Disabling a Service
To prevent a service from being automatically started through its normal boot configuration:
sudo systemctl disable nginx
Disabling does not necessarily stop a service that is currently running.
If you want to disable it and stop it immediately:
sudo systemctl disable --now nginx
Masking a Service
systemd also provides a stronger mechanism called masking.
sudo systemctl mask nginx
A masked service cannot normally be started until it is unmasked.
To remove the mask:
sudo systemctl unmask nginx
Masking is useful when an administrator needs to ensure that a service cannot accidentally or automatically be started.
The difference between disabling and masking is important. Disabling changes automatic activation behavior, whereas masking prevents normal manual or automatic activation entirely.
Understanding Targets
A target is a special type of systemd unit used to group other units and represent particular system states.
Traditional Linux systems often used concepts such as runlevels. systemd uses targets for a similar but more flexible purpose.
Some commonly encountered targets include:
multi-user.target
graphical.target
rescue.target
emergency.target
multi-user.target generally represents a system that has reached a normal multi-user operating state without necessarily running a graphical desktop.
graphical.target represents a system state in which graphical login and desktop-related services are available.
You can determine the default target using:
systemctl get-default
A system might return:
graphical.target
The default target can be changed with:
sudo systemctl set-default multi-user.target
Service Dependencies
One of the important strengths of systemd is its ability to understand relationships between units.
A service may depend on another service or system component.
For example, a network-dependent application may need network functionality before it can operate correctly.
Unit files can express relationships using directives such as:
After=
Before=
Requires=
Wants=
Conflicts=
After= specifies ordering.
For example:
After=network.target
means that the service should be started after network.target.
However, After= primarily establishes ordering. It does not necessarily mean that the other unit must successfully start.
Requires= expresses a stronger dependency relationship.
Wants= establishes a weaker relationship in which another unit is wanted but its failure does not necessarily cause the dependent unit to fail.
Understanding the difference between ordering and dependency is essential when designing reliable services.
Viewing Service Logs
systemd commonly works with journald, the system's logging component.
The journalctl command can be used to inspect service logs.
For example:
sudo journalctl -u nginx
This displays journal entries associated with the Nginx service.
To view only recent entries:
sudo journalctl -u nginx -n 50
To follow new log messages as they appear:
sudo journalctl -u nginx -f
This is particularly useful when troubleshooting a service that starts but then fails.
Creating a Custom Service
Administrators can create their own systemd services.
For example, suppose an application is located at:
/usr/local/bin/myapp
A service file could be created under:
/etc/systemd/system/myapp.service
A simple example is:
[Unit]
Description=My Custom Application
After=network.target
[Service]
ExecStart=/usr/local/bin/myapp
Restart=on-failure
User=myuser
[Install]
WantedBy=multi-user.target
The [Unit] section provides general information and relationships with other units.
The [Service] section describes how the application should be executed.
The [Install] section defines how the service can be integrated into the system's startup configuration.
Reloading Unit Configuration
After creating or modifying a unit file, systemd needs to reread its configuration.
Use:
sudo systemctl daemon-reload
This does not restart every service. It tells systemd to reload its unit-file configuration.
After that, the service can be started:
sudo systemctl start myapp
And enabled for future boots:
sudo systemctl enable myapp
Checking Whether a Service Is Enabled
You can check whether a service is configured for automatic startup:
systemctl is-enabled nginx
Possible results include:
enabled
disabled
masked
static
A service marked enabled is configured for automatic activation through its installation relationships.
A static unit generally does not have its own enablement configuration and is normally activated as a dependency or by another mechanism.
Listing Services
To list currently loaded service units:
systemctl list-units --type=service
To include inactive service units as well:
systemctl list-units --type=service --all
You can also list installed service unit files:
systemctl list-unit-files --type=service
These commands are useful for system administration because they allow an administrator to understand which services exist and which are currently active.
Troubleshooting Failed Services
When a service fails, a systematic approach is useful.
First, check its status:
systemctl status myapp
Then examine its logs:
journalctl -u myapp
You can also inspect recent log entries:
journalctl -u myapp -n 100
If the service is repeatedly failing, check the service definition:
systemctl cat myapp
Then verify that the executable specified by ExecStart exists and can be executed.
For example:
ls -l /usr/local/bin/myapp
Configuration errors, incorrect file paths, missing permissions, unavailable dependencies, incorrect environment settings, and application-level failures are common causes of service problems.
systemd and the Boot Process
During system startup, systemd becomes the primary userspace process and coordinates the transition toward the system's configured target.
Rather than simply starting every service sequentially, systemd can analyze dependencies and start independent units in parallel where possible.
This dependency-based approach can improve boot efficiency and provides a structured way to control how different components interact.
For example, if several services do not depend on each other, they may be started concurrently rather than waiting for each one to finish before starting the next.
Important systemctl Commands
| Command | Purpose |
|---|---|
systemctl start SERVICE |
Start a service |
systemctl stop SERVICE |
Stop a service |
systemctl restart SERVICE |
Restart a service |
systemctl reload SERVICE |
Reload service configuration |
systemctl status SERVICE |
Display service status |
systemctl enable SERVICE |
Enable automatic startup |
systemctl disable SERVICE |
Disable automatic startup |
systemctl mask SERVICE |
Prevent normal activation |
systemctl unmask SERVICE |
Remove a service mask |
systemctl is-active SERVICE |
Check whether service is active |
systemctl is-enabled SERVICE |
Check boot enablement |
systemctl daemon-reload |
Reload unit-file configuration |
systemctl list-units |
List loaded units |
systemctl get-default |
Display default target |
systemctl set-default TARGET |
Change default target |
Advantages of systemd
systemd provides several important benefits for Linux administration.
First, it provides a unified interface for controlling services and many other system resources. Administrators can use familiar commands rather than dealing with different management mechanisms for every service.
Second, dependency management allows services to be started in an organized manner. systemd can determine relationships between units and use those relationships when starting or stopping components.
Third, service status and logs can be investigated through tools such as systemctl and journalctl, making troubleshooting more systematic.
Finally, systemd supports advanced capabilities such as service isolation, resource controls, socket activation, timers, automatic restarts, and dependency-based activation.
Conclusion
Linux systemd is much more than a command for starting and stopping services. It is a complete system and service manager responsible for coordinating many parts of a running Linux system. Its unit-based architecture allows services, targets, timers, sockets, mounts, and other resources to be managed through a consistent framework.
For Linux administrators, understanding the difference between start and enable, stop and disable, reload and restart, and dependencies and ordering is particularly important. Once these concepts are understood, tools such as systemctl, journalctl, and custom unit files provide a powerful foundation for managing and troubleshooting Linux servers.