Creating and modifying SYSTEMd unit files in Linux systems

Time:2021-10-18

(1) Unit file overview

The unit file contains the instructions and behavior information of the unit. In the background, the systemctl command works with the unit file. In order to do the job well and correctly, the system administrator must be able to edit the unit file manually. The unit files manually created by the general system administrator are recommended to be stored under the / etc / SYSTEMd / system / directory.
The format of the cell configuration file is:

Copy code

The code is as follows:

unit_name.type_extension

 

Unit here_ Name stands for unit name, type_ Extension represents the unit type.
The unit file can be placed under a directory as an additional file. For example, in order to customize the sshd.service service, you can create the sshd.service.d/custom.conf file and make some customized configurations in the file.
Similarly, you can create the sshd. Service. Wants / and sshd. Service. Requirements / directories. These directories contain the soft connections of sshd services and associated services. These soft connections can be created automatically or manually during system installation.
Many cell configuration files can use cell specifiers — wildcard strings, which can be dynamically replaced by variables when the cell file is booted. This makes it possible to create some common unit configuration templates.

(2) Understand unit file structure

A typical unit file consists of three sections:
The [unit] section contains general options that do not depend on the unit type. These options provide the unit description, know the unit behavior, and configure the dependencies of the unit and other units.
[unittype] section. If the unit has specific type instructions, these instructions are organized together in the unittype section. For example, the service unit file contains the [service] section, which contains frequently used service configurations.
The [install] section contains the installation information of the systemctlable or disable command.
1) [unit] excerpt
The description unit describes the information. These text information will be output in the systemclstatus command.
The URLs of the documentation unit document information.
The after definition starts after those units. This unit only starts after the specified unit starts. Unlike the requires option, the after option does not explicitly activate a specific unit, and the before option has the opposite function.
The dependency of the requires configuration unit. The units in the requires option need to be activated together. If one unit fails to start, the other units will not be started.
Wants is much less dependent than the requires option. If the unit in the list fails to start, it will not affect other units. This is the recommended way to establish user-defined unit dependencies.
Conflicts defines the unit conflict relationship, which is opposite to requirements.
2) Options when the [unittype] type is [service]
The type of the hive process at startup affects the function of executing and associating options. The optional keywords are:
The default value of simple is to start the process together with the main process of the service;
The forking process starts as a child process of the main service process, and the parent process exits after it is fully started.
Oneshot is similar to simple, but the process exits after starting the unit.
DBUS is similar to simple, but only the main process gets the D-Bus name after the unit is started.
Notify is similar to simple, but after the unit is started, a main message is sent to SD_ The notify() function sends.
Similar to simple, the binary program that actually executes the process will be delayed until the tasks of all units are completed, mainly to avoid mixed output of service state and shell.
Execstart specifies the command or script to start the unit. The execstartpre and execstartpost sections specify the user-defined script to be executed before or after execstart. Type = oneshot allows you to specify multiple user-defined commands that you want to execute sequentially.
Execstop specifies the command or script to execute when the cell stops.
Execreload specifies whether the unit reload is a command or script to execute.
If the restart option is allowed, the process will exit when the service is restarted, and the clear and restart operation will be performed through the systemctl command.
Remainafterexit if this option is set to true, the service will be considered active. Even if all processes have exited, the default value is false. This option needs to be configured only when type = oneshot.
3) [install] excerpt
Alias provides a spatially separated additional name for the cell.
The requiredby unit is allowed to run a series of required dependent units. The requiredby list obtains the dependency information from require.
Wantby units are allowed to run the required weak dependency units, and wantby obtains dependency information from the want list.
Also indicates the unit installed with or assisted by the unit.
Defaultinstance is the limit of the instance unit. This option specifies if the unit is allowed to run the default instance.
4) An example of postfix service:
The unit file is located in / usr / lib / SYSTEMd / system / postfix.service. The contents are as follows:

Copy code

The code is as follows:

[Unit]
Description=PostfixMailTransportAgent
After=syslog.targetnetwork.target
Conflicts=sendmail.serviceexim.service
[Service]
Type=forking
PIDFile=/var/spool/postfix/pid/master.pid
EnvironmentFile=-/etc/sysconfig/network
ExecStartPre=-/usr/libexec/postfix/aliasesdb
ExecStartPre=-/usr/libexec/postfix/chroot-update
ExecStart=/usr/sbin/postfixstart
ExecReload=/usr/sbin/postfixreload
ExecStop=/usr/sbin/postfixstop
[Install]
WantedBy=multi-user.target

 

(3) Create a custom cell file

The following scenarios require customization unit files:
Want to create your own daemon;
Create a second instance of the existing service;
Introduce SYSV init script.
On the other hand, it is sometimes necessary to modify the existing unit file.
The following describes the steps to create a unit file:
1) Prepare the execution file of the custom service.
The executable file can be a script or a program of the software provider. If necessary, prepare a PID file for the main process of the custom service to ensure that the PID remains unchanged. In addition, you may need a script to configure environment variables to ensure that all scripts have executable properties and do not need interaction.
2) Create a unit file in the / etc / SYSTEMd / system / directory and ensure that it can only be edited by root:

Copy code

The code is as follows:

touch/etc/systemd/system/name.servicechmod664/etc/systemd/system/name.service

 

The file does not require execution permission.
3) Open the name.service file and add service configuration. How to configure various variables depends on the added service type. The following is a configuration example that depends on network services:

Copy code

The code is as follows:

[Unit]
Description=service_description
After=network.target
[Service]
ExecStart=path_to_executable
Type=forking
PIDFile=path_to_pidfile
[Install]
WantedBy=default.target

 

4) Notifies SYSTEMd that a new service has been added:

