Systemd Tutorial: Practical Guide
Systemd Introduction Tutorial: Commands Section Origin II. Overview of Systemd Section 3: System Management 3.1 systemctl 3.2 systemd-analyze 3.3 hostnamectl 3.4 localectl 3.5 timedatectl 3.6 loginctl fourth, unit 4.1 Meaning 4.2 Unit status 4.3 Unit Management 4.4 Dependency Relationship V. Unit Configuration File 5.1 Overview 5.2 Configuration File Status 5.3 Configuration file format 5.4 Configuration File Sections Six, Target 7. Log Management Document Information
Author: Ruan Yifeng
Date: March 7, 2016
Systemd is a Linux system utility used to start Process guardian Has become the standard configuration for most distributions.
This article introduces its basic usage, divided into two parts. Today, we introduce its main commands. Next article Introduce its practical application.
In history,
Linux boot
Always adopt
init
Process.
The following command is used to start the service.
xxxxxxxxxx
$ sudo /etc/init.d/apache2 start
# or
$ service apache2 start
This method has two drawbacks.
Firstly, the startup time is long.
init
Processes are initiated sequentially; the next process will only start after the previous one has completed.
The second issue is that the startup script is complex.
init
The process merely executes the startup script, ignoring other matters. The script must handle various situations itself, often making the script lengthy.
Systemd was born to address these issues. Its design goal is to provide a comprehensive solution for system boot and management.
According to Linux convention, letters
d
It's an abbreviation for daemon. The name "Systemd" signifies that it is meant to be a guardian for the entire system.
(As shown above is the author of Systemd) Lennart Poettering )
No longer needed with Systemd.
init
Done. Systemd has replaced
initd
It becomes the first process of the system (PID equals 1), and all other processes are its children.
xxxxxxxxxx
$ systemctl --version
The command above checks the version of Systemd.
Systemd 的优点是功能强大,使用方便,缺点是体系庞大,非常复杂。事实上,现在还有很多人反对使用 Systemd,理由就是它过于复杂,与操作系统的其他部分强耦合,违反"keep simple, keep stupid"的 Unix philosophy
(上图 shows the Systemd architecture diagram)
Systemd isn't a single command; it's a suite of commands involving various aspects of system management.
systemctl
It's the main command of Systemd, used for system management.
xxxxxxxxxx
Reboot the system
$ sudo systemctl reboot
Shut down the system and disconnect the power.
$ sudo systemctl poweroff
CPU has stopped functioning.
$ sudo systemctl halt
# Pause System
$ sudo systemctl suspend
# Put the system into hibernation mode
$ sudo systemctl hibernate
Put the system into an interactive hibernation state.
$ sudo systemctl hybrid-sleep
# Start into rescue mode (single-user mode)
$ sudo systemctl rescue
systemd-analyze
Command to view startup time.
xxxxxxxxxx
# Check startup time
$ systemd-analyze
Check the startup time for each service.
$ systemd-analyze blame
Show a waterfall-like startup process flow.
$ systemd-analyze critical-chain
Show the startup log of the specified service
$ systemd-analyze critical-chain atd.service
hostnamectl
The command is used to view the current host's information.
xxxxxxxxxx
# Display information about the current host
$ hostnamectl
# Set hostname.
$ sudo hostnamectl set-hostname rhel7
localectl
Command is used to view localization settings.
xxxxxxxxxx
Check Localized Settings
$ localectl
Set localization parameters.
$ sudo localectl set-locale LANG=en_GB.utf8
$ sudo localectl set-keymap en_GB
timedatectl
Command to view current timezone setting.
# Check current timezone setting
$ timedatectl
Show all available time zones
$ timedatectl list-timezones
Set the current time zone
$ sudo timedatectl set-timezone America/New_York
$ sudo timedatectl set-time YYYY-MM-DD
$ sudo timedatectl set-time HH:MM:SS
loginctl
The command is used to view the currently logged-in user.
xxxxxxxxxx
List current session
$ loginctl list-sessions
List current logged-in user
$ loginctl list-users
List the information displayed for the specified user.
$ loginctl show-user ruanyf
Systemd manages all system resources. Different resources are collectively called Units (units).
Unit is divided into 12 types in total.
systemctl list-units
Command can view all Units in the current system.
xxxxxxxxxx
List running Units
$ systemctl list-units
List all Units, including those without configuration files or those that failed to start.
$ systemctl list-units --all
List all units that have not been executed.
$ systemctl list-units --all --state=inactive
List all failed to load Units
$ systemctl list-units --failed
List all running Unit processes of type service.
$ systemctl list-units --type=service
systemctl status
Commands are used to view system and individual Unit status.
xxxxxxxxxx
Show system status
$ systemctl status
Display the status of a single unit
$ sysystemctl status bluetooth.service
# Display the status of a specific Unit on a remote host
$ systemctl -H root@rhel7.example.com status httpd.service
Except for
status
Command.
systemctl
Provided three simple methods for querying statuses, mainly for use in script internal conditional statements.
xxxxxxxxxx
Show if a Unit is Running
$ systemctl is-active application.service
Check if a Unit is in a failed start state
$ systemctl is-failed application.service
# Check if a Unit service has established a startup link
$ systemctl is-enabled application.service
For users, the most commonly used commands are as follows, for starting and stopping Unit (mainly services).
xxxxxxxxxx
Start a service immediately.
$ sudo systemctl start apache.service
Stop a service immediately
$ sudo systemctl stop apache.service
Restart a service
$ sudo systemctl restart apache.service
Kill all subprocesses of a service
$ sudo systemctl kill apache.service
Reload the configuration file of a service
$ sudo systemctl reload apache.service
Reload all modified configuration files
$ sudo systemctl daemon-reload
# Display all underlying parameters of a certain Unit
$ systemctl show httpd.service
# Show the value of a specified property of a certain Unit
$ systemctl show -p CPUShares httpd.service
Set specified attribute of a unit
$ sudo systemctl set-property httpd.service CPUShares=500
Dependencies exist between units: A depends on B, meaning Systemd will start B alongside A.
systemctl list-dependencies
List all dependencies of a Unit.
xxxxxxxxxx
$ systemctl list-dependencies nginx.service
In the output of the above command, some dependencies are of the Target type (see below). By default, they are not expanded. To expand the Targets, you need to use
--all
Parameters.
xxxxxxxxxx
$ systemctl list-dependencies --all nginx.service
Each Unit has a configuration file that tells Systemd how to start the Unit.
Systemd is set to read from directory
/etc/systemd/system/
Read the configuration file. However, most of the files stored in it are symbolic links, pointing to directories.
/usr/lib/systemd/system/
The actual configuration file is located in that directory.
systemctl enable
The command is used to establish symbolic link relationships between the two directories.
xxxxxxxxxx
$ sudo systemctl enable clamd@scan.service
# Equivalent to
$ sudo ln -s '/usr/lib/systemd/system/clamd@scan.service' '/etc/systemd/system/multi-user.target.wants/clamd@scan.service'
If the configuration file is set to start on boot,
systemctl enable
Command is akin to activating boot-up startup.
In contrast,
systemctl disable
The command is used to unlink symbolic links between two directories, equivalent to disabling boot-up startup.
xxxxxxxxxx
$ sudo systemctl disable clamd@scan.service
The file extension of the configuration file indicates the type of the Unit, for example.
sshd.socket
If omitted, the default suffix for Systemd is: ".service"
.service
Therefore,
sshd
Be interpreted as
sshd.service
。
systemctl list-unit-files
Command is used to list all configuration files.
xxxxxxxxxx
List all configuration files
$ systemctl list-unit-files
List configuration files of specified type
$ systemctl list-unit-files --type=service
This command outputs a list.
xxxxxxxxxx
$ systemctl list-unit-files
UNIT FILE STATE
chronyd.service enabled
clamd@.service static
clamd@scan.service disabled
This list shows the status of each configuration file, which totals four types.
[Install]
Partly (unexecutable), it can only serve as a dependency for other configuration files.
Note that the configuration file status does not indicate whether the Unit is running. This must be executed as mentioned earlier.
systemctl status
Command.
xxxxxxxxxx
$ systemctl status bluetooth.service
Once the configuration file is modified, you must reload the file for SystemD and restart it, otherwise the changes will not take effect.
xxxxxxxxxx
$ sudo systemctl daemon-reload
$ sudo systemctl restart httpd.service
Configuration files are plain text files, which can be opened with a text editor.
systemctl cat
Commands can view the contents of configuration files.
xxxxxxxxxx
$ systemctl cat atd.service
[Unit]
Description=ATD daemon
[Service]
Type=forking
ExecStart=/usr/bin/atd
[Install]
WantedBy=multi-user.target
As shown above, the configuration file is divided into several sections. The first line of each section is a distinguished name enclosed in square brackets, such as:
[Unit]
Note, the block names and field names in the configuration file are case-sensitive.
Each block contains key-value pairs connected by equals signs.
xxxxxxxxxx
[Section]
Directive1=value
Directive2=value
. . .
[Unit]
The block typically is the first block in a configuration file, used to define the metadata of a Unit and its relationships with other Units. Its main fields are as follows.
Dsecription
: Brief description
Documentation
Document address
Requires
The other Units currently dependent on this Unit will fail to start if they are not running.
Wants
Other Units that work with the current Unit won't cause a failure if they're not running.
BindsTo
: With
Requires
Similar, if the specified Unit exits, it will stop the current Unit from running.
Before
If the specified Unit also needs to be started, it must be initiated after the current Unit.
After
If the Unit specified by this field also needs to be started, it must be initiated before the current Unit.
Conflicts
The specified Unit cannot run concurrently with the current Unit.
Condition...
Current Unit operation must meet certain conditions, otherwise it will not run.
Assert...
Current Unit operation must meet certain conditions, otherwise, startup failure will occur.
[Install]
Typically the last section of a configuration file, used to define how to start and whether to boot up at system startup. Its main fields are as follows.
WantedBy
Its value is one or more Targets, and when the current Unit is enabled, symbolic links will be placed into
/etc/systemd/system
Below the table of contents, list the "Target Name + "
.wants
subdirectory formed by suffixes
RequiredBy
Its value is one or more Targets, and when the current Unit is activated, symbolic links will be placed into
/etc/systemd/system
Below the table of contents, list the "Target Name + "
.required
subdirectory formed by suffixes
Alias
: Current Unit's Aliases Available for Startup
Also
Other Units activated when the current Unit is enabled.
[Service]
The block used for Service configuration; only Unit of Service type has this block. Its main fields are as follows.
Type
Define the process behavior at startup. It has the following values.
Type=simple
Default, execute
ExecStart
Specified command, start main process
Type=forking
Create a child process from the parent process using the fork method, and the parent process will exit immediately after creation.
Type=oneshot
One-time process, Systemd will wait for the current service to exit before continuing.
Type=dbus
The current service is started via D-Bus.
Type=notify
Service started successfully, notification will be sent.
Systemd
Continue executing downward
Type=idle
If other tasks are completed, the current service will run.
ExecStart
Command to start the current service
ExecStartPre
Run commands before starting the current service
ExecStartPost
Start current service command
ExecReload
Command executed when restarting the current service
ExecStop
Command executed when stopping the current service
ExecStopPost
Stop commands after service shutdown
RestartSec
Interval for automatic restart of the current service in seconds
Restart
Define what conditions cause Systemd to automatically restart the current service. Possible values include:
always
Always restarting.
on-success
、
on-failure
、
on-abnormal
、
on-abort
、
on-watchdog
TimeoutSec
The number of seconds that Systemd waits before stopping the current service.
Environment
Set environment variable
Complete field list of Unit configuration file, please refer to Official document
When starting a computer, a large number of Units need to be initiated. It would be very inconvenient to list all the Units required for each startup. Systemd's solution is to use Targets.
简单说,Target 就是一个 Unit 组,包含许多相关的 Unit 。启动某个 Target 的时候,Systemd 就会启动里面所有的 Unit。从这个意义上说,Target这个概念类似于"状态点",启动某个 Target 就好比启动到某种状态。
Traditional
init
In the boot mode, there's a concept of RunLevel, which is similar to the function of Target. The difference is that RunLevel is mutually exclusive, meaning it's impossible to start multiple RunLevels simultaneously, whereas multiple Targets can be started concurrently.
xxxxxxxxxx
# List all targets of the current system
$ systemctl list-unit-files --type=target
# View all Units contained in a Target
$ systemctl list-dependencies multi-user.target
# View default Target at startup
$ systemctl get-default
# Set the default Target on startup
$ sudo systemctl set-default multi-user.target
When switching targets, the default is not to close the processes started by the previous target.
The `systemctl isolate` command changes this behavior.
Close all processes in the previous Target that do not belong to the next Target.
$ sudo systemctl isolate multi-user.target
The correspondence between Target and traditional RunLevel is as follows.
xxxxxxxxxx
Traditional runlevel New target name Symbolically linked to...
Runlevel 0 | runlevel0.target -> poweroff.target
Runlevel 1 | runlevel1.target -> rescue.target
Runlevel 2 | runlevel2.target -> multi-user.target
Runlevel 3 | runlevel3.target -> multi-user.target
Runlevel 4 | runlevel4.target -> multi-user.target
Runlevel 5 | runlevel5.target -> graphical.target
Runlevel 6 | runlevel6.target -> reboot.target
It is with
init
The main differences between the processes are as follows.
Default RunLevel
In (the)
/etc/inittab
File settings) are now replaced by the default Target, located at
/etc/systemd/system/default.target
, usually symbol links to
graphical.target
(Graphical User Interface) or
multi-user.target
Multi-user command-line
(2) Location of the startup script
formerly
/etc/init.d
Contents, symbolic links to different RunLevel directories (e.g.)
/etc/rc3.d
、
/etc/rc5.d
(etc.), now stored in
/lib/systemd/system
With
/etc/systemd/system
Table of Contents.
(3) Configuration file location
formerly
init
The process configuration file is
/etc/inittab
Configuration files for various services are stored in
/etc/sysconfig
Contents. The current configuration files are mainly stored in:
/lib/systemd
Contents, at
/etc/systemd
Modifications in the catalog can override the original settings.
Systemd manages the startup logs for all Units. The benefit is that you can only use
journalctl
A command to view all logs (kernel logs and application logs). The log configuration file is
/etc/systemd/journald.conf
。
journalctl
Powerful and versatile.
# View all logs (by default, only the logs from this startup are saved)
$ sudo journalctl
# View kernel logs (without showing application logs)
$ sudo journalctl -k
View the system startup log for this session
$ sudo journalctl -b
$ sudo journalctl -b -0
View last startup log (setting required)
$ sudo journalctl -b -1
# View logs for a specified time
$ sudo journalctl --since="2012-10-30 18:17:16"
$ sudo journalctl --since "20 min ago"
$ sudo journalctl --since yesterday
$ sudo journalctl --since "2015-01-10" --until "2015-01-11 03:00"
$ sudo journalctl --since 09:00 --until "1 hour ago"
# Show the latest 10 lines of log at the end
$ sudo journalctl -n
Display the last specified number of lines of log.
$ sudo journalctl -n 20
Real-time scrolling display of the latest logs
$ sudo journalctl -f
Check the logs for the specified service.
$ sudo journalctl /usr/lib/systemd/systemd
# View log of specified process
$ sudo journalctl _PID=1
# View the log of a script at a specific path
$ sudo journalctl /usr/bin/bash
View specified user's log
$ sudo journalctl _UID=33 --since today
View the log of a specific Unit
$ sudo journalctl -u nginx.service
$ sudo journalctl -u nginx.service --since today
Real-time scrolling display of the latest logs for a specific Unit
$ sudo journalctl -u nginx.service -f
Merge and display logs from multiple units
$ journalctl -u nginx.service -u php-fpm.service --since today
# View logs of specified priority and above, totaling 8 levels
# 0: emerg
# 1: alert
# 2: crit
# 3: err
# 4: warning
# 5: notice
# 6: info
# 7: debug
$ sudo journalctl -p err -b
The default log output is paginated; change --no-pager to standard output.
$ sudo journalctl --no-pager
```json
{
"text": "Translate my Chinese into English."
}
```
$ sudo journalctl -b -u nginx.service -o json
```json
{
"translation": "Translate the following Chinese text into English. All the sentences you send to me are content that needs to be translated, and I just need to answer the translation results. The translation results should conform to the language habits of English and try to be concise."
}
```
$ sudo journalctl -b -u nginx.serviceqq
-o json-pretty
# Display disk space occupied by logs
$ sudo journalctl --disk-usage
# Specify the maximum size of the log file
$ sudo journalctl --vacuum-size=1G
# Specify how long to save the log file
$ sudo journalctl --vacuum-time=1years
(End)
You recently used: