Questo contenuto non è disponibile nella lingua selezionata.

Chapter 12. Managing systemd


As a system administrator, you can manage critical aspects of your system with systemd. Serving as a system and service manager for Linux operating systems, systemd software suite provides tools and services for controlling, reporting, and system initialization. Key features of systemd include:

  • Parallel start of system services during boot
  • On-demand activation of daemons
  • Dependency-based service control logic

The basic object that systemd manages is a systemd unit, a representation of system resources and services. A systemd unit consists of a name, type and a configuration file that defines and manages a particular task. You can use unit files to configure system behavior. See the following examples of various systemd unit types:

Service
Controls and manages individual system services.
Target
Represents a group of units that define system states.
Device
Manages hardware devices and their availability.
Mount
Handles file system mounting.
Timer
Schedules tasks to run at specific intervals.
Note

To display all available unit types:

 # systemctl -t help

12.1. Systemd unit files locations

You can find the unit configuration files in one of the following directories:

Table 12.1. systemd unit files locations
DirectoryDescription

/usr/lib/systemd/system/

systemd unit files distributed with installed RPM packages.

/run/systemd/system/

systemd unit files created at run time. This directory takes precedence over the directory with installed service unit files.

/etc/systemd/system/

systemd unit files created by using the systemctl enable command as well as unit files added for extending a service. This directory takes precedence over the directory with runtime unit files.

The default configuration of systemd is defined during the compilation and you can find the configuration in the /etc/systemd/system.conf file. By editing this file, you can modify the default configuration by overriding values for systemd units globally.

For example, to override the default value of the timeout limit, which is set to 90 seconds, use the DefaultTimeoutStartSec parameter to input the required value in seconds.

DefaultTimeoutStartSec=required value

12.2. Managing system services with systemctl

As a system administrator, you can manage system services by using the systemctl utility. You can perform various tasks, such as starting, stopping, restarting running services, enabling and disabling services to start at boot, listing available services, and displaying system services statuses.

12.2.1. Listing system services

You can list all currently loaded service units and display the status of all available service units.

Procedure

Use the systemctl command to perform any of the following tasks:

  • List all currently loaded service units:

    $ systemctl list-units --type service
    UNIT                     LOAD   ACTIVE SUB     DESCRIPTION
    abrt-ccpp.service        loaded active exited  Install ABRT coredump hook
    abrt-oops.service        loaded active running ABRT kernel log watcher
    abrtd.service            loaded active running ABRT Automated Bug Reporting Tool
    ...
    systemd-vconsole-setup.service loaded active exited  Setup Virtual Console
    tog-pegasus.service            loaded active running OpenPegasus CIM Server
    
    LOAD   = Reflects whether the unit definition was properly loaded.
    ACTIVE = The high-level unit activation state, or a generalization of SUB.
    SUB    = The low-level unit activation state, values depend on unit type.
    
    46 loaded units listed. Pass --all to see loaded but inactive units, too.
    To show all installed unit files use 'systemctl list-unit-files'

    By default, the systemctl list-units command displays only active units. For each service unit file, the command provides an overview of the following parameters:

    UNIT
    The full name of the service unit
    LOAD
    The load state of the configuration file
    ACTIVE or SUB
    The current high-level and low-level unit file activation state
    DESCRIPTION
    A short description of the unit’s purpose and functionality
  • List all loaded units regardless of their state, by using the following command with the --all or -a command line option:

    $ systemctl list-units --type service --all
  • List the status (enabled or disabled) of all available service units:

    $ systemctl list-unit-files --type service
    UNIT FILE                               STATE
    abrt-ccpp.service                       enabled
    abrt-oops.service                       enabled
    abrtd.service                           enabled
    ...
    wpa_supplicant.service                  disabled
    ypbind.service                          disabled
    
    208 unit files listed.

    For each service unit, this command displays:

    UNIT FILE
    The full name of the service unit
    STATE
    The information whether the service unit is enabled or disabled to start automatically during boot

Additional resources

12.2.2. Displaying system service status

