Home » How-to » Using Systemd Services Tutorial

Using Systemd Services Tutorial

Linux operating system as well as Windows supports not only regular applications but also services that work in the background. Services are very important, they monitor the state of the system, connect external devices and networks automatically, and allow processes to interact with hardware (dbus) and other. In addition, various web servers and database servers are implemented as services.

Services are working in the background, so you can't interact with them using regular tools. In this article, we will dive into how to use Systemd services in Linux. You will learn how to view services that are already running, stop, start, enable or disable autostart for services.


Table of Contents

Basics

You need an initialization system to manage services. The initialization system is the main service that starts other services at the right time, makes sure they work normally, writes logs, and most importantly provides an interface for services management to users. The initialization system is started by Linux kernel.

Before Systemd was developed, all Linux distributions used init scripts to handle services. At that time each service was started sequentially one by one, without the ability to start in parallel. After this, the initialization script took the PID identifier of the services process and stored it. This identifier can be used to check the state of the service and stop it when needed. All of this can be done manually.

But then Systemd was released. This initialization system allows to start services in parallel. So, now it is required to have the ability to configure dependencies for services. So, now service starting order is determined by a complicated dependency tree.

When the service is started, Systemd collects its output into a log and monitors its state. For example, it can restart a service when the service is suddenly failed.

Each service in Systemd must be described by a dedicated Unit file. The file contains information on how to start the service and how to manage it. Here you can see unit types list:

  • service - regular service, program;
  • target - group of services;
  • automount - mount point configuration which should be mounted automatically;
  • device - device file which is generated on system startup;
  • mount - mount point configuration;
  • path - path to a file or a folder;
  • scope - external process;
  • slice - a group of internal Systemd services;
  • snapshot - serialized state of running services;
  • socket - allows to activate the service when it is required;

In this article, I will describe only regular services (*.service) and a little bit about systemd targets (*.target). All other unit types were listed to get you a better understanding of Systemd.

All Systemd services can be divided into two groups:

  • system - all system services which can be managed only by users with superuser privileges. Configuration files for these services are located in the /lib/systemd/system and /usr/lib/systemd/system folders.
  • user - services that can be managed in user space by a regular user. Their configuration files are located in /lib/systemd/user or /usr/lib/systemd/user. Also, you can find user-specific services in his home directory $USER/.config/systemd/user.

Also, Systemd has jobs. It is actions which are performed for services. For example, starting, stopping, etc. A job exists only during the performing of any action to any service.

Now, you know the basics, let's have a look at the main utility for services management - systemctl.

Systemctl Command

Systemd has a tool for services management in Linux. It is systemctl command. This command allows to do a lot of things, for example, restart services, check their status and even analyze system startup performance. Here is the syntax of the command:

$ systemctl <options> <command> <service_name_1> <service_name_2>…

The <options> configures command behavior, output verbosity, etc. The <command> specifies what to do with the service. And <service_name_1> and <service_name_2> are the services for which the action will be performed. In few cases the command can be used without specifying command or service.

Options are depended on the command, so let's look at available commands first:

  • list-units - list all units which are loaded into the memory;
  • list-sockets - list all service sockets which are loaded into the memory;
  • list-timers - list all timers which are loaded into the memory
  • start - start the service in Linux
  • stop - stop the service in Linux
  • reload - ask the service to update its configuration from the filesystem
  • restart - restart the service
  • try-restart - restart the service only if it is running
  • reload-or-restart - ask the service to update its configuration from the filesystem, or if it is not supported just restart the service
  • isolate - run only one service or group of services with their dependencies, all other services will be stopped
  • kill - send a kill signal to the service. Can be used with --signal and --kill-who options
  • clean - remove all data related to the services, including cache, logs, execution data, etc.
  • is-active - check if the service is running
  • is-failed - check if the service is failed
  • status - view the state of the service and its logs
  • show - view the properties of the service
  • cat - view contents of the unit file for the service
  • reset-failed - clear the failed state for services which are exited with an error
  • list-dependencies - view dependencies for the service in Linux
  • list-unit-files - list all systemd units which are available in the system
  • enable - add the service to the system autostart
  • disable - remove the service from the system autostart
  • is-enabled - check if the service is started automatically
  • reenable - remove the service from system autostart, and then add it again
  • list-jobs - list all running Systemd jobs
  • snapshot - save the current state of all services for restoring in the future
  • daemon-reload - reload Systemd-specific configuration for all services
  • mask - make the unit not accessible
  • unmask - restore masked Systemd unit
  • link - add Systemd unit which is located not in one of the default folder for units
  • revert - revert the unit contents for the service to the default state.
  • edit - edit the service configuration without modified main unit file.

