Compile the service management script using systemd
The main purpose of running a Linux server is to provide services by running programs, such as mysql and web server. Therefore, the main task of Linux Server Management is to configure and manage various service programs running above. In Linux, The init system is responsible for managing service programs. As I introduced in my article "getting started with systemd", Linux's init system has evolved from sysvinit to systemd. This article describes how to compile a configuration file for running services in the systemd environment.
Unit configuration file
Unit is the basic unit for managing tasks using systemd. We have already introduced that a service-type Unit represents a background service process. Next, we will introduce in detail how to configure a service-type unit. Let's take a look at a simple service configuration:
[Unit]
Description = Prometheus Server
Documentation = https://prometheus.io/docs/introduction/overview/
Afterdomainnetwork.tar get
[Service]
User = prometheus
Restart = on-failure
WorkingDirectory =/usr/local/share/prometheus/
ExecStart =/usr/local/share/prometheus \
-Config. file =/usr/local/share/prometheus. yml
[Install]
Wantedbypolicmulti-user.tar get
This is the configuration file of the prometheus service on the host. Save the above content to the file/lib/systemd/system/prometheus. service, and then you can use the systemctl command to manage the prometheus service. Note that the service type configuration file name must end with. service.
View the configuration details above, we will find that the configuration content is divided into three parts:
[Unit] the description of the unit itself, and the settings of services that are dependent on others, including the settings of the unit after which services are started.
[Service] different unit types must use the corresponding settings. For example, the timer Type unit should be [Timer], and the socket type unit should be [Socket]. The unit of the Service type is [Service]. This project mainly regulates the script for starting the Service, the file name of the Environment configuration file, and the restart method.
[Install] This section mainly sets the target to which the unit is installed.
Detailed configuration of service type unit
The configuration file is divided into three parts, each of which provides detailed configuration information. To precisely control the running mode of a service, we need to understand these detailed configuration options and finally let the service run as expected.
[Unit] Section
Description: a simple Description of the unit.
Documentation-related content, such as Documentation = https://prometheus.io/docs/introduction/overview/
Documentation = man: sshd (8)
Documentation = file:/etc/ssh/sshd_config
After indicates the service in which the unit is started. It only indicates the order in which the service is started and is not mandatory.
Before is opposite to After. It is best to start this service Before the specified service starts. It only indicates the order in which the service is started and is not mandatory.
Requires this unit must be started after which service can be started! Is to set the dependencies between services. If the leading service set in this item is not started successfully, this unit will not be started!
Wants is opposite to Requires. It standardizes the services to be started after this unit. If the services followed by this Wants are not started successfully, it will not affect the unit itself!
Conflicts, if any service is started after this project, this unit cannot be started! If this unit is started, the specified service cannot be started.
[Service] Section
Type
It indicates that the startup method of this service will affect ExecStart, mainly including the following types:
Simple: the default value. This service is mainly started by the program set by ExecStart and is resident in the memory after being started.
Forking: A program specified by ExecStart generates sub-processes through spawns to provide services, and then the parent process exits.
Oneshot: similar to simple, but this program ends after work and will not resident in the memory.
Similar to simple, but this service must continue running only after obtaining a D-Bus name! Therefore, you must set BusName = when setting this project.
Idle: similar to simple, it means that to execute this service, it must be executed after all the work is successfully executed. This type of service is usually a service that can be executed only after it is started.
Notify: similar to simple, but this service must continue to run after receiving a message sent by an sd_notify () function.
ExecStart
Is the program that actually executes the service. The format that accepts "command parameter parameters..." cannot accept special characters such as <,>, >>, |, and &. Many bash syntaxes are not supported. Therefore, it is best to directly write these special characters into the script!
ExecStartPre and ExecStartPost execute additional commands before and after the service starts.
ExecStop is used to implement the systemctl stop command and disable the service.
ExecReload is used to implement the systemctl reload command to reload the configuration information of the service.
When Restart is set to Restart = 1, if the service is terminated, the service is automatically restarted.
RestartSec works with Restart to Restart the service after the service is terminated. The default value is 100 ms.
KillMode
It can be process, control-group, or none. If it is process, the service will terminate only the main program (the string of commands followed by ExecStart ), if it is a control-group, other control-group programs generated by daemon will also be closed. If it is none, no program will be closed.
TimeoutSec
If the service cannot be "started normally or ended normally" for some reason when it is started or closed, how long will it take for us to enter the "Force ended" status!
RemainAfterExit
When it is set to RemainAfterExit = 1, the service will start again after all the programs to which the service belongs are terminated. This is very helpful for the Type = oneshot service!
Environment variable settings are very important for many programs. The following configuration can be used to set environment variables for service programs in different ways:
Environment is used to set Environment variables. It can be used multiple times:
[Service]
# Client Env Vars
Environment = ETCD_CA_FILE =/path/to/CA. pem
Environment = ETCD_CERT_FILE =/path/to/server. crtEnvironmentFile sets the Environment variables by file. You can save the following content to the file testenv:
Aaa_00004_anchor_0 = X. X
Bbb_00004_private_0 = X. X
CCC_HOSTNAME = test.example.com and set it as follows:
[Service]
EnvironmentFile =/testenv then you can use the environment variables set in the file in the ExecStart configuration, such:
ExecStart =/xxx -- abc = xx $ {aaa_rj4_anchor_0} yy [Install]
Most of the settings following WantedBy are followed by *. target unit. This unit is attached to the target unit.
When the current unit is enable, the unit followed by Also must Also enable.
When systemctl enable is related to the Alias service, the service creates a link file!
Detailed configuration of Timer-Type unit
Timer-type units are mainly used to execute scheduled tasks and may replace cron services. Since timer-type units are often used together with service-type units, this article also introduces the timer unit configuration. Different from the service type unit, the main part of the timer unit configuration file is [Timer]. The following are the main configuration items:
OnActiveSec: How long does it take to execute this unit after timers.tar get is started.
How long does OnBootSec execute this unit after it is started.
OnStartupSec: How long does it take to execute this unit when systemd is started for the first time.
The unit Service managed by the timer configuration file OnUnitActiveSec will be executed several times after the last startup.
The unit Service managed by the timer configuration file OnUnitInactiveSec will be executed after the last stop.
You do not need to set the Unit. Basically, we set the service name. server + service name. timer. If your service name and timer name are different, you need to specify the service name through the Unit item in the. timer file.
OnCalendar uses the actual time (non-cyclic time) to start the service.
When OnCalendar is used, Persistent specifies whether or not this function is continuously executed.
Based on the above introduction, I believe that you have a basic understanding of the systemd service type and timer Type unit configuration. Let's configure two practical examples.
Configure the redis Service
On Ubuntu, we usually manually compile and install redis. After the installation is complete, you need to configure redis as a service managed by systemd. The following describes the specific configuration process.
Add a redis configuration file
First, manually create the/etc/redis directory and add the configuration file:
$ Sudo mkdir/etc/redis and copy the configuration file redis. conf in the Code directory to the/etc/redis directory:
$ Sudo cp/tmp/redis-4.0.0/redis. conf/etc/redis/then modify the supervised in the configuration file/etc/redis. conf to systemd:
Supervised systemd
Then, configure the working directory in the configuration file/etc/redis. conf and change dir./:
Dir/var/lib/redis
Configure the redis service managed by systemd
Create the/etc/systemd/system/redis. service file
$ Sudo vim/etc/systemd/system/redis. service:
[Unit]
Description = Redis In-Memory Data Store
Afterdomainnetwork.tar get
[Service]
User = redis
Group = redis
ExecStart =/usr/local/bin/redis-server/etc/redis. conf
ExecStop =/usr/local/bin/redis-cli shutdown
Restart = always
[Install]
Wantedbypolicmulti-user.tar get
Start the service and configure it to start upon startup:
$ Sudo systemctl start redis
$ Sudo systemctl enable redis
$ Sudo systemctl status redis
Regular backup of files through scripts
Bash script for backup files:
#! /Bin/bash
Mydate ()
{
Date "+ % Y % m % d % H % M % S"
}
Backupdate = $ (mydate)
Tar-zcf/tmp/backup.${backupdate).tar.gz/home/nick/learn
Save the above Code to the file/usr/local/bin/backupdir. sh and add the executable permission:
$ Sudo chmod + x/usr/local/bin/backupdir. sh and then create the service unit configuration file:
[Unit]
Description = nick backup learn dir service
[Service]
User = nick
Group = nick
Type = simple
ExecStart =/usr/local/bin/backupdir. sh
[Install]
Wantedbypolicmulti-user.tar get
Save the unit configuration above to the/etc/systemd/system/nickbak. service file.
Then run the following command to test the service execution:
$ Sudo systemctl daemon-reload
A backup task such as $ sudo systemctl start nickbak. service is executed only once when sudo systemctl start nickbak. service is executed. Next we will configure it as scheduled execution through timer unit.
Create the timer unit configuration file:
[Unit]
Description = nick backup learn dir timer
[Timer]
OnCalendar = *: 0/15
Persistent = true
Unit = nickbak. service
[Install]
Wantedbypolicmulti-user.tar get
Save the unit configuration above to the/etc/systemd/system/nickbak. timer file. In the configuration, OnCalendar = *: 0/15 indicates that the nickbak. service is executed every 15 minutes.
Run the following command to set nickbak. timer to boot and start nickbak. timer:
$ Sudo systemctl daemon-reload
$ Sudo systemctl enable nickbak. timer
$ Sudo systemctl start nickbak. timer:
$ Sudo systemctl status nickbak. timer
From now on, nickbak. timer will execute the nickbak. service every 15 minutes.
Summary
Systemd provides all aspects of service management (actually unit management). What we need to do is to write the configuration file of the service unit and then use systemd to manage our services. This is a seemingly simple and complex task (many configuration items need to be constantly adjusted and optimized in practice ). I hope this article is a simple entry for everyone.
Refer:
Laruence's Linux Private food-Basic Learning (version 4) full-definition bookmarks PDF Edition
This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151290.htm