Manage Systemd Services and Units using systemctl

An init system and system manager called systemd has rapidly emerged as the new norm for Linux distributions. The widespread use of systemd makes it well worth the effort to become familiar with it because it will make managing servers much simpler. You will be able to better understand systemd’s power, flexibility, and capacities by learning about and using its tools and daemons, or at the very least, you will be able to do your tasks with less effort.

The systemd calls Any software that operates in the “background” (without a terminal or user interface), typically watching for events to happen and providing services, was given the acronym “daemon” to represent a “service”. A good illustration is a web server that waits for a request before delivering a page or an SSH server that watches for attempts to log in. Despite the fact that they are fully functional programs, there are daemons whose work is less obvious.

Most systemd actions have “units” as their target, which are resources that systemd understand how to manage. Units are classified according to the type of resource they represent, and they are defined using unit files. The suffix at the end of the file indicates the kind of each unit. The target unit for service management tasks will be service units, which have unit files ending in .service. However, for most service management commands, you can omit the .service suffix since Systemd is smart enough to recognize that You’re probably using service management commands to interact with a service.

The basic command for inspecting and controlling systemd is systemctl. Its applications include system condition verification and system and service management.

In this guide, we will walk you through how to Manage Systemd Services and Units using systemctl. Let’s dive to learn more about systems services.

Starting and Stopping Services

The start command is used to start a systemd service by executing the instructions below in the service’s unit file. You should use the sudo command if you’re not a root user.

sudo systemctl start application.service

As previously stated, systemd knows to check for *.service files for service management commands, therefore the command might be written as follows:

sudo systemctl stop application.service

While the aforementioned syntax is acceptable for general administration, we will use the .service suffix for the remaining commands to be clear about the target we are working on.

To stop the running service, you just run like below.

sudo systemctl stop application.service

Restarting and Reloading Services

To restart the running service, utilize the restart command:

sudo systemctl restart application.service

You can use the reload command to start the process of reloading the configuration files if the application in question can do so without restarting:

sudo systemctl reload application.service

The reload-or-restart command might be used if you are unsure whether the service has the ability to reload its configuration. If available, this will reload the current configuration. If not, the service will be restarted to pick up the updated configuration:

sudo systemctl reload-or-restart application.service

Enabling and Disabling Services

Services must be enabled in order to instruct systemd to launch them automatically at boot. Simply run the enable command below.

sudo systemctl enable application.service

This will generate a symbolic link from the system’s copy of the service file (often in /lib/systemd/system or /etc/systemd/system) to the directory on disk where systemd checks for autostart files (typically /etc/systemd/system/some_target.target.wants). A target will be defined later in this book).

To disable the service from launching automatically, you will run disable command:

sudo systemctl disable application.service

The symbolic link that suggested the service should launch automatically will be removed as a result of this action.

Checking the service status

You can use the status command to determine a service’s status on your system:

sudo systemctl status application.service

You will receive the service status, the cgroup hierarchy, and the first few lines of the log from this.

There are various ways to look for particular states. For instance, you may use the is-active command to determine whether a unit is now active (running):

systemctl is-active application.service

The current unit state, which is often active or inactive, will be returned. If it is activated, the exit code will be “0,” which makes the output easier for shell scripts to understand.

To determine whether the unit is enabled, use the is-enabled command:

systemctl is-enabled application.service

It will then again set the exit code to “0” or “1” depending on the response to the command question and output whether the service is enabled or disabled.

A third test is to see if the unit has failed. This indicates that there was an issue with the unit’s startup:

systemctl is-failed application.service

If everything is working properly, this will return active; otherwise, it will fail. If the unit was halted deliberately, it may return unknown or inactive. A “0” exit status implies a failure, whereas a “1” exit status indicates any other status.

To locate the systemd services that failed to start execute the line below.

systemctl --state=failed

Listing Current Units

So far, the commands have proven effective for managing single services, but not for exploring the present status of the system. A number of systemctl commands offer this information.

To get a list of all active units that systemd is aware of, employ the list-units command:

systemctl list-units

Alternatively, you can execute the systemctl without passing any argument.

systemctl

