Menu Close
Settings Close

Language and Page Formatting Options

Red Hat Training

A Red Hat training course is available for RHEL 8

Chapter 17. Working with systemd unit files

This chapter includes the description of systemd unit files. The following sections show you how to:

  • Create custom unit files
  • Convert SysV init scripts to unit files
  • Modify existing unit files
  • Work with instantiated units

17.1. Introduction to unit files

A unit file contains configuration directives that describe the unit and define its behavior. Several systemctl commands work with unit files in the background. To make finer adjustments, system administrator must edit or create unit files manually. systemd unit files locations lists three main directories where unit files are stored on the system, the /etc/systemd/system/ directory is reserved for unit files created or customized by the system administrator.

Unit file names take the following form:


Here, unit_name stands for the name of the unit and type_extension identifies the unit type. For a complete list of unit types, see systemd unit files

For example, there usually is sshd.service as well as sshd.socket unit present on your system.

Unit files can be supplemented with a directory for additional configuration files. For example, to add custom configuration options to sshd.service, create the sshd.service.d/custom.conf file and insert additional directives there. For more information on configuration directories, see Modifying existing unit files.

Also, the sshd.service.wants/ and sshd.service.requires/ directories can be created. These directories contain symbolic links to unit files that are dependencies of the sshd service. The symbolic links are automatically created either during installation according to [Install] unit file options or at runtime based on [Unit] options. It is also possible to create these directories and symbolic links manually. For more details on [Install] and [Unit] options, see the tables below.

Many unit file options can be set using the so called unit specifiers – wildcard strings that are dynamically replaced with unit parameters when the unit file is loaded. This enables creation of generic unit files that serve as templates for generating instantiated units. See Working with instantiated units.

17.2. Unit file structure

Unit files typically consist of three sections:

  • The [Unit] section — contains generic options that are not dependent on the type of the unit. These options provide unit description, specify the unit’s behavior, and set dependencies to other units. For a list of most frequently used [Unit] options, see Important [Unit] section options.
  • The [Unit type] section — if a unit has type-specific directives, these are grouped under a section named after the unit type. For example, service unit files contain the [Service] section.
  • The [Install] section — contains information about unit installation used by systemctl enable and disable commands. For a list of options for the [Install] section, see Important [Install] section options.

17.3. Important [Unit] section options

The following tables lists important options of the [Unit] section.

Table 17.1. Important [Unit] section options

Option [a]Description


A meaningful description of the unit. This text is displayed for example in the output of the systemctl status command.


Provides a list of URIs referencing documentation for the unit.


Defines the order in which units are started. The unit starts only after the units specified in After are active. Unlike Requires, After does not explicitly activate the specified units. The Before option has the opposite functionality to After.


Configures dependencies on other units. The units listed in Requires are activated together with the unit. If any of the required units fail to start, the unit is not activated.


Configures weaker dependencies than Requires. If any of the listed units does not start successfully, it has no impact on the unit activation. This is the recommended way to establish custom unit dependencies.


Configures negative dependencies, an opposite to Requires.

[a] For a complete list of options configurable in the [Unit] section, see the systemd.unit(5) manual page.
[b] In most cases, it is sufficient to set only the ordering dependencies with After and Before unit file options. If you also set a requirement dependency with Wants (recommended) or Requires, the ordering dependency still needs to be specified. That is because ordering and requirement dependencies work independently from each other.

17.4. Important [Service] section options

The following tables lists important options of the [Service] section.

Table 17.2. Important [Service] section options

Option [a]Description


Configures the unit process startup type that affects the functionality of ExecStart and related options. One of:

* simple – The default value. The process started with ExecStart is the main process of the service.

* forking – The process started with ExecStart spawns a child process that becomes the main process of the service. The parent process exits when the startup is complete.

* oneshot – This type is similar to simple, but the process exits before starting consequent units.

* dbus – This type is similar to simple, but consequent units are started only after the main process gains a D-Bus name.

* notify – This type is similar to simple, but consequent units are started only after a notification message is sent via the sd_notify() function.

