Detailed explanation of systemd's unit configuration file

Table of contents

unit type

systemctl common commands

unit configuration file

[Unit] part detailed explanation

[Service] part detailed explanation

service-specific parameters

process execution environment

process environment variable

how to kill a process

process resource control

Detailed explanation of [Install] part

Target meaning

Common unit configuration files


Systemd is a Linux system and service manager, compatible with SysV and LSB initialization scripts, Systemd has the following features:

  • Aggressive Parallelization Capabilities
  • Start a service using socket and D-Bus activation
  • Provides on-demand startup of daemons, using Linux cgroups to track processes
  • Supports snapshot and restore of system state
  • Maintain mounts and automount points
  • Implement well-designed service control logic based on transaction dependencies

The systemctl command is the main tool for managing systemd, it combines the functionality of the SysVinit service and chkconfig commands into one tool, and you can use it to enable and disable services permanently or for the current session only

unit type

Systemd manages units, which are representations of system resources and services, and the following list shows the types of units that systemd can manage:

  • service A service on the system, including starting, restarting, and stopping a service
  • socket The network socket associated with the service
  • device uses systemd to manage devices specially
  • mount mount points managed by systemd
  • The mount point that is automatically mounted when automount starts
  • swap swap space on the system
  • target Synchronization point for other units, usually used to start enabled services at boot time
  • path The path to activate based on the path. For example, you can start a service based on the state of a path, such as whether it exists
  • timer is used to schedule a timer to activate another unit.
  • snapshot A snapshot of the current systemd state. Typically used to rollback after making temporary changes to systemd
  • slice limits resources through Linux control group nodes (cgroups)
  • scope Information from the systemd bus interface. Usually used to manage external system processes

systemctl common commands

systemctl start chronyd #启动
systemctl stop chronyd #停止
systemctl restart chronyd #重启
systemctl status chronyd #查看 unit 状态

systemctl enable chronyd #设置 unit 开启启动
systemctl disable chronyd #取消 unit 开机启动
systemctl is-enabled chronyd #查看 unit 是否开机启动

# 重新加载 unit 的配置文件,每次修改了 unit 的配置文件后,需要执行以下命令重新加载 unit 的配置文件
systemctl daemon-reload

systemctl mask chronyd #屏蔽 unit,屏蔽后 unit 无法启动
systemctl unmask chronyd #取消屏蔽

# 更多命令可通过 systemctl --help 或 man systemctl 来查看

unit configuration file

The unit configuration file of the sshd service is as follows, mainly divided into three parts: [Unit], [Service] and [Install]

[root@vm03 ~]# cat /usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.service
Wants=sshd-keygen.service

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

[Unit] part detailed explanation

The parameters used in this section are not limited to service type units, but are also common to other types of units. For a complete list of these parameters and their descriptions, you can run the command man systemd.unit or visit the systemd.unit Chinese  manual

Note: A space-separated list can be specified after each parameter in the [unit] block

  • Description: Description of the current unit
  • Documentation: document address, only accepts URIs of type: http://, https://, file:, info:, man:
  • Requires: Indicates that there is a strong dependency between this unit and other units. If this unit is activated, the units listed here will also be activated. If one of the dependent units cannot be activated, systemd will not start this unit
  • Wants: Similar to Requires, the difference is that if the dependent unit fails to start, it will not affect the continued operation of the unit
  • After: Indicates that the unit should be started after a certain service, the options can refer to  the systemd.special Chinese manual
  • Before: Indicates that the unit should be started before a certain service, and the After and Before fields only involve the startup sequence, not dependencies
  • BindsTo: Similar to Requires, when the specified unit stops, this unit will also stop
  • PartOf: Similar to Requires, when the specified unit stops or restarts, it will also cause the unit to stop or restart
  • Conflicts: If the specified unit is running, this unit will not be able to run
  • OnFailure: When the unit enters the failure state, activate the specified unit

[Service] part detailed explanation

service-specific parameters