The systemctl utility supports other commands too. But most used are listed in this article. Now let's have a look at general systemctl options:

  • -t, --type - filter units by their service type
  • --state - filter units or services by their state
  • -a, --all - display all known services
  • -q - minimize output
  • --version - print the program version
  • --no-pager - disable pagination
  • --no-legend - disable columns description

Most actions are performed by commands, options just help to make the output more convenient.

How to Control Services in Linux

1. List Running Services

First of all, let's view all services which are loaded in memory. By default, you will see all units, for example, targets, mounts, timers, etc. If you want to get only services, filter the output by type using the --type option:

systemctl list-units --type service

Note that the command does not just output regular text. It opens less utility and passes the text into it. So, pagination is available here. You can scroll output using the up/down and right/left arrow keys. Press the q key to quit.

The command prints all services which are known by Systemd. They are running or were running before. Systemd does not look through all unit files when you use this command. The output of the command contains a few columns:

  • LOAD - the loaded value means that the unit file was successfully loaded.
  • ACTIVE - state of a service, helps to understand whether the unit is running or not.
  • SUB - detailed state of a service.
  • DESCRIPTION - short description of a service.

You can filter the list of services by their state using the --state option. For example, this command will print services which are running:

systemctl list-units --type service --state running

The following command prints services which were exited with an error:

systemctl list-units --type service --state failed

You can use any state value for the ACTIVE or SUB column.

2. List All Services

In the previous section, we have learned how to list services which are loaded in memory. But if you want to see all services you have to see at unit files. Use the list-unit-files command to do this. For example, you can print all existing units:

systemctl list-unit-files

Here you can see few columns too. But they little different. The first column reflects whether the unit is started automatically on the system startup. The second column displays the default state of autostart configuration. Now, let's filter only Linux services:

systemctl list-unit-files --type service

Here, you can use state filters as well as in the previous section, but the values will be different.

3. Search a Service by the Name

If you want to find a specific service but don't remember its full name, you can use filtering by pattern. For example, you can find all services with the name which starts with mysql:

systemctl list-unit-files 'mysql*'

4. Starting a Service

Use the start command to run a service. This command expects the service name as the first parameter:

sudo systemctl start <service_name.service>

For example, run the following command to start Nginx web-server:

sudo systemctl start nginx.service

Note, that the .service extension can be omitted. If everything works fine, the command will output nothing.

5. Stopping a Service

You can stop a service in Linux using this command:

sudo systemctl stop <service_name.service>

For example, you can use this command to stop Nginx web server:

sudo systemctl stop nginx

Even more, you can stop multiple services by one command using filtering by pattern. For example, you can stop all services which has name that starts with "php" using this command:

sudo systemctl stop 'php*.service'

But this works only for services which are running. You can start services using this approach. Pattern matching only works for units which are loaded in memory. So, when you try to start multiple services you can't be sure that the list is full.

6. Restarting a Service

There are two ways to restart services. The first way is completely restart when the services are stopped and started again. The second way is reloading when the service updates its configuration from the filesystem, but not all services support this.

Run this command to restart Nginx web-server:

sudo systemctl restart nginx

If you want the service to update its configuration, use the reload command:

sudo systemctl reload nginx