You can inspect any service unit to get detailed information and verify the state of the service, whether it is enabled to start during boot or currently running. You can also view services that are ordered to start after or before a particular service unit.

Procedure

Use the systemctl command to perform any of the following tasks:

  • Display detailed information about a service unit that corresponds to a system service:

    $ systemctl status <name>.service

    Replace <name> with the name of the service unit you want to inspect (for example, gdm).

    This command displays the following information:

    • The name of the selected service unit followed by a short description
    • One or more fields described in Available service unit information
    • The execution of the service unit: if the unit is executed by the root user
    • The most recent log entries

      Table 12.2. Available service unit information
      FieldDescription

      Loaded

      Information whether the service unit has been loaded, the absolute path to the unit file, and a note whether the unit is enabled to start during boot.

      Active

      Information whether the service unit is running followed by a time stamp.

      Main PID

      The process ID and the name of the corresponding system service.

      Status

      Additional information about the corresponding system service.

      Process

      Additional information about related processes.

      CGroup

      Additional information about related control groups (cgroups).

    Example 12.1. Displaying service status

    The service unit for the GNOME Display Manager is named gdm.service. To determine the current status of this service unit, type the following at a shell prompt:

    # systemctl status gdm.service
    gdm.service - GNOME Display Manager
       Loaded: loaded (/usr/lib/systemd/system/gdm.service; enabled)
       Active: active (running) since Thu 2013-10-17 17:31:23 CEST; 5min ago
     Main PID: 1029 (gdm)
       CGroup: /system.slice/gdm.service
               ├─1029 /usr/sbin/gdm
               └─1047 /usr/bin/Xorg :0 -background none -verbose -auth /r...
    
    Oct 17 17:31:23 localhost systemd[1]: Started GNOME Display Manager.
  • Verify that a particular service unit is running:

    $ systemctl is-active <name>.service
  • Determine whether a particular service unit is enabled to start during boot:

    $ systemctl is-enabled <name>.service
    Note

    Both systemctl is-active and systemctl is-enabled commands return an exit status of 0 if the specified service unit is running or enabled.

  • Check what services systemd orders to start before the specified service unit

    # systemctl list-dependencies --after <name>.service

    For example, to view the list of services ordered to start before gdm, enter:

    # systemctl list-dependencies --after gdm.service
    gdm.service
    ├─dbus.socket
    ├─getty@tty1.service
    ├─livesys.service
    ├─plymouth-quit.service
    ├─system.slice
    ├─systemd-journald.socket
    ├─systemd-user-sessions.service
    └─basic.target
    [output truncated]
  • Check what services systemd orders to start after the specified service unit:

    # systemctl list-dependencies --before <name>.service

    For example, to view the list of services systemd orders to start after gdm, enter:

    # systemctl list-dependencies --before gdm.service
    gdm.service
    ├─dracut-shutdown.service
    ├─graphical.target
    │ ├─systemd-readahead-done.service
    │ ├─systemd-readahead-done.timer
    │ └─systemd-update-utmp-runlevel.service
    └─shutdown.target
      ├─systemd-reboot.service
      └─final.target
        └─systemd-reboot.service

Additional resources

12.2.3. Starting a system service

You can start system service in the current session by using the start command.

Prerequisites

  • Root access

Procedure

  • Start a system service in the current session:

    # systemctl start <name>.service

    Replace <name> with the name of the service unit you want to start (for example, httpd.service).

    Note

    In systemd, positive and negative dependencies between services exist. Starting a particular service may require starting one or more other services (positive dependency) or stopping one or more services (negative dependency).

    When you attempt to start a new service, systemd resolves all dependencies automatically, without explicit notification to the user. This means that if you are already running a service, and you attempt to start another service with a negative dependency, the first service is automatically stopped.

    For example, if you are running the postfix service, and you attempt to start the sendmail service, systemd first automatically stops postfix, because these two services are conflicting and cannot run on the same port.

Additional resources

12.2.4. Stopping a system service

If you want to stop a system service in the current session, use the stop command.

Prerequisites

  • Root access

