System CTL enables nginx processes to automatically restart after hanging up

 

Following the article on July 31, 2018:

vim /lib/systemd/system/nginx.service

 

[Service]
Restart=always
RestartSec=1
Type=forking
PIDFile=/run/nginx.pid

 

 systemctl daemon-reload

systemctl start nginx

After kill ing, the nginx will be automatically restarted.

------------------------------------------

If the original link is valid, please click on the original link to see.
Original: http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html

I. Origin

Historically, Startup of Linux Always adopted init Process.

The following command is used to start the service.

$ sudo /etc/init.d/apache2 start
# perhaps
$ service apache2 start

This method has two drawbacks.

First, the start-up time is long. The init process is started serially, and the next process will not start until the previous process has started.

Second, the startup script is complex. The init process simply executes the startup script, whatever else. The script needs to handle all kinds of situations by itself, which often makes the script very long.

II. Systemd Overview

Systemd was born to solve these problems. Its design goal is to provide a complete set of solutions for the start-up and management of the system.

According to Linux convention, the letter d is short for daemon. The name Systemd means that it guards the whole system.

With Systemd, you don't need init anymore. Systemd replaces initd as the first process of the system (PID equals 1), and all other processes are its sub-processes.

$ systemctl --version

The above command looks at the version of System D.

Systemd has the advantages of powerful function, easy to use, but the disadvantage is that the system is huge and complex. In fact, there are still many people who oppose the use of Systemd because it is too complex, strongly coupled with other parts of the operating system, and violates the "keep simple, keep flexible" Unix Philosophy.

(Systemd schematic diagram above)

3. System Management

System is not a command, but a set of commands, involving all aspects of system management.

3.1 systemctl

System CTL is the main command of System d, which is used in management system.

# reboot system now
$ sudo systemctl reboot

# Shut down the system and cut off the power supply
$ sudo systemctl poweroff

# CPU stops working
$ sudo systemctl halt

# Suspension system
$ sudo systemctl suspend

# Hibernate the system
$ sudo systemctl hibernate

# Let the system go to interactive sleep
$ sudo systemctl hybrid-sleep

# Start into Rescue State (Single User State)
$ sudo systemctl rescue

3.2 systemd-analyze

The system d-analysis command is used to view the startup time.

# Viewing startup time-consuming
$ systemd-analyze                                                                                       

# Viewing the startup time of each service
$ systemd-analyze blame

# Show a waterfall-like start-up process flow
$ systemd-analyze critical-chain

# Display the startup flow for the specified service
$ systemd-analyze critical-chain atd.service

3.3 hostnamectl

The hostname CTL command is used to view information about the current host.

# Display the information of the current host
$ hostnamectl

# Set the host name.
$ sudo hostnamectl set-hostname rhel7

3.4 localectl

The localectl command is used to view localization settings.

# View localization settings
$ localectl

# Set localization parameters.
$ sudo localectl set-locale LANG=en_GB.utf8
$ sudo localectl set-keymap en_GB

3.5 timedatectl

The timedatectl command is used to view the current time zone settings.

# View the current time zone settings
$ timedatectl

# Display all available time zones
$ timedatectl list-timezones                                                                                   

# Setting 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

3.6 loginctl

The loginctl command is used to view the currently logged-in user.

# List the current session
$ loginctl list-sessions

# List current logged-in users
$ loginctl list-users

# List the information that displays the specified user
$ loginctl show-user ruanyf

Unit

4.1 Meaning

Systemd can manage all system resources. Different resources are collectively called Unit.

Unit is divided into 12 kinds.

  • Service unit: System services
  • Target unit: A group of multiple units
  • Device Unit: Hardware Device
  • Mount Unit: Mount Point of File System
  • Automount Unit: Automatic Mount Point
  • Path Unit: File or Path
  • Scope Unit: An external process that is not initiated by System D
  • Slice Unit: Process Group
  • Snapshot Unit: System snapshot, you can cut back a snapshot
  • Socket Unit: socket for Interprocess Communication
  • Swap Unit: swap file
  • Timer Unit: Timer

The system CTL list-units command can view all Unit s of the current system.

# List Unit s that are running
$ systemctl list-units

# List all Unit s, including those that did not find the configuration file or failed to start
$ systemctl list-units --all

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

# List all Unit s that failed to load
$ systemctl list-units --failed

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

4.2 Unit Status

The system CTL status command is used to view the system status and the status of a single Unit.

# Display system status
$ systemctl status

# Display the status of a single Unit
$ sysystemctl status bluetooth.service

# Display the status of a Unit on a remote host
$ systemctl -H 7.example.com status httpd.service

In addition to the status command, system CTL provides three simple ways to query the status, mainly for the use of judgment statements within the script.

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

# Show whether a Unit is in a failed start state
$ systemctl is-failed application.service

# Show whether a Unit service has established a startup link
$ systemctl is-enabled application.service

4.3 Unit Management

For users, the following commands are most commonly used to start and stop Unit (mainly service).

# 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 the subprocesses of a service
$ sudo systemctl kill apache.service