If the service does not support reloading you will get an error. You can use the reload-or-restart command to avoid this. In this case, the service will be restarted when reloading is not supported:

sudo systemctl reload-or-restart nginx

7. Getting the State of a Service

You can view the state of a service using the status command:

sudo systemctl status <service_name>

For example, run this command to view the state for Nginx web-server:

sudo systemctl status nginx

Here you can see the current status of a service in the Active field. Possible values are: active, inactive and dead. Also here you can find memory usage statistics, the number of running processes, and the main process PID. At the bottom of the command output, you can see the ten last lines of the service log. They can be very helpful for troubleshooting. If the 10 lines are not enough for you, specify the number of lines using the --lines option. For example:

sudo systemctl status --lines 10 avahi-daemon

In some cases, the log lines can be cut by the screen width. Use the -l option to avoid this:

sudo systemctl status -l nginx

8. Adding a Service to System Autostart

If you want to add service to the system autostart, use the enable command. For example, the command for adding Nginx web-server looks like this:

sudo systemctl enable nginx

To remove the service from the system autostart use the disable command:

sudo systemctl disable nginx

You can read about autostart in detail in the article How to Configure Service to Start Automatically in Linux.

9. Editing a Service

In some cases you may want to edit a systemd service file. For example, for adding extra environment variables or configuring auto restart. But you shouldn't edit unit files in /usr/lib or /lib folders. They can be overwritten on the next system update.

You can copy the required unit into the /etc/systemd/system/ folder and edit it here. There is the edit command, especially for these cases. Use it with the --full option to create a copy of the unit file in /etc/systemd/system folder. For example, use this command to edit the unit file for Nginx web-server:

sudo systemctl edit --full nginx

Make required changes and save the file. For example, you can add the SITE environment variable with the value losst:

Environment="SITE=losst"

When you use the edit command without the --full option for Nginx service, it will create the /etc/systemd/system/nginx.service.d folder and the override.conf file in it.

sudo systemctl edit nginx

Here you should place only the parameter which you want to change or add. For example place here this line to add the same environment variable:

Envirnoment="SITE=losst"

After unit changes you should update Systemd configuration from the disk using the following command:

sudo systemctl daemon-reload

Now, you can restart the service an ensure that the changes were applied.

10. Removing a Service

You can remove a service by removing the package which provides this service. But it does not work for default Systemd services. You can make the service unavailable for use. Use the mask command to do this:

sudo systemctl mask <service_name>

For example, masking Nginx web server:

sudo systemctl mask nginx

This command creates the symbolic link to /dev/null with the name of the service in the /etc/systemd/system folder. After this the service is masked. Pay attention, that if you have already edited the service you will get the error "Failed to mask unit: File /etc/systemd/system/*.service already exists". In this case, you can delete all modifications using the revert command. This command will erase all your changes:

sudo systemctl revert nginx

You can ensure that the service is masked using the status command:

sudo systemctl status nginx

Use the unmask command to make service available again:

sudo systemctl unmask nginx

How to Control User's Services in Linux

As I said before, Systemd supports not only system services service management, but also services which are owed by regular users. They do not require superuser privileges, start at the first user's authorization and stop when the last user's session ends. Unit files for these services are the same but they are located in different folders. You can find them in the home directory $USER/.config/systemd/user or in the system directories: /usr/lib/systemd/user/ and /lib/systemd/user/.

All commands for controlling these services are the same too but you must use the --user option. For example, use this command to list all user-specific services that are available for the current user:

systemctl --user list-unit-files --type service

In the same way, you can get the state of the service. Just use the status command with the --user option. For example, use this command to get the status of the dbus service:

systemctl --user status dbus.service

Wrapping Up

Now you wouldn't have problems with services management in Linux. This article can't cover everything about the services. Systemd is a very large complicated and multipurpose system. It can't be described in one article. But I think you can find here all that you need to control services effectively.

Creative Commons License
The article is distributed under Creative Commons ShareAlike 4.0 license. Link to the source is required .

Leave a Comment