[Linux | systemd] Detailed explanation of the configuration file of systemd (systemctl command) running service

[systemctl] Let the program run in the background as a daemon process

First, you need to create a systemd unit configuration file, such as: verdaccio.service, usually placed under /lib/systemd/system/

Add the following configuration:

[Unit]
Description=Verdaccio lightweight npm proxy registry

[Service]
Type=simple
Restart=on-failure
User=verdaccio
ExecStart=/usr/bin/verdaccio --config /etc/verdaccio/config.yaml

[Install]
WantedBy=multi-user.target

Auto-start at boot: systemctl enable verdaccio.service

Start now: systemctl start verdaccio.service

Restart: systemctl restart verdaccio.service

Running status: systemctl status verdaccio.service

Foreword:

        Have you ever thought about how there are so many services running on the server, how they all work? Services are independent individuals, and each one only cares about his or her own life and death. If a certain service dies secretly, it will have serious consequences, and if one service is managed in one way, the master will be exhausted.

        Therefore, it is not surprising at all that Linux’s management service capabilities are very good. Article source address: https://www.yii666.com/blog/347720.html

        One of the main capabilities of the Linux server is to configure and manage various service programs running on the system. In the early days, the ability to manage service programs was handled by the startup program init system. With the iteration of the Linux system, the earlier init system has evolved from the original sysvinit to today's systemd.

        Therefore, systemd, as the startup program of the init system, is responsible for managing many services running on the system. The method of systemd management is not difficult. You only need to learn how to write the configuration file for running services, and you can easily manage services.

1. Detailed explanation of .server service configuration file information

This is a prometheus service process:

(For example: nginx.service file in /usr/lib/systemd/system directory)

[Unit] 
Description=nginx - web server 
After=network.target remote-fs.target nss-lookup.target 

[Service] 
PIDFile=/opt/nginx/logs/nginx.pid 
ExecStartPre=/opt/nginx/sbin/nginx -t -c /opt/nginx/conf/nginx.conf 
ExecStart=/opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf 
ExecReload=/opt/nginx/sbin/nginx -s reload 
ExecStop=/opt/nginx/sbin/nginx -s stop 
ExecQuit=/opt/nginx/sbin/nginx -s quit 
Type=forking
PrivateTmp=true 

[Install] 
WantedBy=multi-user.target

[Unit]      Control unit: mainly provides service description, startup sequence and dependencies

Description:        Description of the service;

Documentation:          Service documentation

After:         Indicates which service this unit is started after. It only explains the order in which services are started, and is not mandatory.

Before:       The opposite meaning of After

Requires:        This unit needs to be started after which service is started! Dependencies between services are set here. If the leading service set in this item does not start successfully, then this unit will not be started!

Wants:       Just the opposite of Requires, it specifies what services will be started after this unit. If the service following Wants does not start successfully, it will not affect the unit itself!

Conflicts:          If the service connected to this project is started, then this unit cannot be started! (Mutual exclusivity) If this unit is started, the specified service cannot be started.

[Service]      service: mainly gives the startup behavior of the service, how to start, restart, and stop

EnvironmentFile:         The parameter file of the service, forming $OPTIONS;

ExecStart:        is the program that actually executes this service. It accepts the format of "command parameter parameters..." and cannot accept special characters such as <, >, >>, |, &, etc., and many bash syntaxes do not support it. Therefore, when using these special characters, it is best to write them directly into the script!

ExecStop:         used to implement the systemctl stop command and shut down the service.

ExecReload:       Used to implement the systemctl reload command to reload the configuration information of the service.

ExecStartPre:       command executed before starting the service;

ExecStartPost:       command executed after starting the service;

ExecStopPre:       command executed before stopping the service;

ExecStopPost:       command executed after stopping the service;

Type:         Service startup type. By default, simple means that ExecStart is the main process, and notify is similar to simple, and a notification signal will be sent after the startup is completed.

Type extension:

 Type: Define the startup type. The values ​​it can set are as follows:
- simple: the default value. This service is mainly started by the program set by ExecStart, and resides in the memory after startup -
forking: the program started by ExecStart specifies spawns a child process to provide services, and then The parent process exits
- oneshot: similar to simple, but this program ends after the work is completed and will not reside in the memory
- dbus: similar to simple, but this service must obtain a D-Bus name. will continue to run! Therefore, when setting up this project, it is usually necessary to set BusName=
- idle: similar to simple, which means that to execute this service, all work must be successfully completed before execution. This type of service is usually a service that can be executed only after booting up
- notify: similar to simple, but this service must receive a message sent by the sd_notify() function before it can continue to run.

KillMode:        Service stop type. By default, all child processes are killed when the control-group is stopped. Process only kills the main process. None only stops the service and does not kill the process;

 KillMode extension: Article source address https://www.yii666.com/blog/347720.html

 KillMode: Defines how Systemd stops the sshd service. The values ​​it can set are as follows:
 - control-group (default value): all child processes in the current control group will be killed
 - process: only the main process will be killed
 - mixed: the main process will receive the SIGTERM signal, and the child process will receive the SIGTERM signal. To SIGKILL signal
 - none: no process will be killed, only the stop command of the service will be executed.