# Reload the configuration file for a service
$ sudo systemctl reload apache.service

# Overload all modified configuration files
$ sudo systemctl daemon-reload

# Display all the underlying parameters of a Unit
$ systemctl show httpd.service

# Displays the value of a specified attribute of a Unit
$ systemctl show -p CPUShares httpd.service

# Setting the specified properties of a Unit
$ sudo systemctl set-property httpd.service CPUShares=500

4.4 Dependency

Unit has dependencies: A depends on B, which means that Systemd will start B while starting A.

The system CTL list-dependencies command lists all the dependencies of a Unit.

$ systemctl list-dependencies nginx.service

Among the output results of the above command, some dependencies are Target type (see below), which will not be expanded by default. If you want to expand Target, you need to use the -- all parameter.

$ systemctl list-dependencies --all nginx.service

V. Unit Configuration File

5.1 Overview

Each Unit has a configuration file that tells Systemd how to start the Unit.

Systemd reads configuration files from the directory / etc/systemd/system / by default. However, most of the files stored in it are symbolic links, pointing to the directory / usr / lib / system D / system /, where the real configuration files are stored.

The system CTL enable command is used to establish symbolic links between the above two directories.

$ sudo systemctl enable .service
# Equivalent to
$ sudo ln -s '/' '/'

If boot is set in the configuration file, the system CTL enable command is equivalent to activating boot.

Correspondingly, the system CTL disable command is used between two directories to revoke symbolic links, which is equivalent to revoking boot-up.

$ sudo systemctl disable .service

The suffix name of the configuration file is the type of Unit, such as sshd.socket. If omitted, the default suffix for System D is. service, so sshd is understood as sshd.service.

5.2 Configuration File Status

The system CTL list-unit-files command is used to list all configuration files.

# List all configuration files
$ systemctl list-unit-files

# List the configuration files of the specified type
$ systemctl list-unit-files --type=service

This command will output a list.

$ systemctl list-unit-files

UNIT FILE              STATE
chronyd.service        enabled
clamd@.service         static
.service     disabled

This list shows the status of each configuration file. There are four types.

  • enabled: A startup link has been established
  • Disad: No startup link was established
  • static: This configuration file has no [Install] section (cannot be executed) and can only be used as a dependency on other configuration files.
  • masked: This profile is forbidden to establish startup links

Note that the status of the configuration file does not tell whether the Unit is running. This must execute the system CTL status command mentioned earlier.

$ systemctl status bluetooth.service

Once you modify the configuration file, let System D reload the configuration file and restart it, otherwise the modification will not take effect.

$ sudo systemctl daemon-reload
$ sudo systemctl restart httpd.service

5.3 Configuration File Format

Configuration files are plain text files that can be opened with a text editor.

The system CTL cat command can view the contents of the configuration file.

$ systemctl cat atd.service

[Unit]
Description=ATD daemon

[Service]
Type=forking
ExecStart=/usr/bin/atd

[Install]
WantedBy=multi-user.target

As you can see from the output above, the configuration file is divided into several blocks. The first line of each block is a distinctive name in square brackets, such as [Unit]. Note that the block name and field name of the configuration file are case sensitive.

Inside each block are some key-value pairs of equal sign connections.

[Section]
Directive1=value
Directive2=value
. . .

Note that there should be no spaces on either side of the equals of the key pair.

Block of 5.4 Profile

The [Unit] block is usually the first block of the configuration file to define Unit metadata and the relationship between the configuration and other Units. Its main fields are as follows.

  • Description: A brief description
  • Documentation: Document address
  • Requires: Other Units currently relied on by Unit will fail to start if they are not running
  • Wants: Other Units that work with the current Unit will not fail to start if they are not running
  • BindsTo: Similar to Requires, the Unit specified by it will cause the current Unit to stop running if it exits
  • Before: If Unit specified in this field is to be started, it must be started after the current Unit
  • After: If the Unit specified in this field is to be started, it must be started before the current Unit
  • Conflicts: Unit specified here cannot run concurrently with the current Unit
  • Condition...: The current Unit operation must meet the conditions, otherwise it will not run.
  • Assert...: Conditions that must be met by the current Unit operation, otherwise the startup failure will be reported.

[Install] is usually the last block of the configuration file to define how to start and whether to start. Its main fields are as follows.

  • WantedBy: Its value is one or more Targets, and when Unit is currently activated (enable) symbolic links are placed in a subdirectory under the / etc/systemd/system directory with the Target name +. wants suffix
  • RequiredBy: Its value is one or more Targets, and when Unit is currently activated, symbolic links are placed in subdirectories under the / etc / system D / system directory with the Target name +. required suffix
  • Alias: Alias: Alias currently available for Unit startup
  • Also: When Unit is currently enable d, other Units will be activated at the same time