Copy code

The code is as follows:

systemctldaemon-reload
systemctlstartname.service

 

(4) Create emacs.service example:

1) Create the file and ensure the correct permissions:
 

Copy code

The code is as follows:

~]#touch/etc/systemd/system/emacs.service
~]#chmod664/etc/systemd/system/emacs.service

 

2) Add configuration information:
 

Copy code

The code is as follows:

[Unit]
Description=Emacs:theextensible,self-documentingtexteditor
[Service]
Type=forking
ExecStart=/usr/bin/emacs–daemon
ExecStop=/usr/bin/emacsclient–eval”(kill-emacs)”
Environment=SSH_AUTH_SOCK=%t/keyring/ssh
Restart=always
[Install]
WantedBy=default.target

 

3) Notify SYSTEMd and start the service:
 

Copy code

The code is as follows:

~]#systemctldaemon-reload
~]#systemctlstartemacs.service

 

(5) Example of creating a second sshd service

1) Copy sshd_ Config file
 

Copy code

The code is as follows:

]#cp/etc/ssh/sshd{,-second}_config

 

2) Edit sshd second_ Config file, add 22220 port and PID file:
 

Copy code

The code is as follows:

Port22220
PidFile/var/run/sshd-second.pid

 

If you need to modify other parameters, please read the help.
3) Copy unit file:
 

Copy code

The code is as follows:

~]#cp/usr/lib/systemd/system/sshd{,-second}.service

 

4) Edit the cell file sshd-second.service
Modify description field

Copy code

The code is as follows:

Description=OpenSSHserversecondinstancedaemon

 
Add the sshd.service service after the after keyword:

Copy code

The code is as follows:

After=syslog.targetnetwork.targetauditd.servicesshd.service

 
Remove sshdkey creation:

Copy code

The code is as follows:

ExecStartPre=/usr/sbin/sshd-keygen

 

Remove this row
In the execution script, add the configuration file of the second sshd service:

Copy code

The code is as follows:

ExecStart=/usr/sbin/sshd-D-f/etc/ssh/sshd-second_config$OPTIONS

 
The modified sshd-second.service file is as follows:
 

Copy code

The code is as follows:

[Unit]
Description=OpenSSHserversecondinstancedaemon
After=syslog.target network.targe tauditd.service sshd.service
[Service]
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D -f /etc/ssh/sshd-second_config$OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target

 

5) If you use SELinux and add a TCP port, the port responsible for the second sshd service will be rejected for binding:
 

Copy code

The code is as follows:

~]#semanage port -a -tssh_port_t -p tcp22220

 

6) Set up startup and test:

Copy code

The code is as follows:

~]#systemctl enable sshd-second.service
~]$ssh -p 22220 [email protected]

 

Make sure that the firewall port is also open.

(6) Modify an existing unit file

The SYSTEMd unit configuration file is saved in the / usr / lib / SYSTEMd / system / directory by default. The system administrator does not recommend directly modifying the files in this directory. The customized files are in the / etc / SYSTEMd / system / directory. If there is a need for expansion, the following scheme can be used:
Create a directory / etc / SYSTEMd / system / unit. D /. This is the most recommended way. You can refer to the initial unit file and expand the default configuration through the attachment configuration file. The upgrade of the default unit file will be automatically upgraded and applied.
Copy a copy of the original configuration file from / usr / lib / SYSTEMd / system / to / etc / SYSTEMd / system /, and then modify it. The copied version will overwrite the original configuration. In this way, the configuration package of attachments cannot be added for scenarios that do not require additional functions.
If you need to restore to the default configuration file, you only need to delete the configuration file under / etc / SYSTEMd / system /. You do not need to restart the machine. Use the following command to apply the change:

Copy code

The code is as follows:

systemctl daemon-reload

 

The daemon reload option reloads all the unit files and recreates the dependency book, which is used when changes to the unit file need to be applied immediately. In addition, you can use the following command to achieve the same purpose:
 

Copy code

The code is as follows:

init q

 

In addition, if you modify the unit file of a running service, the service needs to be restarted:

Copy code

The code is as follows:

systemct lrestart name.service

 

(7) Extended default cell profile configuration

To expand the default cell file configuration, you need to create a directory under / etc / SYSTEMd / system / and execute the following commands with root:
 

Copy code

The code is as follows:

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

 

To create a configuration file under the directory just created, it must end with a. Conf file.
For example, create a custom dependency file with the following contents:
 

Copy code

The code is as follows:

[Unit]
Requires=new_dependency
After=new_dependency

 

As another example, it can be configured to restart 30 seconds after the main process exits. The configuration example is as follows:

Copy code

The code is as follows:

[Service]
Restart=always
RestartSec=30

 

It is recommended that only one small file be generated at a time, and each file only focuses on improving one function, so that the configuration file can be easily removed or linked to the configuration directory of other service pairs.
To apply the changes just made, use root to do the following:
 

Copy code

The code is as follows:

systemctldaemon-reload
systemctlrestartname.service

 

Example: extend httpd.service service configuration
In order to execute user-defined scripts when the httpd service is started, you need to modify the httpd unit configuration file and perform the following steps. First, create a directory of customization files and customization files:
 

Copy code

The code is as follows:

~]#mkdir/etc/systemd/system/httpd.service.d
~]#touch/etc/systemd/system/httpd.service.d/custom_script.conf

 

Assuming that the customization file is located in / usr / local / bin / custom.sh, add this information to custom_ In script.conf custom script:

Copy code

The code is as follows:

[Service]
ExecStartPost=/usr/local/bin/custom.sh

 

Apply changes:

Copy code

The code is as follows:

~]#systemctldaemon-reload
~]#systemctlrestarthttpd.service