Only service type units have these parameters, for a complete list of parameters, please visit  systemd.service Chinese manual  or  systemd.service

  • simple (default value): The service is started by the main process. systemd thinks that the service will start immediately, and the service process will not fork. If the service wants to start other services, do not use this type of start, unless the service is socket-activated.
  • forking: The service will be started as a fork, at which point the parent process will exit and the child process will become the main process. systemd thinks that when the service process forks and the parent process exits, the service starts successfully. For regular daemons, unless you are sure that this startup method cannot meet your needs, use this type of startup. Using this startup type should also specify PIDFile= so that systemd can track the main process of the service
  • oneshot: Similar to simple, but only executed once, Systemd will wait for it to finish executing before starting other services. This option is suitable for services that perform only one task and then exit immediately. It may be necessary to set RemainAfterExit=yes at the same time so that systemd still considers the service to be active after the service process exits
  • dbus: Similar to simple, but starts after waiting for D-Bus signal. systemd considers the service ready when the specified BusName is present on the DBus system bus.
  • notify: Similar to simple, Systemd will be notified after startup, and then continue to execute
  • idle: similar to simple, but the service will not be started until all other tasks are executed

RemainAfterExit: A boolean value that specifies that the service should be considered alive even if all processes of the service have exited, defaults to no

GuessMainPID: A boolean value that specifies whether systemd should guess the main PID of a service if it cannot reliably determine it. This option is ignored unless Type=forking is set and PIDFile is not set, defaults to yes

PIDFile: The absolute filename pointing to the PID file for this daemon. This option is recommended for services with Type=forking. Systemd reads the PID of the daemon's main process after the service has started. Systemd will not write to the file configured here, but it will delete the file after the service shuts down

BusName: The name of the D-Bus bus to reach this service. This option is required for services with Type=dbus

ExecStart: The command and parameters executed when the service starts

ExecStartPre: The command executed before the service starts

ExecStartPost: The command executed after the service starts

ExecReload: the command executed when restarting the service

ExecStop: Commands and parameters executed when the service stops

ExecStopPost: command executed after the service stops

RestartSec: Sleep time in seconds before restarting the service

TimeoutStartSec: Time to wait for the service to start (in seconds)

TimeoutStopSec: Time to wait for the service to stop (in seconds)

TimeoutSec: Configure the abbreviation of TimeoutStartSec and TimeOutshopSec at the same time

Restart: Configure whether to restart the service when the service process exits, is killed, or reaches a timeout. The values ​​that can be set are as follows:

  • no service will not be restarted, this is the default
  • on-success restarts only if the service process exits cleanly (exit code 0)
  • on-failure only restarts when the service process exits abnormally. The so-called "abnormal exit" means: the exit code is not "0"
  • on-abnormal Restart if the process terminates due to a signal or timeout
  • on-watchdog Restart when watchdog times out
  • on-abort restart if the process exits due to an uncaught signal not specified as a clean exit status
  • always always restart

Environment: specify environment variables

KillMode: Define how systemd stops the service. The values ​​that can be set are as follows:

  • control-group (default value): all child processes in the current control group will be killed
  • process: only kill the main process
  • mixed: the main process will receive the SIGTERM signal, and the child process will receive the SIGKILL signal
  • none: no process will be killed, just execute the stop command of the service

process execution environment

The configuration options shared by service, socket, mount, and swap units and used to define the process execution environment are listed below. For complete parameter descriptions, you can run the command man systemd.exec or visit the Chinese manual of  systemd.exec

WorkingDirectory: Set the working directory of the process

User=, Group: Set the user and group used by the process during execution, which can be set as a UID/GID in the form of a number or a name in the form of a string

NoNewPrivileges: Receives a Boolean value. Set to yes to indicate that all processes and child processes of the service cannot obtain any new permissions through execve() calls. This option is the simplest and most effective way to prevent processes from elevating privileges

SELinuxContext: Set the SELinux security context of the process

