Systemd is an init system and system manager that has become widespread and is becoming the new standard for Linux machines. Although there are legitimate doubts as to whether systemd is an improvement over traditional SysV initialization systems, most distributions have already switched to systemd, or plan to do so.
In short, systemd is responsible for working with processes: starting, stopping, checking status, reloading the configuration, and more. Those. this is a very important aspect of the OS that you need to understand and be able to use it. If you need to check the status (running or stopped, successfully starting, or crashed with an error) of the service, add the service to autoload or remove it from autoload, check the list of services in autoload, check the properties of the loaded service or see the causes of the error, then you turn to systemd.
Thanks to the widespread use of systemd among Linux systems, getting to know it is worth the time, understanding systemd will make server administration and your desktop Linux much easier. Learning and using the tools and daemons that systemd spans will help you better appreciate the power, flexibility, and capabilities that it provides, or at least help you do your work with minimal plugins.
In this guide, we will discuss the systemctl command, which is the central management tool for controlling the init system. We will look at how to manage services, check states, change system states and work with configuration files. We will cover the issues of how to manage services, check statuses, change system states and work with configuration files.
Please note: although systemd has become the standard initialization system for many Linux distributions, it is not implemented universally in all distributions. As you progress through this guide, if your terminal displays a bash: systemctl is not installed error , (bash: systemctl is not installed) , then you probably have a different initialization system installed on your computer.
The primary goal of an init system is to initialize the components that should start after the Linux kernel boots up (traditionally called “userland” components). The init system is also used to manage the services and daemons of a Linux-based computer at any time while the system is running. With this in mind, we will start with some simple service management operations.
In systemd, the goal (objects) of most actions are “ units ”, which are resources that systemd knows how to manage. Units are classified by the type of resource they represent and are defined by files known as unit files. The type of each unit can be determined by the suffix at the end of the file.
For service management tasks, the target unit is a service unit that has unit files with the suffix .service. However, for most service control commands, you can actually drop the .service suffix, since systemd is smart enough to know that you probably want to work with the service when using service control commands.
Starting and Stopping Services
To start the systemd service by following the instructions in the unit file, use the start command. If you are working as a non-root user, you will have to use sudo, because the command you execute will affect the state of the operating system:
sudo systemctl start apache2.service
As we mentioned above, systemd knows that you need to look for * .service files for service control commands, so this command can be entered without problems as follows:
sudo systemctl start apache2
Although you can use the above format for normal administration, for clarity in the rest of the commands, we will use the suffix .service to be explicit with respect to the purpose we are working on.
To stop the current service, use the stop command :
sudo systemctl stop apache2.service
Restart and Reboot
To restart a running service, you can use the restart command :
sudo systemctl restart apache2.service
If the application in question can reload its configuration files (without restarting), you can run the reload command to initiate this process:
sudo systemctl reload apache2.service
If you do not know if the service has the functionality to reload the configuration, you can run the reload-or-restart command. It will reload the configuration if the application supports this. Otherwise, it will restart the service so that the new configuration is picked up:
sudo systemctl reload-or-restart apache2.service
Enabling and Disabling Services
The above commands are useful for starting or stopping commands during the current session. In order for systemd to automatically start services when the computer boots, you must enable them.
To start the service at boot, use the enable command :
sudo systemctl enable apache2.service
This will create a symbolic link from a copy of the system service file (usually in /lib/systemd/system or /etc/systemd/system ) to a place on the disk where systemd looks for autostart files (usually /etc/systemd/system/ some target.target.wants ) We will move on to what target is, later in this guide).
To disable the automatic start of the service, you can type:
sudo systemctl disable apache2.service
This will remove the symbolic link indicating that the service should start automatically.
Keep in mind that enabling a service does not start it in the current session. If you want to start the service and enable it at boot time, you will have to issue start and enable commands. To add a service to startup at the same time and start it, use the –now switch :
sudo systemctl enable --now apache2.service
The above command will add the Apache webserver to startup and immediately launch it.
The –now switch works with the enable, disable, and mask commands, respectively, to immediately start, stop, or mask a unit, without waiting for the next boot.
The @ (“dog”) symbol in service names
Some unit names contain the @ symbol (i.e. [email protected]): this means that they are instances of a template unit whose real name does not contain the part that is indicated as string in the conditional example (i.e. name @ .service). string is called the instance identifier and is similar to the argument that is passed to the unit template when called with the systemctl command: in the unit file, it will replace the % i specifier.
For greater accuracy, before attempting to create an instance of the name @ .suffix of a unit template, systemd does look for a unit with the exact file name [email protected], even though such “conflicts” are quite rare, since most unit files containing the @ sign imply the use of patterns. In addition, if the unit template is called without an instance identifier, nothing will work, since the % i specifier cannot be substituted.
For example, in the OpenVPN unit file:
systemctl cat [email protected]
ExecStart=/usr/bin/openvpn --status %t/openvpn-server/status-%i.log --status-version 2 --suppress-timestamps --config %i.conf
The specifier % i is visible in this line ; when it is replaced, the name of the log file and configuration file is obtained.
Using various string values , it is possible to configure OpenVPN autorun with various configuration files. For example:
systemctl enable [email protected]_tcp_443
Many services support instance template models. For example, Apache2:
systemctl enable [email protected]
This command will cause the environment variable APACHE_CONFDIR to be set to /etc/apache2-test .
Checking the status of services
To check the status of a service on your system, you can use the status command :
systemctl status apache2.service
This will display the status of the service, the cgroup hierarchy, and the first few lines of the log.
For example, when checking the status of the Apache web server, you can see the output as follows:
This gives you a good overview of the current state of the application, notifies you of any problems and any actions that may be required.
There are also methods for checking specific conditions. For example, to check if a given service is active (works), you can use the is-active command :
systemctl is-active apache2.service
This will return the current state of the service, which is usually active or inactive. The exit code will be “0” if it is active, making the result easier to parse with programs and scripts.
To find out if a service is enabled for autostart, you can use the is-enabled command :
systemctl is-enabled apache2.service
Enabled or disabled will be displayed, and again the exit code will be set to “0” or “1” depending on the answer to the command question.
The third check is to see if the device is in a failed state. This indicates that there was a problem with the launch of the service in question:
systemctl is-failed apache2.service
This will return active if it works correctly or failed if an error occurs. If the device was intentionally stopped, unknown or inactive may be returned. Output status “0” means that a failure has occurred, and output status “1” indicates any other status.
The following command will immediately show all failed units:
System Status Overview
Commands have so far been useful for managing individual services, but they are not very useful for examining the current state of the system. There are several systemctl commands that provide this information.
List of Current Services
To view a list of all active units that the system knows about, we can use the list-units command :
This will show you a list of all units that systemd currently has in active status. The result will look something like this:
The output has the following columns:
- UNIT : Unit name systemd
- LOAD : Was the unit configuration successfully parsed (parsed) in systemd. The configuration of the loaded units is stored in memory.
- ACTIVE : The resulting state of whether the unit is active. This is usually a fairly simple way to unequivocally answer the question: did the unit launch successfully or not.
- SUB : This is a lower level state that indicates more detailed information about the device. This often depends on the type of device, the state and the actual method in which the device operates.
- DESCRIPTION : A short textual description of what the unit is / does.
Since the list-units command only shows active units by default, all of the above entries will appear as “ loaded ” in the LOAD column and “ active ” in the ACTIVE column . This mapping is actually the default behavior of systemctl when called without additional commands, so you will see the same if you call systemctl with no arguments:
systemctl list-units --all
This will show any unit that the system has downloaded or attempted to load, regardless of the current state of the system. After starting, some units become inactive, and some units that systemd tried to load could not be found on disk.
You can use other flags to filter these results. For example, we can use the –state = flag to indicate the LOAD , ACTIVE, or SUB states that we want to see. The –all flag must also be specified so that systemctl allows the display of inactive units:
systemctl list-units --all --state=inactive
systemctl list-units --type=service
systemctl --type=service --all
systemctl list-units --type=service --state=СТАТУС
systemctl --type=service --state=СТАТУС
For example, the output of services that have completed their work:
systemctl --type=service --state=exited
systemctl list-units --type=service --state=running
systemctl --type=service --state=running
List all unit files
The list-units command only displays units that systemd tried to parse and load into memory. Since systemd will only read units that it believes are needed, the list will not necessarily include all available units in the system. To view each available unit file in the systemd paths, including those that systemd did not attempt to load, you can use the list-unit-files command instead :
If you want to see only units added to autoload, then use the following construction:
systemctl list-unit-files | grep enabled
Below we look at what “ masked ” means .
So far, we have been working with services and displaying information about units and single files that systemd knows about. However, we can find out more specific unit information using some additional commands.
Display unit file
To display the unit file that systemd has uploaded to your system, you can use the cat command (it was added in systemd version 209). For example, to see the Apache web server unit file, we can enter:
systemctl cat apache2.service
The unit file will be displayed as it is known to the current working systemd process. This can be important if you recently modified unit files, or if you override some parameters in a unit file fragment (we will talk about this later).
To see the unit dependency tree, you can use the list-dependencies command :
systemctl list-dependencies ssh.service
Recursive dependencies are displayed only for .target units that indicate system states. To recursively list all dependencies, enable the –all flag.
To show the inverse dependencies (units depending on the specified unit), you can add the –reverse flag to the command . Other useful flags are the –before and –after flags , which can be used to display units that depend on the specified device, starting from before and after, respectively.
Verifying Unit Properties
To see the low-level properties of a unit, you can use the show command. It will display a list of properties set for the specified unit using the key = value format :
systemctl show sshd.service
systemctl show ssh.socket -p Conflicts
Applying and Removing Unit Masks
In the service management section, we looked at how to stop or disable a service, but systemd also has the ability to mark a device as completely unable to start, automatically or manually, by associating it with /dev/null . This is called unit masking and is possible with the mask command :
sudo systemctl mask nginx.service
If you check list-unit-files , you will see that the service now appears as masked :
sudo systemctl start nginx.service Failed to start nginx.service: Unit nginx.service is masked.
sudo systemctl unmask nginx.service
This will return the unit to its previous state, allowing it to start or turn on.
Editing Unit Files
Although we will not address the issue of unit file format in this guide, be aware that systemctl provides built-in mechanisms for editing and modifying unit files if you need to make adjustments. This functionality was added in systemd version 218.
The edit command will open a unit file fragment for this element by default:
sudo systemctl edit ssh.socket
Inside this directory, a snippet (fragment) with the name override.conf will be created . When a unit loads, systemd will in memory combine the override fragment with the full unit file. Fragment directives will take precedence over those specified in the unit’s source file.
If you want to edit the complete unit file instead of creating a fragment, you can pass the –full flag :
sudo systemctl edit --full ssh.socket
This will load the current unit file into the editor, where it can be changed. When you exit the editor, the modified file will be written to /etc/systemd/system, it will take precedence over the system definition of the unit (which is usually located somewhere in /lib/systemd / system ).
To remove all the additions you have made, delete the .d configuration directory or the modified service file from / etc / systemd / system . For example, to remove a snippet, we can enter:
sudo rm -r /etc/systemd/system/ssh.socket.d
To delete a complete modified unit file, one could type:
sudo rm /etc/systemd/system/ssh.service
After deleting the file or directory, you must restart the systemd process so that it no longer tries to reference these files and returns back to using system copies. You can do this by typing:
sudo systemctl daemon-reload
Setting up system status (trigger level) using goals
The targets are special unit files that describe the state of the system or the synchronization point. Like other units, files that define targets can be identified by their suffix, which in this case is .target . The goals themselves do not do much, but are instead used to group other units.
This can be used to bring the system into certain states, just as other initialization systems use runlevels. They are used as reference when certain functions are available, allowing you to specify the desired state instead of the individual units needed to create this state.
For example, there is swap.target , which is used to indicate that swap is ready to use. Units that are part of this process can synchronize for this purpose, indicating in their configuration that they WantedBy = or RequiredBy = target swap.target . Units that require a page file can specify this condition using the Wants = , Requires =, and After = specifications to indicate the nature of their relationship.
Getting and setting a default target
The systemd process has a default target, which it uses when booting the system. Satisfying the cascade of dependencies on this single goal will bring the system to the desired state. To find the default target for your system, enter:
sudo systemctl set-default graphical.target
List of available goals
You can get a list of available goals in your system by entering:
systemctl list-unit-files --type=target
systemctl list-units --type=target
You can start all units associated with the target and stop all units that are not part of the dependency tree. The command we need for this is called isolate . This is similar to changing the trigger level in other initialization systems.
For example, if you are working in a graphical environment with active graphical.target , you can turn off the graphics system and put the system into a multi-user command line state by isolating multi-user.target . Since graphical.target depends on multi-user.target , but not vice versa, all graphic blocks will be stopped.
You can take a look at the dependencies of the goal you are isolating before you complete this procedure to make sure that you are not stopping vital services:
systemctl list-dependencies multi-user.target
If you are comfortable with units that will be kept alive, you can isolate the target by typing:
sudo systemctl isolate multi-user.target
Using shortcuts for important events
There are goals specific to important events, such as shutting down or rebooting. However, systemctl also has a few shortcuts that add a bit of extra functionality.
For example, to put the system in rescue mode (single-user), you can simply use the rescue command instead of isolating rescue.target :
sudo systemctl rescue
This will provide additional functionality to alert all registered users about the event.
To stop the system, you can use the halt command :
sudo systemctl halt
To start a complete shutdown, you can use the poweroff command :
sudo systemctl poweroff
sudo systemctl reboot
For example, to reboot the system, you can usually enter:
By now, you should be familiar with some of the key features of the systemctl command that allow you to interact with and manage your systemd instance. The systemctl utility will be your main point of interaction with services and system state management.
Although systemctl primarily works with the systemd kernel process, there are other components in the systemd system that are controlled by other utilities. Other features, such as log management and user sessions, are handled by separate daemons and management utilities ( journald/journalctl and logind/loginctl, respectively). Take time to familiarize yourself with these other tools and daemons, this will make managing an easier task.