* idle – similar to simple, the actual execution of the service binary is delayed until all jobs are finished, which avoids mixing the status output with shell output of services.


Specifies commands or scripts to be executed when the unit is started. ExecStartPre and ExecStartPost specify custom commands to be executed before and after ExecStart. Type=oneshot enables specifying multiple custom commands that are then executed sequentially.


Specifies commands or scripts to be executed when the unit is stopped.


Specifies commands or scripts to be executed when the unit is reloaded.


With this option enabled, the service is restarted after its process exits, with the exception of a clean stop by the systemctl command.


If set to True, the service is considered active even when all its processes exited. Default value is False. This option is especially useful if Type=oneshot is configured.

[a] For a complete list of options configurable in the [Service] section, see the systemd.service(5) manual page.

17.5. Important [Install] section options

The following tables lists important options of the [Install] section.

Table 17.3. Important [Install] section options

Option [a]Description


Provides a space-separated list of additional names for the unit. Most systemctl commands, excluding systemctl enable, can use aliases instead of the actual unit name.


A list of units that depend on the unit. When this unit is enabled, the units listed in RequiredBy gain a Require dependency on the unit.


A list of units that weakly depend on the unit. When this unit is enabled, the units listed in WantedBy gain a Want dependency on the unit.


Specifies a list of units to be installed or uninstalled along with the unit.


Limited to instantiated units, this option specifies the default instance for which the unit is enabled. See Working with instantiated units.

[a] For a complete list of options configurable in the [Install] section, see the systemd.unit(5) manual page.

17.6. Creating custom unit files

There are several use cases for creating unit files from scratch: you could run a custom daemon, create a second instance of some existing service as in Creating a custom unit file by using the second instance of the sshd service

On the other hand, if you intend just to modify or extend the behavior of an existing unit, use the instructions from Modifying existing unit files.


The following procedure describes the general process of creating a custom service:

  1. Prepare the executable file with the custom service. This can be a custom-created script, or an executable delivered by a software provider. If required, prepare a PID file to hold a constant PID for the main process of the custom service. It is also possible to include environment files to store shell variables for the service. Make sure the source script is executable (by executing the chmod a+x) and is not interactive.
  2. Create a unit file in the /etc/systemd/system/ directory and make sure it has correct file permissions. Execute as root:

    touch /etc/systemd/system/name.service
    chmod 664 /etc/systemd/system/name.service

    Replace name with a name of the service to be created. Note that file does not need to be executable.

  3. Open the name.service file created in the previous step, and add the service configuration options. There is a variety of options that can be used depending on the type of service you wish to create, see Unit file structure.

    The following is an example unit configuration for a network-related service:



    • service_description is an informative description that is displayed in journal log files and in the output of the systemctl status command.
    • the After setting ensures that the service is started only after the network is running. Add a space-separated list of other relevant services or targets.
    • path_to_executable stands for the path to the actual service executable.
    • Type=forking is used for daemons that make the fork system call. The main process of the service is created with the PID specified in path_to_pidfile. Find other startup types in Important [Service] section options.
    • WantedBy states the target or targets that the service should be started under. Think of these targets as of a replacement of the older concept of runlevels.
  4. Notify systemd that a new name.service file exists by executing the following command as root:

    systemctl daemon-reload
    systemctl start name.service

    Always run the systemctl daemon-reload command after creating new unit files or modifying existing unit files. Otherwise, the systemctl start or systemctl enable commands could fail due to a mismatch between states of systemd and actual service unit files on disk. Note, that on systems with a large number of units this can take a long time, as the state of each unit has to be serialized and subsequently deserialized during the reload.

17.7. Creating a custom unit file by using the second instance of the sshd service