Restart:         service restart type, the default is no, no restart, on-success will restart when it exits normally, on-failure will restart when it exits abnormally. 

Restart extension:

 Restart: Defines the restart method of Systemd after sshd exits. The values ​​it can set are as follows:
 - no (default value): will not restart after exit
 - on-success: will only restart when exiting normally (exit status code is 0)
 - on-failure: exit abnormally (exit status code is non-0), including termination by signals and timeouts, it will restart
 - on-abnormal: it will only restart when it is terminated by signals and timeout
 - on-abort: it will only restart when it terminates by receiving an uncaptured signal Restart
 - on-watchdog: Exit after timeout before restarting
 - always: No matter what the reason for exit, always restart

Note: For daemon processes, it is recommended to set it to on-failure. For services that allow error exits, this can be set to on-abnormal.

RestartSec:        How long to restart the service. For example RestartSec=42s

TimeoutSec:        If the service fails to "normally start or end normally" for some reason when starting or shutting down, how long do we have to wait before entering the "forced end" state!

RemainAfterExit:        When set to RemainAfterExit=1, this service will try to start again after all programs to which this service belongs are terminated. This is very helpful for Type=oneshot services!

Environment:         configure environment variables

[Service]
Environment="GODEBUG='madvdontneed=1'"
Environment="BEAT_LOG_OPTS=-e"
Environment="BEAT_CONFIG_OPTS=-c /etc/v_filebeat.yml"
Environment="BEAT_PATH_OPTS=-path.home /usr/share/filebeat -path.config /etc/filebeat -path.data /var/lib/data -path.logs /var/log/logs"

 EnvironmentFile:       Set environment variables through files

[Service]
EnvironmentFile=/testenv

Variable declarations can be written using shell commands on the testenv file: 

GODEBUG='madvdontneed=1'
BEAT_LOG_OPTS=-e
BEAT_CONFIG_OPTS=-c /etc/v_filebeat.yml
BEAT_PATH_OPTS=-path.home /usr/share/filebeat -path.config /etc/filebeat -path.data /var/lib/data -path.logs /var/log/logs

The environment variables set in the file can then be used in the ExecStart configuration. 

user:         User name that can be set for the service 

[Install]       Installation part: Mainly explains how to install this configuration file, which target to install the unit on, so that it can start automatically after booting.

WantedBy:         Most of what follows this setting is *.target unit. Meaning, which target unit should this unit itself be attached to?

 Target means service group, which represents a set of services. WantedBy=multi-user.target means that the Target where the service is located is multi-user.target, and the corresponding path is under /etc/systemd/system/multi-user.target.wants. Use systemctl enable to create a symbolic link and the contents of the [Install] field will be recognized for installation.

 Systemd has a default startup Target. It is multi-user.target. All services in this group will be started at boot.

Also:          When the current unit is enabled, the unit following Also also needs to be enabled.

Alias:        When systemctl enables related services, this service will create link files! Enabled by default!

————————————————————————————————————————

Note: In the configuration file, the second line of ExecStart is set to a null value, which is equivalent to canceling the settings in the first line.
Before all startup settings, you can add a hyphen (-) to indicate "suppress errors", that is, when an error occurs. , does not affect the execution of other commands. For example, EnvironmentFile=-/etc/sysconfig/sshd (note the hyphen after the equal sign) means that even if the /etc/sysconfig/sshd file does not exist, no error will be thrown.

========================================================================

2. Detailed explanation of system .target file information

View the target configuration command of the system:
systemctl cat multi-user.target

For example: the default.target file in the /etc/systemd/system directory)

[Unit]
Description=Multi-User System
Documentation=man:systemd.special(7)
Requires=basic.target
Conflicts=rescue.service rescue.target
After=basic.target rescue.service rescue.target
AllowIsolate=yes

Note that there is no startup command in the Target configuration file.

In the above output results, the main fields have the following meanings.

Requires:         requires basic.target to be run together.

Conflicts: Conflict fields. If rescue.service or rescue.target is running, multi-user.target cannot run, and vice versa.

After:      Indicates that multi-user.target starts after basic.target, rescue.service, and rescue.target, if they are started.

AllowIsolate:         Allow using the systemctl isolate command to switch to multi-user.target.

=======================================================================

3. Detailed explanation of status information using systemctl status xxxx

Use the systemctl status command to check the status of the service.

For example: systemctl status nginx

The printed information has the following parts:

● nginx.service - nginx - web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 日 2022-10-09 21:47:15 CST; 3 days ago
 Main PID: 994 (nginx)
   CGroup: /system.slice/nginx.service
           ├─994 nginx: master process /opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf
           ├─998 nginx: worker process
           └─999 nginx: worker process

10月 09 21:47:15 localhost.localdomain systemd[1]: Starting nginx - web server...
10月 09 21:47:15 localhost.localdomain nginx[972]: nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok


The above output results have the following meaning.

Loaded:         The location of the configuration file, whether it is set to start at boot, disabled means enabled

Active:         active (running) means running

Main PID:        Main process ID

CGroup:         all child processes of the application, three nginx processes

Log block:        application logs

Guess you like

Origin blog.csdn.net/qq_28505809/article/details/132868792