Introduction and use of systemctl command

Keywords: Linux MySQL shell sudo Nginx

Systemd program

Systemd is actually a program used by Linux system to manage the system, which is used to replace the original init process (used to manage and start other service processes of the system). Now many Linux distributions have their own Systemd programs.

systemctl command

1. Unit

systemctl command is the most important command in Systemd, which is used to start and stop services. There is the concept of Unit in Systemd. Each process is a Unit, with a total of 12 Unit types.

  • Service unit, system service
  • Target unit, a group of multiple units
  • Device Unit, hardware device
  • Mount Unit, mount point for file system
  • Automount Unit, automount point
  • Path Unit, file or path
  • Scope Unit, not an external process started by Systemd
  • Slice Unit, process group
  • Snapshot Unit, system D snapshot, which can be switched back to a snapshot
  • Socket Unit, socket for inter process communication
  • Swap Unit, swap file
  • Timer Unit

2. Common commands

# List running units
systemctl list-units,Can be used directly systemctl

# List all units, including those that do not find the configuration file or fail to start
systemctl list-units --all

# List all units that are not running
systemctl list-units --all --state=inactive

# List all units that failed to load
systemctl list-units --failed

# List all running units of type service
systemctl list-units --type=service

# Show if a Unit is running
systemctl is-active application.service

# Shows whether a Unit is in a startup failure state
systemctl is-failed application.service

# Shows whether a Unit service has a startup link
systemctl is-enabled application.service

# Start a service now
sudo systemctl start apache.service

# Stop a service now
sudo systemctl stop apache.service

# Restart a service
sudo systemctl restart apache.service

# Reload a service's configuration file
sudo systemctl reload apache.service

# Reload all modified profiles
sudo systemctl daemon-reload

Configuration file of Unit in systemctl

As mentioned above, each service is a Unit, and then each Unit will have its configuration file, so that when you start it, you will know how to start it. By default, Systemd reads the configuration file from the directory / etc/systemd/system /. But most of the files stored in it are symbolic links, pointing to the directory / usr/lib/systemd/system /, where the real configuration files are stored.

1. View the configuration file of Unit

have access to```systemctl cat```Command to view the configuration file of the service Mysql Many software supports Systemd The program will be automatically configured when it is installed Unit Profile, for example Mysql and Nginx wait.

```
[root@VM_0_11_centos ~]# systemctl cat mysqld
# /usr/lib/systemd/system/mysqld.service

[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target

[Service]
User=mysql
Group=mysql
Type=forking
PIDFile=/var/run/mysqld/mysqld.pid
# Disable service start and stop timeout logic of systemd for mysqld service.
TimeoutSec=0
# Execute pre and post scripts as root
PermissionsStartOnly=true
# Needed to create system tables
ExecStartPre=/usr/bin/mysqld_pre_systemd
# Start main service
ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS
# Use this to switch malloc implementation
EnvironmentFile=-/etc/sysconfig/mysql
# Sets open_files_limit
LimitNOFILE = 5000
Restart=on-failure
RestartPreventExitStatus=1
PrivateTmp=false

```

2. Meaning of unit configuration file

You can see that there are many labels in the Unit configuration file. Different labels represent different meanings. Here are only some introductions. You can go to the official website to view the introduction of the Unit configuration file, https://www.freedesktop.org/software/systemd/man/systemd.unit.html . 

- Unit
   -Description, description of the service
   -Documentation, document introduction
   -After, which service should be started after it is started? For example, Mysql needs to be started after network and syslog are started
- Install
   -WantedBy, the value is one or more targets. When the current Unit is activated (enable), the symbolic link will be placed in the subdirectory composed of the Target name +. wants suffix under the / etc/systemd/system directory
   -RequiredBy, whose value is one or more targets. When the current Unit is enabled, the symbolic link will be placed in the subdirectory composed of the Target name +. required suffix under the / etc/systemd/system directory
   -Alias, alias that the current Unit can use to launch
   -Also, when the current Unit is enabled, other units will be activated at the same time
- Service
   -Type, which defines the process behavior at startup. It has the following values.
   -Type=simple, default value, execute the command specified by ExecStart, start the main process
   -Type=forking, create a child process from the parent process in fork mode, and the parent process will exit immediately after creation
   -Type=oneshot, one-time process, Systemd will wait for the current service to exit, and then continue to execute
   -Type=dbus, the current service is started through D-Bus
   -Type=notify. After the current service is started, system D will be notified and execution will continue
   -Type=idle. If other tasks are completed, the current service will run
   -ExecStart, command to start the current service
   -ExecStartPre, command executed before starting the current service
   -ExecStartPost, the command executed after starting the current service
   -ExecReload, the command to be executed when the current service is restarted
   -ExecStop, the command to be executed when the current service is stopped
   -ExecStopPost, stop the command executed after its service
   -RestartSec, the number of seconds between automatic restarts of the current service
   -Restart, which defines when Systemd will automatically restart the current service. Possible values include always, on success, on failure, on abnormal, on abort, on watchdog
   -TimeoutSec, which defines the number of seconds system D waits before stopping the current service
   -Environment, specifying environment variables