System Administrators often need to configure and run multiple instances of a service. This is done by creating copies of the original service configuration files and modifying certain parameters to avoid conflicts with the primary instance of the service. The following procedure shows how to create a second instance of the sshd service.


  1. Create a copy of the sshd_config file that will be used by the second daemon:

    # cp /etc/ssh/sshd{,-second}_config
  2. Edit the sshd-second_config file created in the previous step to assign a different port number and PID file to the second daemon:

    Port 22220
    PidFile /var/run/

    See the sshd_config(5) manual page for more information on Port and PidFile options. Make sure the port you choose is not in use by any other service. The PID file does not have to exist before running the service, it is generated automatically on service start.

  3. Create a copy of the systemd unit file for the sshd service:

    # cp /usr/lib/systemd/system/sshd.service /etc/systemd/system/sshd-second.service
  4. Alter the sshd-second.service created in the previous step as follows:

    1. Modify the Description option:

      Description=OpenSSH server second instance daemon
    2. Add sshd.service to services specified in the After option, so that the second instance starts only after the first one has already started: auditd.service sshd.service
    3. The first instance of sshd includes key generation, therefore remove the ExecStartPre=/usr/sbin/sshd-keygen line.
    4. Add the -f /etc/ssh/sshd-second_config parameter to the sshd command, so that the alternative configuration file is used:

      ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config $OPTIONS
    5. After the above modifications, the sshd-second.service should look as follows:

      Description=OpenSSH server second instance daemon auditd.service sshd.service
      ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config $OPTIONS
      ExecReload=/bin/kill -HUP $MAINPID
  5. If using SELinux, add the port for the second instance of sshd to SSH ports, otherwise the second instance of sshd will be rejected to bind to the port:

    # semanage port -a -t ssh_port_t -p tcp 22220
  6. Enable sshd-second.service, so that it starts automatically upon boot:

    # systemctl enable sshd-second.service
  7. Verify if the sshd-second.service is running by using the systemctl status command.
  8. Verify if the port is enabled correctly by connecting to the service:

    ssh -p 22220 user@server

    If the firewall is in use, make sure that it is configured appropriately in order to allow connections to the second instance of sshd.

17.8. Converting SysV init scripts to unit files

Before taking time to convert a SysV init script to a unit file, make sure that the conversion was not already done elsewhere. All core services installed on Red Hat Enterprise Linux come with default unit files, and the same applies for many third-party software packages.

Converting an init script to a unit file requires analyzing the script and extracting the necessary information from it. Based on this data you can create a unit file. As init scripts can vary greatly depending on the type of the service, you might need to employ more configuration options for translation than outlined in this chapter. Note that some levels of customization that were available with init scripts are no longer supported by systemd units.

The majority of information needed for conversion is provided in the script’s header. The following example shows the opening section of the init script used to start the postfix service on Red Hat Enterprise Linux 6:

# postfix      Postfix Mail Transfer Agent
# chkconfig: 2345 80 30
# description: Postfix is a Mail Transport Agent, which is the program that moves mail from one machine to another.
# processname: master
# pidfile: /var/spool/postfix/pid/
# config: /etc/postfix/
# config: /etc/postfix/
# Provides: postfix MTA
# Required-Start: $local_fs $network $remote_fs
# Required-Stop: $local_fs $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop postfix
# Description: Postfix is a Mail Transport Agent, which is the program that moves mail from one machine to another.

In the above example, only lines starting with # chkconfig and # description are mandatory, so you might not find the rest in different init files. The text enclosed between the BEGIN INIT INFO and END INIT INFO lines is called Linux Standard Base (LSB) header. If specified, LSB headers contain directives defining the service description, dependencies, and default runlevels. What follows is an overview of analytic tasks aiming to collect the data needed for a new unit file. The postfix init script is used as an example.

17.9. Finding the systemd service description

You can find descriptive information about the script on the line starting with #description. Use this description together with the service name in the Description option in the [Unit] section of the unit file. The LSB header might contain similar data on the #Short-Description and #Description lines.

17.10. Finding the systemd service dependencies

The LSB header might contain several directives that form dependencies between services. Most of them are translatable to systemd unit options, see the following table:

Table 17.4. Dependency options from the LSB header

LSB OptionDescriptionUnit File Equivalent


Specifies the boot facility name of the service, that can be referenced in other init scripts (with the "$" prefix). This is no longer needed as unit files refer to other units by their file names.