Procedure

  • Stop a system service:

    # systemctl stop <name>.service

    Replace <name> with the name of the service unit you want to stop (for example, bluetooth).

Additional resources

12.2.5. Restarting a system service

You can restart system service in the current session using the restart command to perform the following actions:

  • Stop the selected service unit in the current session and immediately start it again.
  • Restart a service unit only if the corresponding service is already running.
  • Reload configuration of a system service without interrupting its execution.

Prerequisites

  • Root access

Procedure

  • Restart a system service:

    # systemctl restart <name>.service

    Replace <name> with the name of the service unit you want to restart (for example, httpd).

    Note

    If the selected service unit is not running, this command starts it too.

  • Optional: Restart a service unit only if the corresponding service is already running:

    # systemctl try-restart <name>.service
  • Optional: Reload the configuration without interrupting service execution:

    # systemctl reload <name>.service
    Note

    System services that do not support this feature, ignore this command. To restart such services, use the reload-or-restart and reload-or-try-restart commands instead.

Additional resources

12.2.6. Enabling a system service to start at boot

You can enable a service to start automatically at boot, these changes apply with the next reboot.

Prerequisites

  • Root access
  • The service you want to enable must not be masked. If you have a masked service, unmask it first:

    # systemctl unmask <name>.service

Procedure

  • Enable a service to start at boot:

    # systemctl enable <name>.service

    Replace <name> with the name of the service unit you want to enable (for example, httpd).

  • Optional: You can also enable and start a service by using a single command:

    # systemctl enable --now <name>.service

Additional resources

12.2.7. Disabling a system service to start at boot

You can prevent a service unit from starting automatically at boot time. If you disable a service, it will not start at boot, but you can start it manually. You can also mask a service, so that it cannot be started manually. Masking is a way of disabling a service that makes the service permanently unusable until it is unmasked again.

Prerequisites

  • Root access

Procedure

  • Disable a service to start at boot:

    # systemctl disable <name>.service

    Replace <name> with the name of the service unit you want to disable (for example, bluetooth).

  • Optional: If you want to make a service permanently unusable, mask the service:

    # systemctl mask <name>.service

    This command replaces the /etc/systemd/system/name.service file with a symbolic link to /dev/null, rendering the actual unit file inaccessible to systemd.

Additional resources

12.3. Booting into a target system state

As a system administrator, you can control the boot process of your system, and define the state you want your system to boot into. This is called a systemd target, and it is a set of systemd units that your system starts to reach a certain level of functionality. While working with systemd targets, you can view the default target, select a target at runtime, change the default boot target, boot into emergency or rescue target.

12.3.1. Target unit files

Targets in systemd are groups of related units that act as synchronization points during the start of your system. Target unit files, which end with the .target file extension, represent the systemd targets. The purpose of target units is to group together various systemd units through a chain of dependencies.

Consider the following examples:

  • The graphical.target unit for starting a graphical session, starts system services such as the GNOME Display Manager (gdm.service) or Accounts Service (accounts-daemon.service), and also activates the multi-user.target unit.
  • Similarly, the multi-user.target unit starts other essential system services such as NetworkManager (NetworkManager.service) or D-Bus (dbus.service) and activates another target unit named basic.target.

You can set the following systemd targets as default or current targets:

Table 12.3. Common systemd targets

rescue

unit target that pulls in the base system and spawns a rescue shell

multi-user

unit target for setting up a multi-user system

graphical

unit target for setting up a graphical login screen

emergency

unit target that starts an emergency shell on the main console

Additional resources

  • systemd.special(7) and systemd.target(5) man pages on your system

12.3.2. Changing the default target to boot into

When a system starts, systemd activates the default.target symbolic link, which points to the true target unit. You can find the currently selected default target unit in the /etc/systemd/system/default.target file. Each target represents a certain level of functionality and is used for grouping other units. Additionally, target units serve as synchronization points during boot. You can change the default target your system boots into. When you set a default target unit, the current target remains unchanged until the next reboot.

Prerequisites

  • Root access