By passing additional options to systemctl, we can instruct it to output alternative information. For example, you may use the –all flag to examine all the units that systemd has loaded (or attempted to load), regardless of whether they are currently active:

systemctl list-units --all

Other flags can be used to narrow down the results. For instance, we can use the –state= parameter to specify whether we want to observe the LOAD, ACTIVE, or SUB states. You must maintain the –all flag in order for systemctl to display non-active units:

systemctl list-units --all --state=inactive

The –type= filter is another typical one. We can instruct systemctl to only display units of the type we are interested in. For example, to show just active service units, we could apply:

systemctl list-units --type=service

Listing All Unit Files

To see every accessible unit file located in systemd paths, including ones that systemd has not attempted to load, use the list-unit-files command as well:

systemctl list-unit-files

Unit Management

We have been using services and displaying data about the units and unit files that systemd are aware of. However, by applying a few extra commands, we may learn more details about units.

1. Displaying a Unit File:

The cat command can be used to display the unit file that systemd has loaded into its system. For example, to view the atd scheduling daemon’s unit file, we could type:

systemctl cat atd.service

This is useful if you have recently modified unit files or if you are overriding particular options in a unit file fragment.

2. Displaying Dependencies:

You can use the list-dependencies command to view the dependency tree for a unit, for example, sshd.service:

systemctl list-dependencies sshd.service

The –reverse parameter can be added to the command to display reverse dependencies or units that depend on the specified unit. The –before and –after flags, which can be used to display units that start before and after the chosen unit, respectively, are additional helpful flags.

3. Checking Unit Properties:

The show command can be used to display a unit’s low-level attributes. This will show a list of properties set for the selected unit in key=value format:

systemctl show sshd.service

If you just want to display a single property, use the -p flag along with the property name. For example, to view the conflicts that the sshd.service unit has, type:

systemctl show sshd.service -p Conflicts

Masking and Unmasking Units

We covered how to halt or disable a service in the service management section, but systemd can also mark a unit as fully unstartable, either automatically or manually, by connecting it to /dev/null. This is known as masking the unit, and it is possible with the mask command:

sudo systemctl mask nginx.service

As long as the Nginx service is masked, this will prevent it from starting either automatically or manually.

You can notice that the service is now marked as masked in the list-unit-files:

$ systemctl list-unit-files
. . .
kmod-static-nodes.service              static
ldconfig.service                       static
mandb.service                          static
messagebus.service                     static
nginx.service                          masked
..................

Now try to start the service:

$ sudo systemctl start nginx.service
Failed to start nginx.service: Unit nginx.service is masked.

Unmasking Units

Use the unmask command to remove a unit’s mask, restoring its usability:

sudo systemctl unmask nginx.service

The Nginx unit will be restored.

Editing Unit Files

If you need to make changes, systemctl has built-in tools for editing and altering unit files. A unit file snippet for the unit in question will be opened by default when using the edit command:

sudo systemctl edit nginx.service

This will be a blank file in which you can override or add directives to the unit specification. Within the /etc/systemd/system directory, a directory with the name of the unit added .d will be created. For example, a directory called nginx.service.d will be created for the nginx.service.

A snippet called override.conf will be produced within this directory. When the unit is loaded, systemd will combine the override snippet with the whole unit file in memory.

If you want to change the entire unit file rather than just a snippet, use the –full flag:

sudo systemctl edit --full nginx.service

This will open the editor and allow you to modify the current unit file. When the editor is closed, the updated file is written to /etc/systemd/system, which takes precedence over the system’s unit definition (which is normally found in /lib/systemd/system).

To remove any modifications, either delete the unit’s.d configuration directory or the changed service file from /etc/systemd/system. For example, to remove a fragment, we could type:

sudo rm -r /etc/systemd/system/nginx.service.d

To delete a fully edited unit file, type:

sudo rm /etc/systemd/system/nginx.service

After removing the file or directory, restart the systemd process so that it no longer attempts to reference these files and instead uses the system copies.

sudo systemctl daemon-reload

Adjusting System State (Runlevel) with Targets