Contains boot facility names of required services. This is translated as an ordering dependency, boot facility names are replaced with unit file names of corresponding services or targets they belong to. For example, in case of postfix, the Required-Start dependency on $network was translated to the After dependency on

After, Before


Constitutes weaker dependencies than Required-Start. Failed Should-Start dependencies do not affect the service startup.

After, Before

Required-Stop, Should-Stop

Constitute negative dependencies.


17.11. Finding default targets of the service

The line starting with #chkconfig contains three numerical values. The most important is the first number that represents the default runlevels in which the service is started. Map these runlevels to equivalent systemd targets. Then list these targets in the WantedBy option in the [Install] section of the unit file. For example, postfix was previously started in runlevels 2, 3, 4, and 5, which translates to and Note that the depends on, therefore it is not necessary to specify both. You might find information on default and forbidden runlevels also at #Default-Start and #Default-Stop lines in the LSB header.

The other two values specified on the #chkconfig line represent startup and shutdown priorities of the init script. These values are interpreted by systemd if it loads the init script, but there is no unit file equivalent.

17.12. Finding files used by the service

Init scripts require loading a function library from a dedicated directory and allow importing configuration, environment, and PID files. Environment variables are specified on the line starting with #config in the init script header, which translates to the EnvironmentFile unit file option. The PID file specified on the #pidfile init script line is imported to the unit file with the PIDFile option.

The key information that is not included in the init script header is the path to the service executable, and potentially some other files required by the service. In previous versions of Red Hat Enterprise Linux, init scripts used a Bash case statement to define the behavior of the service on default actions, such as start, stop, or restart, as well as custom-defined actions. The following excerpt from the postfix init script shows the block of code to be executed at service start.

