systemctl is the most commonly used systemd management tool. Its main commands are as follows:Command | Description |
status | View unit status. |
cat | View unit configuration. |
start/restart/stop | Control the current status of the unit. |
set-property | Set unit configurations, such as CPUAccounting and CPUShares. |
daemon-reload | Reload the manager configuration. |
list-units | List the units in the system and their statuses. |
list-dependencies | Display the dependencies between units in a tree diagram. |
enable/disable | Enable or disable unit startup on boot, which is equivalent to creating or deleting a symbolic link to the unit file under /etc/systemd/. |
mask/unmask | Similar to disable, but a service after mask cannot be started (even if required by other units), which is equivalent to creating a link to the unit file at /dev/null. |
journalctl is used to query systemd logs. Its common parameters are as follows:Parameter | Description |
-u | Query by unit |
-b | Display only logs from the current startup. |
-k | Display kernel-related logs. |
journalctl -u dbus.service
journalctl -b command can only view logs from the current boot. To query logs from previous boots, switch journald logs to disk storage (see the log management documentation), and then query them in the following ways:--list-boots parameter to list all boot records on the system:journalctl --list-boots
IDX column indicates the boot sequence number. Negative numbers represent historical boot records, and 0 represents the current boot:IDX BOOT ID FIRST ENTRY LAST ENTRY-9 9d27b37bc8014865b0c20c957429dc31 Wed 2023-01-18 15:44:22 HKT Fri 2023-02-24 10:27:36 HKT-8 aa28b72e95074434a4a81b623c400e7e Tue 2023-02-28 16:35:24 HKT Tue 2023-02-28 16:45:08 HKT-7 12a71bb5bd9d4dec993d0e03e0cbe636 Mon 2023-03-06 10:46:43 HKT Mon 2023-03-06 11:07:43 HKT...
IDX number to view logs from the corresponding boot. For example, to view logs from the boot with sequence number -8:journalctl -b -8
systemd-analyze is a system startup time analysis tool. Its main subcommands are as follows:Subcommand | Description |
blame | Analyze the startup time of each service in the system. |
plot | Graphically display the startup order of services in the system. The result can be opened through a web page or a graphical editor. |
dump | View the status and cgroup mask of each service, providing more details than systemctl status. |
blame command analyzes the startup time of each service during the current system boot. By default, it lists the services in descending order of startup time:systemd-analyze blame
8.814s kdump.service2.442s NetworkManager-wait-online.service944ms dev-vda1.device568ms sshd-keygen@rsa.service295ms initrd-switch-root.service214ms var-lib-nfs-rpc_pipefs.mount206ms dnf-makecache.service194ms dracut-initqueue.service143ms user@0.service135ms ipmi.service118ms initrd-parse-etc.service103ms chronyd.service99ms NetworkManager.service99ms systemd-logind.service92ms avahi-daemon.service88ms auditd.service71ms lvm2-monitor.service...
blame to conveniently troubleshoot system startup time. After identifying the time-consuming service, analyze the cause by examining its logs or using other troubleshooting methods. For example, in the output above, the kdump service has the longest startup time. The strace tool shows that its most time-consuming process is loading the kdump kernel.systemd-cgls is used to view the cgroup hierarchy on the system. Compared with viewing the cgroup directories directly, systemd-cgls lists the processes in each cgroup and presents the relationships between hierarchy levels more clearly:systemd-cgls
├─user.slice│ └─user-0.slice│ → user.invocation_id: 183a492473c94efe8e3c4b1e1745f0b0│ → trusted.invocation_id: 183a492473c94efe8e3c4b1e1745f0b0│ ├─33878 sshd: root [priv]│ ├─33892 sshd: root@pts/0│ ├─33893 -bash│ ├─35517 systemd-cgls│ └─35518 less│ └─user@0.service│ └─init.scope│ ├─33882 /usr/lib/systemd/systemd --user│ └─33885 (sd-pam)├─init.scope│ └─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 31└─system.slice├─rngd.service│ └─685 /usr/sbin/rngd -f -x pkcs11 -x nist├─irqbalance.service│ └─683 /usr/sbin/irqbalance --foreground
systemd-nspawn is similar to that of chroot, but the directory to enter must be in the form of an OS tree. If the directory is in the correct OS tree form, first view the directory contents to confirm:ls rootfs/
bin boot data dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var
systemd-nspawn:Directory /root/rootfs doesn't look like it has an OS tree (/usr/ directory is missing). Refusing.:systemd-nspawn -D ./rootfs
Spawning container rootfs on /root/rootfs.Press ^] three times within 1s to kill container.
-b option to start systemd in the container./usr/lib/systemd/system-preset/ and /usr/lib/systemd/user-preset/. The current system mainly has the following configuration files by default:File Name | Function |
90-default.preset | Control system services that start by default |
99-default-disable.preset | Disable all services by default |
85-display-manager.preset | Control whether desktop-related services require autostart |
99-default-disable.preset, you can still enable the required services in 90-default.preset and 85-display-manager.preset.service is the most commonly used unit type. It controls the running of processes on the system, including daemon processes, such as dbus.service and docker.service. Typically, ExecStart= specifies the action to start a program, ExecReload= specifies the action for systemctl reload, and ExecStop= specifies the action to stop the unit.systemctl cat to view the unit file configuration of dbus.service:systemctl cat dbus.service
[Unit], [Service], and [Install]:# /usr/lib/systemd/system/dbus-broker.service[Unit]Description=D-Bus System Message BusDocumentation=man:dbus-broker-launch(1)DefaultDependencies=falseAfter=dbus.socketBefore=basic.target shutdown.targetRequires=dbus.socketConflicts=shutdown.target[Service]Type=notifySockets=dbus.socketOOMScoreAdjust=-900LimitNOFILE=16384ProtectSystem=fullPrivateTmp=truePrivateDevices=trueExecStart=/usr/bin/dbus-broker-launch --scope system --auditExecReload=/usr/bin/busctl call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus ReloadConfig[Install]Alias=dbus.service
systemctl status to view the status information of a service and print the journal logs related to the service. The following uses the sshd service as an example:systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since Fri 2023-04-21 11:52:56 CST; 2 weeks 4 days agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 1208 (sshd)Tasks: 1 (limit: 9183)Memory: 8.7MCPU: 199msCGroup: /system.slice/sshd.service└─1208 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
Dot Color and Shape | Indicated Status |
"○" | inactive or maintenance |
"●" (green) | active |
"●" (white) | deactivating |
"×" | failed or error |
"↻" | reloading |
loaded means the service is loaded, error means loading failed, not-found means the unit file was not found, bad-setting means the unit file configuration is incorrect, and masked means the service is masked. The path that follows is the path of the loaded unit file, and the next field indicates whether the service is enabled to start at boot (enabled). vendor preset indicates whether the distribution vendor presets the service to start at boot.Status | Description |
active | The unit is running. |
inactive | The unit has stopped running. |
activating | The unit is starting. |
deactivating | The unit is stopping. |
failed | unit failed to start. |
Substatus | Description |
running | The unit is running. |
exited | The unit has stopped running. |
waiting | The unit is waiting for certain conditions to occur, such as network connections and file system mounts. |
start-pre | Pre-start preparation for the unit. |
start-post | Post-start tasks for the unit. |
stop-pre | Pre-stop preparation for the unit. |
stop-post | Post-stop tasks for the unit. |
timer is a timer that triggers and activates other units at fixed times (by default, the service with the same name). The trigger time is usually controlled by configuration items such as OnActiveSec=/OnCalendar= in the [Timer] section. For details, run man systemd.timer.*:00/10 configured in sysstat-collect means that the timer starts at the top of the hour and triggers every 10 minutes. Use systemctl cat to view its timer configuration:systemctl cat sysstat-collect.timer
OnCalendar=*:00/10 in the [Timer] section:# /usr/lib/systemd/system/sysstat-collect.timer# Activates activity collector every 10 minutes[Unit]Description=Run system activity accounting tool every 10 minutes[Timer]OnCalendar=*:00/10[Install]WantedBy=sysstat.service
systemctl status, you can see that a timer has two additional fields compared to a service: Trigger and Triggers. Trigger indicates the next trigger time and the remaining time, and Triggers shows the services activated by the timer. Check the status of sysstat-collect.timer:systemctl status sysstat-collect.timer
sysstat-collect.service, and it will be triggered again in 8 minutes.● sysstat-collect.timer - Run system activity accounting tool every 10 minutesLoaded: loaded (/usr/lib/systemd/system/sysstat-collect.timer; enabled; vendor preset: disabled)Active: active (waiting) since Thu 2023-05-11 20:04:47 CST; 1 week 0 days agoUntil: Thu 2023-05-11 20:04:47 CST; 1 week 0 days agoTrigger: Thu 2023-05-18 20:40:00 CST; 8min leftTriggers: ● sysstat-collect.service
mount is used to control mount points in the system. It usually controls the mount location, device, and type through Where=/What=/Type= in the [Mount] section. Under normal circumstances, you only need to configure /etc/fstab, and systemd-fstab-generator automatically generates the corresponding mount units from the mount points in fstab.systemctl cat to view the generated mnt.mount configuration:systemctl cat mnt.mount
systemd-fstab-generator, and its configuration corresponds to the mount entry in /etc/fstab:# /run/systemd/generator/mnt.mount# Automatically generated by systemd-fstab-generator[Unit]Documentation=man:fstab(5) man:systemd-fstab-generator(8)SourcePath=/etc/fstabBefore=local-fs.targetRequires=systemd-fsck@dev-vdb1.serviceAfter=systemd-fsck@dev-vdb1.serviceAfter=blockdev@dev-vdb1.target[Mount]What=/dev/vdb1Where=/mntType=ext4Options=noatime,acl,user_xattr
/etc/fstab:cat /etc/fstab
/dev/vdc1 is mounted to the /data/ directory:/dev/vdc1 /data/ ext4 noatime,acl,user_xattr 1 1
systemd-fstab-generator runs at startup, the corresponding mount service is generated in the system, and its configuration corresponds to the entry in fstab. First, use systemctl list-units to confirm that the mount service has been generated:systemctl list-units -a | grep data
data.mount has been loaded and is in the active state:data.mount loaded active mounted /data
systemctl cat data.mount
What, Where, Type, and Options in the configuration are consistent with those in /etc/fstab:# /run/systemd/generator/data.mount# Automatically generated by systemd-fstab-generator[Unit]Documentation=man:fstab(5) man:systemd-fstab-generator(8)SourcePath=/etc/fstabBefore=local-fs.targetRequires=systemd-fsck@dev-vdc1.serviceAfter=systemd-fsck@dev-vdc1.serviceAfter=blockdev@dev-vdc1.target[Mount]What=/dev/vdc1Where=/dataType=ext4Options=noatime,acl,user_xattr
automount is similar to mount. The difference is that automount mounts a directory only when a user accesses it, rather than remaining mounted since startup like mount. You can use the automount capability through autofs. The following example describes how to use the automount service.dnf install -y autofs
/etc/auto.master file.vim /etc/auto.master
/mnt/ /etc/auto.devices --timeout=10
/mnt/ is the path where the mount point resides (not the device mount point), /etc/auto.devices is the path to the device mount configuration file, and --timeout=10 indicates that the device mount timeout is 10 seconds./etc/auto.devices file.vim /etc/auto.devices
mymnt -fstype=auto :/dev/vdb
mymnt is the mounted directory, -fstype=auto indicates automatic detection of the device file system type, and :/dev/vdb is the device path.systemctl restart autofs
mymnt device, access the mymnt directory under /mnt/, and the automount service automatically mounts the /dev/vdb device to that directory./mnt directory is entered, the mymnt directory is not visible and cannot be auto-completed with Tab, but it can still be accessed directly.cd /mnt/mymnt
/mnt/mymnt directory, the automount service automatically mounts the /dev/vdb device to that directory. Use the lsblk command to check the mount status:lsblk
/dev/vdb has been mounted to /mnt/mymnt:NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTSsr0 11:0 1 18.8M 0 romzram0 251:0 0 8G 0 disk [SWAP]vda 252:0 0 100G 0 disk└─vda1 252:1 0 100G 0 part /vdb 252:16 0 200G 0 disk /mnt/mymntvdc 252:32 0 300G 0 disk└─vdc1 252:33 0 300G 0 part /data
target unit does not perform any operations itself but represents a group of units. A target controls the dependencies and startup order of each unit in the group through unit dependency configurations such as Requires=/After=, which can be viewed using systemctl list-dependencies. Take multi-user.target as an example:systemctl list-dependencies multi-user.target
multi-user.target● ├─acpid.service● ├─arpwatch.service● ├─atd.service● ├─auditd.service● ├─avahi-daemon.service● ├─chrony-wait.service● ├─chronyd.service● ├─crond.service● ├─gssproxy.service
default.target (multi-user.target or graphical.target in this system) needs to be started at startup, and the other targets only need to be specified in their unit files:[Install]WantedBy=multi-user.target
multi-user.target starts.path unit is similar to a timer unit. Its main purpose is to trigger the service with the same name when the monitored path changes. The monitored path and corresponding mode are controlled by configuration items such as DirectoryNotEmpty=/PathChanged= in the [Path] section.systemctl cat to view the built-in systemd-ask-password-console.path configuration:systemctl cat systemd-ask-password-console.path
/run/systemd/ask-password directory is monitored through DirectoryNotEmpty= in the [Path] section:# /usr/lib/systemd/system/systemd-ask-password-console.path[Unit]Description=Dispatch Password Requests to Console Directory WatchDocumentation=man:systemd-ask-password-console.path(8)DefaultDependencies=noConflicts=shutdown.target emergency.serviceAfter=plymouth-start.serviceBefore=paths.target shutdown.target cryptsetup.targetConditionPathExists=!/run/plymouth/pid[Path]DirectoryNotEmpty=/run/systemd/ask-passwordMakeDirectory=yes
.path unit file.my-path-monitor.path file in the /etc/systemd/system directory, and define the path to monitor and the trigger condition:[Unit]Description=Monitor changes in /data/testpath directory[Path]PathModified=/data/testpathUnit=my-triggered-service.service[Install]WantedBy=multi-user.target
.path unit file monitors changes in the /data/testpath directory. When the directory changes, the service named my-triggered-service.service is triggered.my-triggered-service.service file in the /etc/systemd/system directory, and define the service behavior:[Unit]Description=Service triggered by path changes[Service]Type=oneshotExecStart=/usr/bin/echo "123"
echo 123 when the .path unit is triggered.systemctl daemon-reload
.path unit.systemctl start my-path-monitor.path
rm -r /data/testpath
my-triggered-service.service. The service has been triggered by the path service:systemctl status my-triggered-service.service
inactive (dead) indicates that execution is complete:○ my-triggered-service.service - Service triggered by path changesLoaded: loaded (/etc/systemd/system/my-triggered-service.service; static)Active: inactive (dead) since Mon 2023-05-29 03:09:15 UTC; 9s agoTriggeredBy: ● my-path-monitor.pathProcess: 1227670 ExecStart=/usr/bin/echo 123 (code=exited, status=0/SUCCESS)Main PID: 1227670 (code=exited, status=0/SUCCESS)CPU: 1msMay 29 03:09:15 localhost.localdomain systemd[1]: Starting my-triggered-service.service - Service triggered by path changes...May 29 03:09:15 localhost.localdomain echo[1227670]: 123May 29 03:09:15 localhost.localdomain systemd[1]: my-triggered-service.service: Deactivated successfully.May 29 03:09:15 localhost.localdomain systemd[1]: Finished my-triggered-service.service - Service triggered by path changes.
socket unit, like timer/path units, is used together with a service unit. You can use a socket unit to specify the socket that systemd listens on. When data is written to the socket, systemd wakes up the corresponding service unit.systemctl cat to view the configuration of the acpid service and its socket:systemctl cat acpid acpid.socket
Requires=acpid.socket, and the socket unit specifies the listening address through ListenStream=/run/acpid.socket:# /usr/lib/systemd/system/acpid.service[Unit]Description=ACPI Event DaemonDocumentation=man:acpid(8)Requires=acpid.socket[Service]StandardInput=socketEnvironmentFile=/etc/sysconfig/acpidExecStart=/usr/sbin/acpid -f $OPTIONS[Install]Also=acpid.socketWantedBy=multi-user.target# /usr/lib/systemd/system/acpid.socket[Unit]Description=ACPID Listen SocketDocumentation=man:acpid(8)[Socket]ListenStream=/run/acpid.socket[Install]WantedBy=sockets.target
dnf install nc -y
socket_server.service file in the /etc/systemd/system directory:[Unit]Description=Socket Server[Service]ExecStart=nc -l 12345User=nobodyGroup=nobody
socket_server.socket file in the /etc/systemd/system directory:[Unit]Description=Socket Server Socket[Socket]ListenStream=12345Accept=yes[Install]WantedBy=sockets.target
.socket unit file creates a TCP socket on port 12345 and activates socket_server.service when a connection request is received.systemctl daemon-reload
.socket unit.systemctl start socket_server.socket
socket_server.service is activated and runs nc -l 12345.telnet or nc (netcat) to connect to port 12345:telnet localhost 12345
swap unit manages swap partition mounting. Similar to mount, it is usually configured through /etc/fstab and automatically generated by systemd-fstab-generator.fallocate -l 1G /swapfile
mkswap /swapfile
/etc/fstab file./etc/fstab file to specify the path to the swap partition or file, the mount point (use none), the file system type (use swap), and the mount options (use sw). Finally, add two numbers 0 0 to indicate that no file system check is required:/swapfile none swap sw 0 0
systemctl list-units to check the swap service status:systemctl list-units -a | grep swap
swapfile.swap has been loaded and is in the active state:swapfile.swap loaded active active /swapfile
free -h or swapon --show command to check the swap status:free -h
total used free shared buff/cache availableMem: 7.5Gi 195Mi 7.1Gi 9Mi 210Mi 7.1GiSwap: 1.0Gi 0B 1.0Gi
device unit is created by systemd-udevd based on devices under /sys/ and /dev/. Its primary purpose is to control dependencies between devices and between devices and other units.systemctl list-dependencies to view the dependencies of mnt.mount. You can see that it includes dev-vdb1.device:systemctl list-dependencies mnt.mount
mnt.mount depends on the corresponding block device unit dev-vdb1.device:mnt.mount● ├─-.mount● ├─dev-vdb1.device● ├─system.slice○ └─systemd-fsck@dev-vdb1.service
slice is similar to a target and also represents a group of units, but a slice is used for resource control in cgroups. By default, the system divides units into user.slice (user sessions), system.slice (system processes), and machine.slice (container and virtual machine processes).tree command to view the cgroup hierarchy on the system:tree -d /sys/fs/cgroup/
system.slice and user.slice respectively:/sys/fs/cgroup/├── dev-hugepages.mount├── dev-mqueue.mount├── init.scope├── proc-fs-nfsd.mount├── proc-sys-fs-binfmt_misc.mount├── sys-fs-fuse-connections.mount├── sys-kernel-config.mount├── sys-kernel-debug.mount├── sys-kernel-tracing.mount├── system.slice│ ├── NetworkManager.service│ ├── acpid.service│ ├── arpwatch.service│ ├── atd.service│ ├── auditd.service│ ├── avahi-daemon.service│ ├── chronyd.service│ ├── systemd-logind.service│ ├── systemd-udevd.service│ │ └── udev│ ├── systemd-userdbd.service│ ├── tmp.mount│ └── var-lib-nfs-rpc_pipefs.mount└── user.slice└─user-0.slice├── session-1702.scope├── session-22304.scope
scope is similar to a slice/target, but a scope unit can only be created through the systemd dbus interface, and processes in a scope unit do not create child processes on their own.ConfigTableItem, and all configuration items in the table have default initial values. If no manual configuration is performed later, these properties will use the initial values from the code. For example, CPUAccounting defaults to false. You can view them in the src/core/main.c file:static int parse_config_file(void) {const ConfigTableItem items[] = {{ "Manager", "LogLevel", config_parse_level2, 0, NULL },{ "Manager", "LogTarget", config_parse_target, 0, NULL },.....
/etc/systemd/system.conf/etc/systemd/user.conf/etc/systemd/system.conf.d//etc/systemd/user.conf.d/
/usr/lib/systemd/system/. You can use systemctl cat a.service to view its specific content. When you manually set properties using the systemctl set-property command, an additional configuration file for the corresponding unit is eventually generated under /etc/systemd/.rsyslog.service as an example, use systemctl set-property to set the CPU quota to 50%:systemctl set-property rsyslog.service CPUQuota=50%
systemctl show to view the configuration path of this property:systemctl show rsyslog.service | grep CPUQuota
DropInPaths points to the path of the automatically generated configuration file:DropInPaths=/etc/systemd/system.control/rsyslog.service.d/50-CPUQuota.conf
/etc/systemd/system.control/rsyslog.service.d/50-CPUQuota.conf. View the content of this file:cat /etc/systemd/system.control/rsyslog.service.d/50-CPUQuota.conf
CPUQuota=50% configuration that was set through set-property:# This is a drop-in unit file extension, created via "systemctl set-property"# or an equivalent operation. Do not edit.[Service]CPUQuota=50%
Type and Unit configuration. For example, dbus.service with Type=dbus implicitly depends on dbus.socket (equivalent to Requires= and After=dbus.socket).DefaultDependencies= option. For example, if Wants= or Requires=B is configured in A.target, A is configured with an After=B by default. All targets are configured with Conflicts=shutdown.target and Before=shutdown.target by default to ensure that all targets have exited before shutdown. Triggers/TriggeredBy are configured by default in the corresponding services such as socket/path/mount.Dependencies | Description |
Wants/WantedBy | Weak dependency. If A Wants= B, A attempts to start B when A starts. If B fails to start, A continues to start. The same effect can also be achieved by creating a .wants directory outside the unit file. |
Requires/RequiredBy | Strong dependency. If A Requires= B, A attempts to start B when A starts. If B fails to start, A will not start. The same effect can also be achieved by creating a .requires/ directory. |
BindsTo/BoundBy | Stronger dependency. Unlike Requires, if A BindsTo= B and A is stopped, B is also stopped, whereas with Requires, B is not affected. |
Before/After | Startup order. If A Before= B, B can start only after A starts. The shutdown process is reversed: if A Before= B and both A and B need to be shut down, B shuts down first, and only then does A shut down. |
PartOf/ConsistsOf | Similar to Requires, but PartOf only affects shutdown and restart operations. If A PartOf= B, when B is shut down or restarted, A is also shut down or restarted. |
Conflicts/ConflictedBy | If A Conflicts= B, starting A stops B. |
--reverse option of the list-dependencies command to view reverse dependencies:systemctl list-dependencies rsyslog --reverse
rsyslog.service is started by multi-user.target, and multi-user.target is in turn started by graphical.target:rsyslog.service● └─multi-user.target○ └─graphical.target
systemctl cat to view its configuration:systemctl cat rsyslog.service
[Install] section through WantedBy=multi-user.target:# /usr/lib/systemd/system/rsyslog.service[Unit]...[Install]WantedBy=multi-user.target...
フィードバック