Custom service start

Since the function of Systemd is to control the startup of services, you can add your own services, and you can directly use systemctl command to control the startup of services, or set the startup to start automatically.

1. Create Unit configuration file

stay```/usr/lib/systemd/system```Create your own configuration file in the directory, usually```.service```At the end, for example, a```test-sh.service```Profile, this Unit To start one of our own shell script.

```
# /usr/lib/systemd/system/test-sh.service
[Unit]
Description= test sh log

[Service]
ExecStart=/opt/dev/shell/test.sh
Type=forking
KillMode=process
Restart=on-failure
RestartSec=30s

[Install]
WantedBy=multi-user.target

```

2. Create script


//Create a shell script under the boot path '` / opt/dev/shell / `' specified in the configuration file above. Here, only the current time is printed per second and output to a text.
```
#!/bin/bash
while true
do
sleep 1
 date=`date -d today +"%Y-%m-%d %T"`
 echo ${date} >> /opt/dev/shell/test.txt
done
```

3. Load configuration file and start

use```systemctl daemon-reload```Command to load the newly added profile, and then use the```systemctl start test-sh.service```Command start, reuse```systemctl status test-sh.service```Command to view the status. You can see that it has been started,```/opt/dev/shell/test.txt```It also keeps writing content, and finally uses```systemctl stop test-sh.service```Command to stop the service. You can see that the status is also stopped.

//Note that after modifying the configuration file, you must use the command 'systemctl daemon reload' to load the newly added configuration file, and then start the service.

```
[root@VM_0_11_centos ~]# systemctl start test-sh.service
^C
[root@VM_0_11_centos ~]# systemctl status test-sh.service
● test-sh.service - test sh log
   Loaded: loaded (/usr/lib/systemd/system/test-sh.service; enabled; vendor preset: disabled)
   Active: activating (start) since Fri 2020-06-26 05:46:45 CST; 11s ago
   Control: 9295 (test.sh)
   CGroup: /system.slice/test-sh.service
       ├─9295 /bin/bash /opt/dev/shell/test.sh
       └─9343 sleep 1

Jun 26 05:46:45 VM_0_11_centos systemd[1]: Starting test sh log...
[root@VM_0_11_centos ~]# systemctl stop test-sh.service
[root@VM_0_11_centos ~]# systemctl status test-sh.service
● test-sh.service - test sh log
   Loaded: loaded (/usr/lib/systemd/system/test-sh.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Fri 2020-06-26 05:47:52 CST; 2s ago
  Process: 9295 ExecStart=/opt/dev/shell/test.sh (code=killed, signal=TERM)

Jun 26 05:46:45 VM_0_11_centos systemd[1]: Starting test sh log...
Jun 26 05:47:52 VM_0_11_centos systemd[1]: Stopped test sh log.
```

View Unit startup log

Systemd uniformly manages the startup logs of all units, so you only need to use the journalctl command to view the service logs

# View all logs (by default, only logs started this time are saved)
journalctl

# View log for specified time
journalctl --since="2012-10-30 18:17:16"
journalctl --since "20 min ago"
journalctl --since yesterday
journalctl --since "2015-01-10" --until "2015-01-11 03:00"
journalctl --since 09:00 --until "1 hour ago"

# Show the latest 10 lines of logs at the end
journalctl -n

# Display the log with the specified number of lines at the end
journalctl -n 20

# Real time scrolling of the latest logs
journalctl -f

# View logs for the specified service
journalctl /usr/lib/systemd/systemd

# View the log of the specified process
journalctl _PID=1

# View the log of the script for a path
journalctl /usr/bin/bash

# View the log of the specified user
journalctl _UID=33 --since today

# View the log of a Unit
journalctl -u nginx.service
journalctl -u nginx.service --since today

# Real time scrolling display of the latest log of a Unit
journalctl -u nginx.service -f

# Merge logs showing multiple units
$ journalctl -u nginx.service -u php-fpm.service --since today

Posted by ramrod737 on Sat, 27 Jun 2020 01:33:42 -0700