Targets are unique unit files that specify a synchronization point or a state of the system. The files that define targets can be recognized by their suffix, which in this case is .target, just like other units. Targets are used to group other units together, rather than doing much of anything themselves.

For example, a swap.target is used to signal when a swap is prepared for usage. By specifying in their configuration that they are WantedBy= or RequiredBy= the swap.target, units that are a part of this process can sync with this target. By using the Wants=, Requires=, and After= specifications, units that need swap to be accessible can define this requirement. These specifications let you know how these units are related to one another.

1. Getting and Setting the Default Target:

In order to start the system, the systemd process utilizes a default target. The system will reach the intended state after all of its dependencies on that one objective have been satisfied. Type: to locate your system’s default target.

systemctl get-default

The set-default command can be used to set a different default target. By way of example, if you installed a graphical desktop and want the system to launch into that by default, you can adjust your default target as follows:

sudo systemctl set-default graphical.target

2. Listing Available Targets:

You can find a list of the targets that are accessible on your system by issuing the following command:

systemctl list-unit-files --type=target

Multiple targets may be active simultaneously, unlike runlevels. An active target means that systemd has tried to restart all the units connected to it, but has not yet attempted to untie them. To view every active target run:

systemctl list-units --type=target

All the units connected to a target can be started, and all the ones not connected to the dependency tree can be stopped. Isolate is the command that we need to use to do this. In other init systems, changing the runlevel is comparable to this.

As an illustration, if you are in a graphical environment and have the graphical.target active, you can isolate the multi-user.target and put the system into a multi-user command line mode. Because graphical.target is dependent on multi-user.target but not either way around, all graphical units will be terminated.

Before conducting this method, you should examine the target’s dependencies to ensure that you are not interrupting important services by using the following command.

systemctl list-dependencies multi-user.target

When you’re happy with the units you’ll keep alive, isolate the target by typing:

sudo systemctl isolate multi-user.target

Making Use of Shortcuts for Important Events

For significant occurrences like rebooting or shutting down, there are targets set. Systemctl does, however, also offer a few shortcuts that extend its functionality a little.

To set the system into rescue (single-user) mode, for example, use the rescue command rather than isolate rescue.target:

sudo systemctl rescue

Additionally, this will notify all users who are currently logged in about the event.

  • You can use the halt command to shut down the system:
sudo systemctl halt
  • To force a complete shutdown, use the poweroff command:
sudo systemctl poweroff
  • The reboot command can be used to initiate a restart:
sudo systemctl reboot
  • To suspend the system run:
sudo systemctl suspend
  • To Put the system into hibernation execute the command below.
sudo systemctl hibernate
  • Set the system to hybrid sleep (or suspend-to-both).
sudo systemctl hybrid-sleep

Learn more about using systemctl to control the systemd service.

Final Thought

You ought to be acquainted by now with some of the fundamental skills of the systemctl command that let you communicate with and manage your systemd instance. Your primary point of contact for managing services and system status will be the systemctl utility.

Your IT Journey Starts Here!

Ready to level up your IT skills? Our new eLearning platform is coming soon to help you master the latest technologies.

Be the first to know when we launch! Join our waitlist now.

Join our Linux and open source community. Subscribe to our newsletter for tips, tricks, and collaboration opportunities!

Recent Post

Leave a Comment

Your email address will not be published. Required fields are marked *

Related Post

Let’s clarify the differences between merge requests (commonly called pull requests in GitHub), releases, release candidates (RCs), tags, and branches […]

Kind (which in full means “Kubernetes IN Docker”), is a command line tool that enables you to run Kubernetes clusters […]

Are you looking for an easy way to migrate packages from one cPanel server to a new cPanel server? In […]

Let's Connect

Unleash the full potential of your business with CloudSpinx. Our expert solutions specialists are standing by to answer your questions and tailor a plan that perfectly aligns with your unique needs.
You will get a response from our solutions specialist within 12 hours
We understand emergencies can be stressful. For immediate assistance, chat with us now

Contact CloudSpinx today!

Download CloudSpinx Profile

Discover the full spectrum of our expertise and services by downloading our detailed Company Profile. Simply enter your first name, last name, and email address.