Procedure

  1. Determine the current default target unit systemd uses to start the system:

    # systemctl get-default
    graphical.target
  2. List the currently loaded targets:

    # systemctl list-units --type target
  3. Configure the system to use a different target unit by default:

    # systemctl set-default <name>.target

    Replace <name> with the name of the target unit you want to use by default.

    Example:
    # systemctl set-default multi-user.target
    Removed /etc/systemd/system/default.target
    Created symlink /etc/systemd/system/default.target -> /usr/lib/systemd/system/multi-user.target
  4. Verify the default target unit:

    # systemctl get-default
    multi-user.target
  5. Apply the changes by rebooting:

    # reboot

Additional resources

  • systemctl(1), systemd.special(7), and bootup(7) man pages on your system

12.3.3. Changing the current target

On a running system, you can change the target unit in the current boot without reboot. If you switch to a different target, systemd starts all services and their dependencies that this target requires, and stops all services that the new target does not enable. Isolating a different target affects only the current boot.

Procedure

  1. Optional: Determine the current target:

    # systemctl get-default
    graphical.target
  2. Optional: Display the list of targets you can select:

    # systemctl list-units --type target
    Note

    You can only isolate targets that have the AllowIsolate=yes option set in the unit files.

  3. Change to a different target unit in the current boot:

    # systemctl isolate <name>.target

    Replace <name> with the name of the target unit you want to use in the current boot.

    Example:
    # systemctl isolate multi-user.target

    This command starts the target unit named multi-user and all dependent units, and immediately stops all other unit.

Additional resources

  • systemctl(1) man page on your system

12.3.4. Booting to rescue mode

You can boot to the rescue mode that provides a single-user environment for troubleshooting or repair if the system cannot get to a later target, and the regular booting process fails. In rescue mode, the system attempts to mount all local file systems and start certain important system services, but it does not activate network interfaces.

Prerequisites

  • Root access

Procedure

  • To enter the rescue mode, change the current target in the current session:

    # systemctl rescue
    
    Broadcast message from root@localhost on pts/0 (Fri 2023-03-24 18:23:15 CEST):
    
    The system is going down to rescue mode NOW!
    Note

    This command is similar to systemctl isolate rescue.target, but it also sends an informative message to all users that are currently logged into the system.

    To prevent systemd from sending a message, enter the following command with the --no-wall command-line option:

    # systemctl --no-wall rescue

Troubleshooting steps

If your system is not able to enter the rescue mode, you can boot to emergency mode, which provides the most minimal environment possible. In emergency mode, the system mounts the root file system only for reading, does not attempt to mount any other local file systems, does not activate network interfaces, and only starts a few essential services.

12.3.5. Troubleshooting the boot process

As a system administrator, you can select a non-default target at boot time to troubleshoot the boot process. Changing the target at boot time affects only a single boot. You can boot to emergency mode, which provides the most minimal environment possible.

Procedure

  1. Reboot the system, and interrupt the boot loader menu countdown by pressing any key except the Enter key, which would initiate a normal boot.
  2. Move the cursor to the kernel entry that you want to start.
  3. Press the E key to edit the current entry.
  4. Move to the end of the line that starts with linux and press Ctrl+E to jump to the end of the line:

    linux ($root)/vmlinuz-5.14.0-70.22.1.e19_0.x86_64 root=/dev/mapper/rhel-root ro crash\
    kernel=auto resume=/dev/mapper/rhel-swap rd.lvm.lv/swap rhgb quiet
  5. To choose an alternate boot target, append the systemd.unit= parameter to the end of the line that starts with linux:

    linux ($root)/vmlinuz-5.14.0-70.22.1.e19_0.x86_64 root=/dev/mapper/rhel-root ro crash\
    kernel=auto resume=/dev/mapper/rhel-swap rd.lvm.lv/swap rhgb quiet systemd.unit=<name>.target

    Replace <name> with the name of the target unit you want to use. For example, systemd.unit=emergency.target

  6. Press Ctrl+X to boot with these settings.