The [Service] block is used for service configuration, and only Unit of Service type has this block. Its main fields are as follows.

  • Type: Defines the process behavior at startup. It has the following values.
  • Type=simple: Default, execute the command specified by ExecStart, and start the main process
  • Type=forking: Create a child process from the parent process in fork mode, and the parent process exits immediately after creation
  • Type=oneshot: A one-time process, Systemd waits for the current service to exit and continue executing
  • Type=dbus: The current service is started through D-Bus
  • Type=notify: When the current service is started, Systemd is notified, and execution continues.
  • Type=idle: If other tasks are completed, the current service will run
  • ExecStart: The command to start the current service
  • ExecStartPre: Commands executed before starting the current service
  • ExecStartPost: Commands executed after starting the current service
  • ExecReload: Commands executed when restarting the current service
  • ExecStop: The command executed when stopping the current service
  • ExecStopPost: Stop commands executed after its service
  • RestartSec: Number of seconds to automatically restart the current service interval
  • Restart: Defines what conditions Systemd will automatically restart the current service, with possible values including always (always restart), on-success, on-failure, on-abnormal, on-abort, on-watchdog
  • TimeoutSec: Defines the number of seconds that Systemd waits before stopping the current service
  • Environment: Specify environment variables

For a complete list of fields in the Unit configuration file, see Official Documents.

VI. Target

When you start a computer, you need to start a lot of Units. If you start every time, you have to specify which Units you need to start this time, which is obviously very inconvenient. Systemd's solution is Target.

In short, Target is a Unit group that contains many related Units. When a Target is started, Systemd starts all Units in it. In this sense, the concept of Target is similar to "state point", and starting a Target is like starting to a certain state.

In the traditional init startup mode, there is the concept of RunLevel, which is very similar to Target's function. The difference is that RunLevel is mutually exclusive and it is impossible for multiple RunLevels to start at the same time, but multiple Targets can start at the same time.

# View all Target s of the current system
$ systemctl list-unit-files --type=target

# View all Unit s contained in a Target
$ systemctl list-dependencies multi-user.target

# View the default Target at startup
$ systemctl get-default

# Set the default Target at startup
$ sudo systemctl set-default multi-user.target

# When switching Target, the process started by the previous Target is not closed by default.
# The system CTL isolate command changes this behavior.
# Close all processes in the previous Target that do not belong to the latter
$ sudo systemctl isolate multi-user.target

The corresponding relationship between Target and traditional RunLevel is as follows.

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

The main differences between it and the init process are as follows.

(1) The default RunLevel (set in the / etc/inittab file) is now replaced by the default Target at / etc/systemd/system/default.target, usually symbolically linked to graphical.target (graphical interface) or multi-user.target (multi-user command line).

(2) The location of the startup script, formerly the / etc/init.d directory, is symbolically linked to different RunLevel directories (e.g. / etc/rc3.d, / etc/rc5.d, etc.), but now it is stored in the / lib/system d/system and / etc/system d/system directories.

(3) The location of the configuration file. The previous configuration file of init process is / etc/inittab. The configuration files of various services are stored in the / etc/sysconfig directory. The current configuration files are mainly stored in the / lib / system D directory. Modifications in the / etc / system D directory can override the original settings.

VII. Log Management

Systemd manages all Unit startup logs in a unified manner. The advantage is that you can view all the logs (kernel logs and application logs) with only one command from journalctl. The log configuration file is / etc / system D / journald. conf.

journalctl is powerful and has many uses.

# View all logs (by default, save only the logs for this boot)
$ sudo journalctl

# View the Kernel Log (no application log is displayed)
$ sudo journalctl -k

# View the log of this system boot
$ sudo journalctl -b
$ sudo journalctl -b -0

# View the last boot log (need to change settings)
$ sudo journalctl -b -1

# View the log for the 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"

# Display the latest 10-line logs at the tail
$ sudo journalctl -n

# A log showing the number of rows specified at the tail
$ sudo journalctl -n 20

# Real-time scrolling display of the latest logs
$ sudo journalctl -f

# View the log of the specified service
$ sudo journalctl /usr/lib/systemd/systemd

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

# View the logs of scripts for a path
$ sudo journalctl /usr/bin/bash

# View logs of specified users
$ sudo journalctl _UID=33 --since today

# View a Unit log
$ sudo journalctl -u nginx.service
$ sudo journalctl -u nginx.service --since today

# Real-time scrolling display of the latest logs for a Unit
$ sudo journalctl -u nginx.service -f

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

# View the logs for the specified priority (and above) for a total of eight levels
# 0: emerg
# 1: alert
# 2: crit
# 3: err
# 4: warning
# 5: notice
# 6: info
# 7: debug
$ sudo journalctl -p err -b

# Log default paging output, --no-pager changed to normal standard output
$ sudo journalctl --no-pager

# Output in JSON format (single line)
$ sudo journalctl -b -u nginx.service -o json

# With JSON format (multi-line) output, better readability
$ sudo journalctl -b -u nginx.serviceqq
 -o json-pretty

# Display the hard disk space occupied by the log
$ sudo journalctl --disk-usage

# Specify the maximum space occupied by log files
$ sudo journalctl --vacuum-size=1G

# Specify how long the log file will last
$ sudo journalctl --vacuum-time=1years

Keywords: PHP sudo Nginx Apache JSON

Added by Hoangsta on Wed, 12 Jun 2019 22:53:15 +0300