conf_check() {
    [ -x /usr/sbin/postfix ] || exit 5
    [ -d /etc/postfix ] || exit 6
    [ -d /var/spool/postfix ] || exit 5

make_aliasesdb() {
	if [ "$(/usr/sbin/postconf -h alias_database)" == "hash:/etc/aliases" ]
		# /etc/aliases.db might be used by other MTA, make sure nothing
		# has touched it since our last newaliases call
		[ /etc/aliases -nt /etc/aliases.db ] ||
			[ "$ALIASESDB_STAMP" -nt /etc/aliases.db ] ||
			[ "$ALIASESDB_STAMP" -ot /etc/aliases.db ] || return
		touch -r /etc/aliases.db "$ALIASESDB_STAMP"

start() {
	[ "$EUID" != "0" ] && exit 4
	# Check that networking is up.
	[ ${NETWORKING} = "no" ] && exit 1
	# Start daemons.
	echo -n $"Starting postfix: "
	make_aliasesdb >/dev/null 2>&1
	/usr/sbin/postfix start 2>/dev/null 1>&2 && success || failure $"$prog start"
	[ $RETVAL -eq 0 ] && touch $lockfile
	return $RETVAL

The extensibility of the init script allowed specifying two custom functions, conf_check() and make_aliasesdb(), that are called from the start() function block. On closer look, several external files and directories are mentioned in the above code: the main service executable /usr/sbin/postfix, the /etc/postfix/ and /var/spool/postfix/ configuration directories, as well as the /usr/sbin/postconf/ directory.

systemd supports only the predefined actions, but enables executing custom executables with ExecStart, ExecStartPre, ExecStartPost, ExecStop, and ExecReload options. The /usr/sbin/postfix together with supporting scripts are executed on service start. Converting complex init scripts requires understanding the purpose of every statement in the script. Some of the statements are specific to the operating system version, therefore you do not need to translate them. On the other hand, some adjustments might be needed in the new environment, both in unit file as well as in the service executable and supporting files.

17.13. Modifying existing unit files

Services installed on the system come with default unit files that are stored in the /usr/lib/systemd/system/ directory. System Administrators should not modify these files directly, therefore any customization must be confined to configuration files in the /etc/systemd/system/ directory.


  1. Depending on the extent of the required changes, pick one of the following approaches:

    • Create a directory for supplementary configuration files at /etc/systemd/system/unit.d/. This method is recommended for most use cases. It enables extending the default configuration with additional functionality, while still referring to the original unit file. Changes to the default unit introduced with a package upgrade are therefore applied automatically. See Extending the default unit configuration for more information.
    • Create a copy of the original unit file /usr/lib/systemd/system/ in /etc/systemd/system/ and make changes there. The copy overrides the original file, therefore changes introduced with the package update are not applied. This method is useful for making significant unit changes that should persist regardless of package updates. See Overriding the default unit configuration for details.
  2. To return to the default configuration of the unit, delete custom-created configuration files in /etc/systemd/system/.
  3. To apply changes to unit files without rebooting the system, execute:

    systemctl daemon-reload

    The daemon-reload option reloads all unit files and recreates the entire dependency tree, which is needed to immediately apply any change to a unit file. As an alternative, you can achieve the same result with the following command, which must be executed under the root user:

    init q
  4. If the modified unit file belongs to a running service, this service must be restarted to accept new settings:

    systemctl restart name.service

To modify properties, such as dependencies or timeouts, of a service that is handled by a SysV initscript, do not modify the initscript itself. Instead, create a systemd drop-in configuration file for the service as described in: Extending the default unit configuration and Overriding the default unit configuration.

Then manage this service in the same way as a normal systemd service.

For example, to extend the configuration of the network service, do not modify the /etc/rc.d/init.d/network initscript file. Instead, create new directory /etc/systemd/system/network.service.d/ and a systemd drop-in file /etc/systemd/system/network.service.d/my_config.conf. Then, put the modified values into the drop-in file. Note: systemd knows the network service as network.service, which is why the created directory must be called network.service.d

17.14. Extending the default unit configuration

This section describes how to extend the default unit file with additional configuration options.


  1. To extend the default unit file with additional configuration options, first create a configuration directory in /etc/systemd/system/. If extending a service unit, execute the following command as root:

    mkdir /etc/systemd/system/name.service.d/

    Replace name with the name of the service you want to extend. The above syntax applies to all unit types.

  2. Create a configuration file in the directory made in the previous step. Note that the file name must end with the .conf suffix. Type:

    touch /etc/systemd/system/name.service.d/config_name.conf

    Replace config_name with the name of the configuration file. This file adheres to the normal unit file structure, therefore all directives must be specified under appropriate sections, see Unit file structure.

    For example, to add a custom dependency, create a configuration file with the following content:


    Where new_dependency stands for the unit to be marked as a dependency. Another example is a configuration file that restarts the service after its main process exited, with a delay of 30 seconds:


    It is recommended to create small configuration files focused only on one task. Such files can be easily moved or linked to configuration directories of other services.

  3. To apply changes made to the unit, execute as root:

    systemctl daemon-reload
    systemctl restart name.service

Example 17.1. Extending the httpd.service configuration

To modify the httpd.service unit so that a custom shell script is automatically executed when starting the Apache service, perform the following steps.

  1. Create a directory and a custom configuration file:

    # mkdir /etc/systemd/system/httpd.service.d/
    # touch /etc/systemd/system/httpd.service.d/custom_script.conf
  2. Provided that the script you want to start automatically with Apache is located at /usr/local/bin/, insert the following text to the custom_script.conf file:

  3. To apply the unit changes, execute:

    # systemctl daemon-reload
    # systemctl restart httpd.service

The configuration files from configuration directories in /etc/systemd/system/ take precedence over unit files in /usr/lib/systemd/system/. Therefore, if the configuration files contain an option that can be specified only once, such as Description or ExecStart, the default value of this option is overridden. Note that in the output of the systemd-delta command, described in Monitoring overridden units ,such units are always marked as [EXTENDED], even though in sum, certain options are actually overridden.

17.15. Overriding the default unit configuration

This section describes how to override the default unit configuration.


  1. To make changes that will persist after updating the package that provides the unit file, first copy the file to the /etc/systemd/system/ directory. To do so, execute the following command as root:

    cp /usr/lib/systemd/system/name.service /etc/systemd/system/name.service

    Where name stands for the name of the service unit you wish to modify. The above syntax applies to all unit types.

  2. Open the copied file with a text editor, and make the desired changes. To apply the unit changes, execute as root:

    systemctl daemon-reload
    systemctl restart name.service

17.16. Changing the timeout limit

You can specify a timeout value per service to prevent a malfunctioning service from freezing the system. Otherwise, timeout is set by default to 90 seconds for normal services and to 300 seconds for SysV-compatible services.

For example, to extend timeout limit for the httpd service:


  1. Copy the httpd unit file to the /etc/systemd/system/ directory:

    cp /usr/lib/systemd/system/httpd.service /etc/systemd/system/httpd.service
  2. Open file /etc/systemd/system/httpd.service and specify the TimeoutStartUSec value in the [Service] section:

  3. Reload the systemd daemon:

    systemctl daemon-reload
  4. Optional. Verify the new timeout value:

    systemctl show httpd -p TimeoutStartUSec

    To change the timeout limit globally, input the DefaultTimeoutStartSec in the /etc/systemd/system.conf file.

17.17. Monitoring overridden units

This section describes how to display an overview of overridden or modified unit files.


  • To display an overview of overridden or modified unit files, use the following command:


    For example, the output of the above command can look as follows:

    [EQUIVALENT] /etc/systemd/system/ → /usr/lib/systemd/system/
    [OVERRIDDEN] /etc/systemd/system/autofs.service → /usr/lib/systemd/system/autofs.service
    --- /usr/lib/systemd/system/autofs.service      2014-10-16 21:30:39.000000000 -0400
    + /etc/systemd/system/autofs.service  2014-11-21 10:00:58.513568275 -0500
    @@ -8,7 +8,8 @@
     ExecStart=/usr/sbin/automount $OPTIONS --pid-file /run/
     ExecReload=/usr/bin/kill -HUP $MAINPID
    [MASKED]     /etc/systemd/system/cups.service → /usr/lib/systemd/system/cups.service
    [EXTENDED]   /usr/lib/systemd/system/sssd.service → /etc/systemd/system/sssd.service.d/journal.conf
    4 overridden configuration files found.

17.18. Working with instantiated units

It is possible to instantiate multiple units from a single template configuration file at runtime. The "@" character is used to mark the template and to associate units with it. Instantiated units can be started from another unit file (using Requires or Wants options), or with the systemctl start command. Instantiated service units are named the following way:


Where template_name stands for the name of the template configuration file. Replace instance_name with the name for the unit instance. Several instances can point to the same template file with configuration options common for all instances of the unit. Template unit name has the form of:


For example, the following Wants setting in a unit file:

Wants=getty@ttyA.service getty@ttyB.service

first makes systemd search for given service units. If no such units are found, the part between "@" and the type suffix is ignored and systemd searches for the getty@.service file, reads the configuration from it, and starts the services.

For example, the getty@.service template contains the following directives:

Description=Getty on %I
ExecStart=-/sbin/agetty --noclear %I $TERM

When the getty@ttyA.service and getty@ttyB.service are instantiated from the above template, Description= is resolved as Getty on ttyA and Getty on ttyB.

17.19. Important unit specifiers

Wildcard characters, called unit specifiers, can be used in any unit configuration file. Unit specifiers substitute certain unit parameters and are interpreted at runtime. The following table lists unit specifiers that are particularly useful for template units.

Table 17.5. Important unit specifiers

Unit SpecifierMeaningDescription


Full unit name

Stands for the full unit name including the type suffix. %N has the same meaning but also replaces the forbidden characters with ASCII codes.


Prefix name

Stands for a unit name with type suffix removed. For instantiated units %p stands for the part of the unit name before the "@" character.


Instance name

Is the part of the instantiated unit name between the "@" character and the type suffix. %I has the same meaning but also replaces the forbidden characters for ASCII codes.


Host name

Stands for the hostname of the running system at the point in time the unit configuration is loaded.


Runtime directory

Represents the runtime directory, which is either /run for the root user, or the value of the XDG_RUNTIME_DIR variable for unprivileged users.

For a complete list of unit specifiers, see the systemd.unit(5) manual page.

17.20. Additional resources