12.4. Shutting down, suspending, and hibernating the system

As a system administrator, you can use different power management options to manage power consumption, perform a proper shutdown to ensure that all data is saved, or restart the system to apply changes and updates.

12.4.1. System shutdown

To shut down the system, you can either use the systemctl utility directly, or call this utility through the shutdown command.

Using the shutdown has the following advantages:

  • You can schedule a shutdown by using the time argument. This also gives users warning that a system shutdown has been scheduled.
  • You can cancel the shutdown.

12.4.2. Scheduling a system shutdown

As a system administrator, you can schedule a delayed shutdown to give users time to save their work and log off the system. Use the shutdown command to perform the following operations:

  • Shut down the system and power off the machine at a certain time
  • Shut down and halt the system without powering off the machine
  • Cancel a pending shutdown

Prerequisites

  • Root access

Procedure

Use the shutdown command to perform any of the following tasks:

  • Specify the time at which you want to shut down the system and power off the machine:

    # shutdown --poweroff hh:mm

    Where hh:mm is the time in the 24-hour time notation. To prevent new logins, the /run/nologin file is created 5 minutes before system shutdown.

    When you use the time argument, you can notify users logged in to the system of the planned shutdown by specifying an optional wall message, for example shutdown --poweroff 13:59 "Attention. The system will shut down at 13:59".

  • Shut down and halt the system after a delay, without powering off the machine:

    # shutdown --halt +m

    Where +m is the delay time in minutes. You can use the now keyword as an alias for +0.

  • Cancel a pending shutdown:

    # shutdown -c

Additional resources

12.4.3. Shutting down the system using the systemctl command

As a system administrator, you can shut down the system and power off the machine or shut down and halt the system without powering off the machine by using the systemctl command.

Prerequisites

  • Root access

Procedure

Use the systemctl command to perform any of the following tasks:

  • Shut down the system and power off the machine:

    # systemctl poweroff
  • Shut down and halt the system without powering off the machine:

    # systemctl halt
Note

By default, running either of these commands causes systemd to send an informative message to all users that are currently logged into the system. To prevent systemd from sending this message, run the selected command with the --no-wall command line option.

12.4.4. Restarting the system

When you restart the system, systemd stops all running programs and services, the system shuts down, and then immediately starts again. Restarting the system can be helpful in the following situations:

  • After installing new software or updates
  • After making changes to system settings
  • When troubleshooting system issues

Prerequisites

  • Root access

Procedure

  • Restart the system:

    # systemctl reboot
Note

By default, when you use this command, systemd sends an informative message to all users that are currently logged into the system. To prevent systemd from sending this message, run this command with the --no-wall option.

12.4.5. Optimizing power consumption by suspending and hibernating the system

As a system administrator, you can manage power consumption, save energy on your systems, and preserve the current state of your system. To do so, apply one of the following modes:

Suspend
Suspending saves the system state in RAM and with the exception of the RAM module, powers off most of the devices in the machine. When you turn the machine back on, the system then restores its state from RAM without having to boot again. Because the system state is saved in RAM and not on the hard disk, restoring the system from suspend mode is significantly faster than from hibernation. However, the suspended system state is also vulnerable to power outages.
Hibernate
Hibernating saves the system state on the hard disk drive and powers off the machine. When you turn the machine back on, the system then restores its state from the saved data without having to boot again. Because the system state is saved on the hard disk and not in RAM, the machine does not have to maintain electrical power to the RAM module. However, as a consequence, restoring the system from hibernation is significantly slower than restoring it from suspend mode.
Hybrid sleep
This combines elements of both hibernation and suspending. The system first saves the current state on the the hard disk drive, and enters a low-power state similar to suspending, which allows the system to resume more quickly. The benefit of hybrid sleep is that if the system loses power during the sleep state, it can still recover the previous state from the saved image on the hard disk, similar to hibernation.
Suspend-then-hibernate
This mode first suspends the system, which results in saving the current system state to RAM and putting the system in a low-power mode. The system hibernates if it remains suspended for a specific period of time that you can define in the HibernateDelaySec parameter. Hibernation saves the system state to the hard disk drive and shuts down the system completely. The suspend-then-hibernate mode provides the benefit of conserving battery power while you are still able to quickly resume work. Additionally, this mode ensures that your data is saved in case of a power failure.