Set various soft/hard resource limits for the process: LimitCPU=, LimitFSIZE=, LimitDATA=, LimitSTACK=, LimitCORE=, LimitRSS=, LimitNOFILE=, LimitAS=, LimitNPROC=, LimitMEMLOCK=, LimitLOCKS=, LimitSIGPENDING=, LimitMSGQUEUE=, LimitNICE=, LimitRTPRIO=, LimitRTTIME= There are two notations for the value, and a single value value means to set the soft and hard limits to the same value. The colon-separated soft:hard value means to set the soft limit and hard limit respectively (for example, LimitAS=4G:16G), and the special value infinity means no limit. For options in bytes, base 1024 K, M, G, T, P, E suffixes can be used (e.g. LimitAS=16G). For time limits, you can add "ms" (milliseconds), "s" (seconds), "min" (minutes), "h" (hours), "d" (days), "w" (weeks) and other explicit time unit suffixes

UMask: Set the file creation mask, the default value is 0022

OOMScoreAdjust: Set the priority of the process being killed due to insufficient memory. Can be set to an integer value between -1000 (forbidden to be killed) and 1000 (first to be killed)

Environment: Set the environment variables of the process, accepting a space-separated list of VAR=VALUE. This option can be used multiple times to add new variables or modify existing variables (the last setting of the same variable shall prevail). Set to empty means to clear all previously set variables. Note: (1) Variable expansion will not be performed inside the string (that is, "$" has no special meaning); (2) If the value contains spaces or equal signs, double quotes (") must be used on both sides of the string to delimit, for example: Environment="VAR1=word1 word2" VAR2=word3 "VAR3=$word 5 6" means that three variables "VAR1", "VAR2", and "VAR3" are set, and their values ​​are "word1 word2", " word3", "$word 5 6"

EnvironmentFile: Similar to Environment=, the difference is that this option reads the setting of environment variables from a text file. Blank lines in the file and lines beginning with semicolon (;) or pound sign (#) will be ignored, and the format of other lines must conform to the shell variable assignment syntax of VAR=VALUE. A backslash (\) at the end of a line is treated as a continuation character, similar to shell syntax. If you want to include spaces in the variable value, you must add double quotes (") to both ends of the value. The file must be represented by an absolute path (can contain wildcards). But you can add a "-" prefix to the path to ignore non-existing files. You can use this option multiple times to read settings from multiple different files. If it is set to empty, it means clearing all environment variables that have been previously read from the file. to read it. Environment variables read from a file override variables of the same name set in Environment=. The order in which files are read is the order in which they appear in the unit file, and for the same variable, the setting in the last file read prevails

UnsetEnvironment: Explicitly unsets a specific environment variable for this unit

StandardInput: Set the standard input (STDIN) of the process, which can be set to one of null, tty, tty-force, tty-fail, data, file:path, socket, fd:name, the default value of this option is null

StandardOutput: Set the standard output (STDOUT) of the process, which can be set to one of inherit, null, tty, journal, syslog, kmsg, journal+console, syslog+console, kmsg+console, file:path, append:path, socket, fd:name

StandardError: Set the standard error (STDERR) of the process, the value range and meaning are the same as StandardOutput=

StandardInputText, StandardInputData: Set any text or binary data passed to the process through standard input (STDIN). These options are only meaningful when StandardInput=data

LogLevelMax: Filter the log messages generated by this unit according to this log level, which can be set to a syslog log level, which is one of emerg (the lowest log level, only displaying the most fatal messages), alert, crit, err, warning, notice, info, debug (the highest log level, displaying the most detailed debugging messages)

process environment variable

For detailed instructions, visit  the systemd.exec Chinese manual

$PATH: directory list of executable files (absolute paths separated by colons), this value is fixed at /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

$LANG: Localization settings. Can be set via the locale.conf(5) file

$USER, $LOGNAME, $HOME, $SHELL: username, username, home directory, login shell

$MAINPID: PID of the unit's main process (if it can be determined)

how to kill a process

The service, socket, mount, swap, and scope units all have a set of configuration options for how to kill the process. For complete parameter descriptions, you can run the command man systemd.kill or visit the systemd.kill Chinese  manual

KillMode: Set the method to kill the process when the unit stops. The range of values ​​is: control-group, process, mixed, none The default value is control-group, which means killing all processes in the cgroup of the unit (for the service unit, the ExecStop= action must be executed first)

KillSignal: Set what signal to use in the first step of killing the process, all available signals are detailed in  the signal(7)  manual. The default is the SIGTERM signal. Note that systemd will unconditionally follow this signal with a SIGCONT signal to ensure clean killing of suspended processes

SendSIGHUP: Whether to send a SIGHUP signal to all processes of the unit immediately after sending the KillSignal= signal in the first step. This is mainly used to notify processes such as shells that their connection has been broken. Defaults to "no"

SendSIGKILL: Whether to use the SIGKILL or FinalKillSignal= signal to kill the remaining process after the TimeoutStopSec= time has elapsed. The default value is "yes"

FinalKillSignal: When a timeout occurs and SendSIGKILL= is turned on, which signal is sent to the remaining processes. Should be set to a signal that cannot be caught and handled by the service (SIGTERM is not appropriate). For developers, it can be used to generate a coredump to understand why the service did not terminate properly when it received the initial SIGTERM signal. This is done by setting LimitCORE= and setting FinalKillSignal= to one of SIGQUIT or SIGABRT. The default value for this option is SIGKILL

WatchdogSignal: Which signal is used to terminate the service when the watchdog (WatchdogSec=) times out. The default value for this option is SIGABRT

process resource control

The slice, scope, service, socket, mount, and swap units share a set of configuration options for limiting process resource usage. Essentially, these options rely on the cgroups function of the Linux kernel to organize a group of processes into a tree-like hierarchy and limit the various resources they allow. For a complete list of these parameters and their descriptions, you can run the command man systemd.resource-control or visit the systemd.resource-control Chinese  manual

Detailed explanation of [Install] part

[install] defines the installation information of the unit. This part of the configuration is only used when systemctl enable or systemctl disable is used. This part is not explained when the unit is running, which is equivalent to configuring how to boot

The parameters used in this section are not limited to service type units, but are also common to other types of units. For a complete list of these parameters and their descriptions, run the command man systemd.unit or visit the systemd.unit Chinese  manual

  • Alias: The current unit can be used to start the alias, the names listed here must have the same suffix (ie type) as the service file name, when executing systemctl enable will create symbolic links from these names to the unit file name
  • RequiredBy: Indicates the Target where the service is located. Its value is one or more Targets. When systemctl is enabled, the unit symbolic link will be placed in the subdirectory formed by the Target name + .required suffix under the /etc/systemd/system directory
  • WantedBy: Indicates the Target where the service is located. Its value is one or more Targets. When the current systemctl is enabled, the unit symbolic link will be placed in the subdirectory formed by the Target name + .wants suffix under the /etc/systemd/system directory
  • Also: when systemctl enable or systemctl disable, it will enable and disable other unit list at the same time

Target meaning

The meaning of Target is a service group, which means a group of services. WantedBy=multi-user.target means that the Target where the unit is located is multi-user.target (multi-user mode)

This setting is very important, because executing systemctl enable will link the unit to the /etc/systemd/system/multi-user.target.wants directory to realize the function of booting

Common unit configuration files

# nginx的unit 配置文件
cat /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/run/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /usr/local/nginx/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /usr/local/nginx/run/nginx.pid)"

[Install]
WantedBy=multi-user.target

# redis的unit 配置文件
[Unit]
Description=Redis data structure server
Documentation=https://redis.io/documentation
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf
LimitNOFILE=10032
NoNewPrivileges=yes
OOMScoreAdjust=-900
Type=notify
User=redis
Group=redis

[Install]
WantedBy=multi-user.target

# mysql的unit 配置文件
[Unit]
Description=mysql server
Documentation=https://dev.mysql.com/doc/refman/5.7/en/using-systemd.html
After=network.target
After=syslog.target

[Service]
User=mysql
Group=mysql
Type=forking
PIDFile=/usr/local/mysql/mysqld.pid
ExecStart=/usr/local/mysql/bin/mysqld --daemonize --pid-file=/usr/local/mysql/mysqld.pid $MYSQLD_OPTS
LimitNOFILE=5000
Restart=on-failure

[Install]
WantedBy=multi-user.target

# prometheus的unit 配置文件
[Unit]
Description=prometheus service
Documentation=https://prometheus.io/docs/prometheus/latest/management_api
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/prometheus/prometheus \
    --config.file=/usr/local/prometheus/prometheus.yml \
    --storage.tsdb.retention.time=92d \
    --storage.tsdb.path=/usr/local/prometheus/data \
    --web.listen-address=0.0.0.0:9090 \
    --web.console.templates=/usr/local/prometheus/consoles \
    --web.console.libraries=/usr/local/prometheus/console_libraries
#如果想要输出日志重定向到文件,可以按如下方式,注意此时就不能使用续行符了
#ExecStart=/bin/bash -ce "/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml >> /var/log/prometheus.log  2>&1"
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

# alertmanager的unit 配置文件
[Unit]
Description=alertmanager service
Documentation=https://prometheus.io/docs/alerting/latest/management_api
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/alertmanager/alertmanager \
    --config.file=/usr/local/alertmanager/alertmanager.yml \
    --storage.path=/usr/local/alertmanager/data \
    --data.retention=120h \
    --web.listen-address=0.0.0.0:9093
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

# node_exporter的unit配置文件
[Unit]
Description=node_exporter
Documentation=https://github.com/prometheus/node_exporter
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/prometheus_exporter/node_exporter-1.1.2.linux-amd64/node_exporter \
    --web.listen-address=0.0.0.0:9100 \
    --web.telemetry-path=/metrics
ExecStop=/bin/kill -s TERM $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

# redis_exporter的unit配置文件
[Unit]
Description=redis_exporter
Documentation=https://github.com/oliver006/redis_exporter
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/prometheus_exporter/redis_exporter-v1.25.0.linux-amd64/redis_exporter \
    -redis.addr=localhost:6379 \
    -redis.password=123456 \
    -web.listen-address=:9121 \
    -web.telemetry-path=/metrics
Restart=on-failure

[Install]
WantedBy=multi-user.target

# blackbox_exporter的unit配置文件
[Unit]
Description=blackbox_exporter
Documentation=https://github.com/prometheus/blackbox_exporter
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/prometheus_exporter/blackbox_exporter-0.19.0.linux-amd64/blackbox_exporter \
    --web.listen-address=0.0.0.0:9115 \
    --config.file=/usr/local/prometheus_exporter/blackbox_exporter-0.19.0.linux-amd64/blackbox.yml
ExecStop=/bin/kill -s TERM $MAINPID
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

# mysqld_exporter的unit配置文件
[Unit]
Description=mysql_exporter
Documentation=https://github.com/prometheus/mysqld_exporter
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/prometheus_exporter/mysqld_exporter-0.13.0.linux-amd64/mysqld_exporter \
    --config.my-cnf=/usr/local/prometheus_exporter/mysqld_exporter-0.13.0.linux-amd64/.my.cnf \
    --web.listen-address=:9104 \
    --web.telemetry-path=/metrics
Restart=on-failure

[Install]
WantedBy=multi-user.target

# systemd管理java进程
[Unit]
Description=question_api
Documentation=https://docs.oracle.com/javase/tutorial/deployment/jar/basicsindex.html
After=network.target

[Service]
Type=forking
SuccessExitStatus=143
ExecStart=/bin/sh -c "/usr/local/java/jdk1.8.0_201/bin/java -Xms2048m -Xmx2048m -jar /app/question_api/question_api_beta.jar --server.port=8080 >> /var/log/app/question_api.log 2>&1 &"
ExecStop=/bin/kill -s TERM $MAINPID

Restart=on-failure

[Install]
WantedBy=multi-user.target

# 配置项 SuccessExitStatus=143 是为了抑制stop时报错 Main process exited, code=exited, status=143/n/a
# 这是因为 java 程序在响应 SIGTERM 时不会并不会发回预期的退出状态
# 所以需要将退出代码 SuccessExitStatus=143 添加到 systemd 服务文件作为成功退出状态来抑制这种报错

Guess you like

Origin blog.csdn.net/zzchances/article/details/127993610