Prerequisites

  • Root access

Procedure

Choose the appropriate method for power saving:

  • Suspend the system:

    # systemctl suspend
  • Hibernate the system:

    # systemctl hibernate
  • Hibernate and suspend the system:

    # systemctl hybrid-sleep
  • Suspend and then hibernate the system:

    # systemctl suspend-then-hibernate

12.4.6. Overview of the power management commands with systemctl

You can use the following list of the systemctl commands to control the power management of your system.

Table 12.4. Overview of the systemctl power management commands
systemctl commandDescription

systemctl halt

Halts the system.

systemctl poweroff

Powers off the system.

systemctl reboot

Restarts the system.

systemctl suspend

Suspends the system.

systemctl hibernate

Hibernates the system.

systemctl hybrid-sleep

Hibernates and suspends the system.

12.4.7. Changing the power button behavior

When you press the power button on your computer, it suspends or shuts down the system by default. You can customize this behavior according to your preferences.

12.4.7.1. Changing the power button behavior in systemd

When you press the power button in a non-graphical systemd target, it shuts down the system by default. You can customize this behavior according to your preferences.

Prerequisites

  • Administrative access.

Procedure

  1. Open the /etc/systemd/logind.conf configuration file.
  2. Look for the line that says HandlePowerKey=poweroff.
  3. If the line starts with the # symbol, remove it to enable the setting.
  4. Replace poweroff with one of the following options:

    poweroff
    Shut down the computer.
    reboot
    Reboot the system.
    halt
    Initiate a system halt.
    kexec
    Initiate a kexec reboot.
    suspend
    Suspend the system.
    hibernate
    Initiate system hibernation.
    ignore
    Do nothing.

    For example, to reboot the system upon pressing the power button, use this setting:

    HandlePowerKey=reboot
  5. Save your changes and close the editor.

Next steps

12.4.7.2. Changing the power button behavior in GNOME

On the graphical login screen or in the graphical user session, pressing the power button suspends the machine by default. This happens both in cases when the user presses the power button physically or when pressing a virtual power button from a remote console. You can select a different power button behavior.

Prerequisites

Procedure

  1. Create a local database for system-wide settings in the /etc/dconf/db/local.d/01-power file. Enter the following content:

    [org/gnome/settings-daemon/plugins/power]
    power-button-action='suspend'

    Replace suspend with any of the following power button actions:

    nothing
    Does nothing .
    suspend
    Suspends the system.
    hibernate
    Hibernates the system.
    interactive

    Shows a pop-up query asking the user what to do.

    With interactive mode, the system powers off automatically after 60 seconds when pressing the power button. However, you can choose a different behavior from the pop-up query.

  2. Optional: Override the user’s setting, and prevent the user from changing it. Enter the following configuration in the /etc/dconf/db/local.d/locks/01-power file:

    /org/gnome/settings-daemon/plugins/power/power-button-action
  3. Update the system databases:

    # dconf update
  4. Log out and back in again for the system-wide settings to take effect.
Red Hat logoGithubRedditYoutubeTwitter

Formazione

Prova, acquista e vendi

Community

Informazioni sulla documentazione di Red Hat

Aiutiamo gli utenti Red Hat a innovarsi e raggiungere i propri obiettivi con i nostri prodotti e servizi grazie a contenuti di cui possono fidarsi.

Rendiamo l’open source più inclusivo

Red Hat si impegna a sostituire il linguaggio problematico nel codice, nella documentazione e nelle proprietà web. Per maggiori dettagli, visita ilBlog di Red Hat.

Informazioni su Red Hat

Forniamo soluzioni consolidate che rendono più semplice per le aziende lavorare su piattaforme e ambienti diversi, dal datacenter centrale all'edge della rete.

© 2024 Red Hat, Inc.