Introduction to Systemd: Practice

Source: Internet
Author: User
Tags openssh server ssh server

Introduction to Systemd: Practice

Getting started with Systemd: Practice

In the previous article, we introduced the main Commands of Systemd. This article mainly describes how to use Systemd to manage our services and their meanings;

I. boot

For software that supports Systemd, a configuration file is automatically added to the/usr/lib/systemd/system directory during installation. If you want the software to start up, run the following command (using httpd. service ).

$ sudo systemctl enable httpd

The above command is equivalent to adding a symbolic link to the/etc/systemd/system directory, pointing to the httpd. service file in/usr/lib/systemd/system.

This is because when the instance is started, Systemd only executes the configuration file in the/etc/systemd/system directory. This also means that if you put the modified configuration file in this directory, You can overwrite the original configuration.

Ii. Start the service

After the startup is enabled, the software will not start immediately. You must wait until the next boot. If you want to run the software now, run the systemctl start command.

$ sudo systemctl start httpd

After the preceding command is executed, startup may fail. Therefore, run the systemctl status Command to check the status of the service.

$ Sudo systemctl status httpdhttpd. service-The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd. service; enabled) Active: active (running) since 12:18:22 JST; 7 min ago Main PID: 4349 (httpd) Status: "Total requests: 1; Current requests/sec: 0; Current traffic: 0 B/sec "CGroup:/system. slice/httpd. service Charge-4349/usr/sbin/httpd-DFOREGROUND limit-4350/usr/sbin/httpd-DFOREGROUND limit-4351/usr/sbin/httpd-DFOREGROUND limit-4352/usr/ sbin/httpd-DFOREGROUND limit-4353/usr/sbin/httpd-DFOREGROUND limit-4354/usr/sbin/httpd-DFOREGROUND December 05 12:18:22 localhost. localdomain systemd [1]: Starting The Apache HTTP Server... december 05 12:18:22 localhost. localdomain systemd [1]: Started The Apache HTTP Server. December 05 12:22:40 localhost. localdomain systemd [1]: Started The Apache HTTP Server.

The output result is as follows:

Loaded row: Specifies the location of the configuration file. If it is set to enable the Active row upon startup, it indicates that the Main PID line is running: Main Process IDStatus line: application itself (httpd here) the Current Status CGroup block of the provided software: All sub-process log blocks of the application: application logs
3. Stop services

To terminate a running service, run the systemctl stop command.

$ sudo systemctl stop httpd.service

Sometimes, the command may not respond and the service cannot be stopped. At this time, we had to "kill the process" and send a kill signal to the running process.

$ sudo systemctl kill httpd.service

In addition, to restart the service, run the systemctl restart command.

$ sudo systemctl restart httpd.service
4. Read the configuration file

The configuration file determines how a service is started. The following describes what the configuration file contains.

As mentioned above, the configuration file is mainly stored in the/usr/lib/systemd/system directory, or in the/etc/systemd/system directory. Find the configuration file and use the text editor to open it.

The systemctl cat command can be used to view the configuration file. The following uses the sshd. service file as an example. It is used to start an SSH server for other users to log on via SSH.

$ systemctl cat sshd.service[Unit]Description=OpenSSH server daemonDocumentation=man:sshd(8) man:sshd_config(5)After=network.target sshd-keygen.serviceWants=sshd-keygen.service[Service]EnvironmentFile=/etc/sysconfig/sshdExecStart=/usr/sbin/sshd -D $OPTIONSExecReload=/bin/kill -HUP $MAINPIDType=simpleKillMode=processRestart=on-failureRestartSec=42s[Install]WantedBy=multi-user.target

As you can see, the configuration file is divided into several blocks, each of which contains several key-value pairs. The following describes the content of each block in sequence.

V. [Unit] Block: startup sequence and dependency

The Description field in the Unit block provides a brief Description of the current service, and the Documentation field provides the document location.

The following settings are the startup sequence and dependency, which are important.

After field: required if network.tar get or sshd-keygen.service needs to be started, sshd. service should be started After them.
Correspondingly, there is also a Before field that defines the services Before which sshd. service should be started.

Note that the After and Before fields only involve the startup sequence and do not involve dependencies.

For example, a Web application requires a postgresql database to store data. In the configuration file, it only defines to start after postgresql, but does not define to depend on postgresql. After the service is launched, postgresql needs to be restarted for some reason. when the service is stopped, the Web application cannot establish a database connection.

To set the dependency, use the Wants field and Requires field.

Wants field: represents a weak dependency between the sshd. service and the sshd-keygen.service, that is, if the sshd-keygen.service fails to start or stops running, sshd. service continues to run.
The Requires field indicates a "strong dependency" relationship, that is, if the service fails to start or exits unexpectedly, sshd. service must also exit.

Note that the Wants field and Requires field only involve dependencies and are irrelevant to the startup sequence. By default, they are started at the same time.

6. [Service] Block: startup Behavior

The Service block defines how to start the current Service.

6.1 start command

Many software programs have their own environment parameter files, which can be read using the EnvironmentFile field.

EnvironmentFile field: Specifies the environment parameter file of the current service. The key = value key-value pair in the file can be obtained in the form of $ key in the current configuration file.

In the above example, the sshd environment parameter file is/etc/sysconfig/sshd.

ExecStart is the most important field in the configuration file.

ExecStart field: defines the commands executed when the process is started.

In the preceding example, the command to start sshd is/usr/sbin/sshd-D $ OPTIONS. The variable $ OPTIONS comes from the environment parameter file specified by the EnvironmentFile field.

Similar to this, the following fields are also used.

ExecReload field: ExecStop field of the Command executed when the service is restarted: ExecStartPre field of the Command executed when the service is stopped: ExecStartPost field of the Command executed before the service is started: ExecStopPost field of the Command executed after the service is started: command executed after the service is stopped

See the following example.

[Service]ExecStart=/bin/echo execstart1ExecStart=ExecStart=/bin/echo execstart2ExecStartPost=/bin/echo post1ExecStartPost=/bin/echo post2

In the preceding configuration file, ExecStart in the second line is set to null, which is equal to canceling the settings in the first line. The running result is as follows.

execstart2post1post2

Before all the startup settings, you can add a hyphen (-) to indicate "suppressing errors". That is, when an error occurs, the execution of other commands is not affected. For example, EnvironmentFile =-/etc/sysconfig/sshd (pay attention to the conjunction number after the equal sign) means that even if the/etc/sysconfig/sshd file does not exist, no error will be thrown.

6.2 start Type

The Type field defines the Startup Type. You can set the following values.

Simple (default): the process started in the ExecStart field is the main process. The forking: ExecStart field is started in the fork () mode. At this time, the parent process will exit, and the child process will become the main process oneshot: similar to simple, but only once, Systemd starts other services only after it is executed: similar to simple, but will wait until the D-Bus signal starts notify: similar to simple, after the service is started, a notification is sent, and then Systemd starts other service idle: similar to simple, but the service will be started until all other tasks are completed. One application scenario is to make the output of the service not mixed with the output of other services.

The following is an oneshot example. When a laptop is started, you must turn off the touchpad. The configuration file can be written in this way.

[Unit]Description=Switch-off Touchpad[Service]Type=oneshotExecStart=/usr/bin/touchpad-off[Install]WantedBy=multi-user.target

In the preceding configuration file, the Startup type is set to oneshot, which indicates that this service only needs to run once and does not need to run for a long time.

If you want to open the configuration file at a later time after it is disabled, modify the configuration file as follows.

[Unit]Description=Switch-off Touchpad[Service]Type=oneshotExecStart=/usr/bin/touchpad-off startExecStop=/usr/bin/touchpad-off stopRemainAfterExit=yes[Install]WantedBy=multi-user.target

In the preceding configuration file, the RemainAfterExit field is set to yes, indicating that the service is still executed after the process exits. In this case, once the systemctl stop command is used to stop the service, the command specified by ExecStop will be executed, and the touchpad will be re-enabled.

6.3 restart

The Service block has some fields that define the restart behavior.

KillMode field: defines how Systemd stops the sshd service.

In the preceding example, if KillMode is set to process, only the master process is stopped and no sshd sub-process is stopped. That is, the SSH session opened by the sub-process is still connected. This setting is not very common, but it is very important for sshd. Otherwise, when you stop the service, it will be killed together with the SSH session opened by yourself.

The following values can be set for the KillMode field.

Control-group (default): All Sub-processes in the current control group will be killed. process: only the main process mixed is killed. The main process will receive the SIGTERM signal, and the sub-process will receive the SIGKILL Signal none: no process is killed, but the stop command of the service is executed.

Next is the Restart field.

Restart field: defines the Restart mode of Systemd after sshd exits.
In the above example, if Restart is set to on-failure, sshd will be restarted if any unexpected failure occurs. If sshd stops normally (for example, execute the systemctl stop command), it will not restart.

The Restart field can be set as follows.

No (default): on-success will not be restarted after exit: on-failure will be restarted only when the exit status code is 0: during abnormal exit (the exit status code is not 0), including the signal termination and timeout, The on-abnormal will be restarted. Only when the signal is terminated or timed out will the on-abort be restarted: only when the uncaptured signal is terminated will the on-watchdog be restarted: timed out and always be restarted: always restarted for whatever reason

We recommend that you set the daemon to on-failure. For services that are allowed to exit with an error, you can set it to on-abnormal.

The last is the RestartSec field.

RestartSec field: the number of seconds that need to be waited before Systemd restarts the service. In the preceding example, wait for 42 seconds.
VII. [Install] Block

The Install block defines how to Install this configuration file, that is, how to enable startup.

WantedBy field: indicates the Target of the service.

Target indicates a service group, indicating a group of services. Wantedbypolicmulti user.tar get indicates that the Target of sshd is Multi user.tar get.

This setting is very important, because when executing the systemctl enable sshd. service command, a symbolic link of sshd. service will be placed in the Multi user.tar get. wants subdirectory under the/etc/systemd/systemdirectory.

Systemd has the default start Target.

$ systemctl get-defaultmulti-user.target

The above result indicates that the default start Target is Multi user.tar get. All services in this group will be started. This is why the systemctl enable command can be set to boot.

The systemctl list-dependencies command and the systemctl isolate command are also useful when Target is used.

# View all services included in the multi-user.target $ systemctl list-dependencies multi-user.target # switch to another target # shutdown.tar get is shutdown status $ sudo systemctl isolate shutdown.tar get

In general, there are two commonly used targets: one is Multi user.target, and the other is graphical.target, which depends on multi user.tar get. The official document provides a clear Target dependency diagram.

8. Target configuration file

Target also has its own configuration file.

$ systemctl cat multi-user.target[Unit]Description=Multi-User SystemDocumentation=man:systemd.special(7)Requires=basic.targetConflicts=rescue.service rescue.targetAfter=basic.target rescue.service rescue.targetAllowIsolate=yes

Note: The Target configuration file does not contain the start command.

The main fields in the output result are as follows.

Requires field: Run basic.tar get together. Conflicts field: Conflict field. If rescue.serviceor rescue.targetis running, multi user.tar get cannot run, and vice versa. After: Export multi-user.targetis started After basic.tar get, rescue. service, and rescue.tar get, if they have been started. AllowIsolate: allows the use of the systemctl isolatecommand to switch to multi user.tar get.
9. modify the configuration file and restart

After modifying the configuration file, you need to reload the configuration file and restart the relevant services.

# Reload the configuration file $ sudo systemctl daemon-reload # restart related services $ sudo systemctl restart foobar

Original article from: http://www.ruanyifeng.com /... /Systemd-tutorial-part-two.html Author: Ruan Yifeng

Address: http://www.codeceo.com/article/systemd-coding.html

Address: http://www.linuxprobe.com/systemd-bestry-artikel.html


In the previous article, we introduced the main Commands of Systemd. This article mainly describes how to use Systemd to manage our services and their meanings;

I. boot

For software that supports Systemd, a configuration file is automatically added to the/usr/lib/systemd/system directory during installation. If you want the software to start up, run the following command (using httpd. service ).

$ sudo systemctl enable httpd

The above command is equivalent to adding a symbolic link to the/etc/systemd/system directory, pointing to the httpd. service file in/usr/lib/systemd/system.

This is because when the instance is started, Systemd only executes the configuration file in the/etc/systemd/system directory. This also means that if you put the modified configuration file in this directory, You can overwrite the original configuration.

Ii. Start the service

After the startup is enabled, the software will not start immediately. You must wait until the next boot. If you want to run the software now, run the systemctl start command.

$ sudo systemctl start httpd

After the preceding command is executed, startup may fail. Therefore, run the systemctl status Command to check the status of the service.

$ Sudo systemctl status httpdhttpd. service-The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd. service; enabled) Active: active (running) since 12:18:22 JST; 7 min ago Main PID: 4349 (httpd) Status: "Total requests: 1; Current requests/sec: 0; Current traffic: 0 B/sec "CGroup:/system. slice/httpd. service Charge-4349/usr/sbin/httpd-DFOREGROUND limit-4350/usr/sbin/httpd-DFOREGROUND limit-4351/usr/sbin/httpd-DFOREGROUND limit-4352/usr/ sbin/httpd-DFOREGROUND limit-4353/usr/sbin/httpd-DFOREGROUND limit-4354/usr/sbin/httpd-DFOREGROUND December 05 12:18:22 localhost. localdomain systemd [1]: Starting The Apache HTTP Server... december 05 12:18:22 localhost. localdomain systemd [1]: Started The Apache HTTP Server. December 05 12:22:40 localhost. localdomain systemd [1]: Started The Apache HTTP Server.

The output result is as follows:

Loaded row: Specifies the location of the configuration file. If it is set to enable the Active row upon startup, it indicates that the Main PID line is running: Main Process IDStatus line: application itself (httpd here) the Current Status CGroup block of the provided software: All sub-process log blocks of the application: application logs
3. Stop services

To terminate a running service, run the systemctl stop command.

$ sudo systemctl stop httpd.service

Sometimes, the command may not respond and the service cannot be stopped. At this time, we had to "kill the process" and send a kill signal to the running process.

$ sudo systemctl kill httpd.service

In addition, to restart the service, run the systemctl restart command.

$ sudo systemctl restart httpd.service
4. Read the configuration file

The configuration file determines how a service is started. The following describes what the configuration file contains.

As mentioned above, the configuration file is mainly stored in the/usr/lib/systemd/system directory, or in the/etc/systemd/system directory. Find the configuration file and use the text editor to open it.

The systemctl cat command can be used to view the configuration file. The following uses the sshd. service file as an example. It is used to start an SSH server for other users to log on via SSH.

$ systemctl cat sshd.service[Unit]Description=OpenSSH server daemonDocumentation=man:sshd(8) man:sshd_config(5)After=network.target sshd-keygen.serviceWants=sshd-keygen.service[Service]EnvironmentFile=/etc/sysconfig/sshdExecStart=/usr/sbin/sshd -D $OPTIONSExecReload=/bin/kill -HUP $MAINPIDType=simpleKillMode=processRestart=on-failureRestartSec=42s[Install]WantedBy=multi-user.target

As you can see, the configuration file is divided into several blocks, each of which contains several key-value pairs. The following describes the content of each block in sequence.

V. [Unit] Block: startup sequence and dependency

The Description field in the Unit block provides a brief Description of the current service, and the Documentation field provides the document location.

The following settings are the startup sequence and dependency, which are important.

After field: required if network.tar get or sshd-keygen.service needs to be started, sshd. service should be started After them.
Correspondingly, there is also a Before field that defines the services Before which sshd. service should be started.

Note that the After and Before fields only involve the startup sequence and do not involve dependencies.

For example, a Web application requires a postgresql database to store data. In the configuration file, it only defines to start after postgresql, but does not define to depend on postgresql. After the service is launched, postgresql needs to be restarted for some reason. when the service is stopped, the Web application cannot establish a database connection.

To set the dependency, use the Wants field and Requires field.

Wants field: represents a weak dependency between the sshd. service and the sshd-keygen.service, that is, if the sshd-keygen.service fails to start or stops running, sshd. service continues to run.
The Requires field indicates a "strong dependency" relationship, that is, if the service fails to start or exits unexpectedly, sshd. service must also exit.

Note that the Wants field and Requires field only involve dependencies and are irrelevant to the startup sequence. By default, they are started at the same time.

6. [Service] Block: startup Behavior

The Service block defines how to start the current Service.

6.1 start command

Many software programs have their own environment parameter files, which can be read using the EnvironmentFile field.

EnvironmentFile field: Specifies the environment parameter file of the current service. The key = value key-value pair in the file can be obtained in the form of $ key in the current configuration file.

In the above example, the sshd environment parameter file is/etc/sysconfig/sshd.

ExecStart is the most important field in the configuration file.

ExecStart field: defines the commands executed when the process is started.

In the preceding example, the command to start sshd is/usr/sbin/sshd-D $ OPTIONS. The variable $ OPTIONS comes from the environment parameter file specified by the EnvironmentFile field.

Similar to this, the following fields are also used.

ExecReload field: ExecStop field of the Command executed when the service is restarted: ExecStartPre field of the Command executed when the service is stopped: ExecStartPost field of the Command executed before the service is started: ExecStopPost field of the Command executed after the service is started: command executed after the service is stopped

See the following example.

[Service]ExecStart=/bin/echo execstart1ExecStart=ExecStart=/bin/echo execstart2ExecStartPost=/bin/echo post1ExecStartPost=/bin/echo post2

In the preceding configuration file, ExecStart in the second line is set to null, which is equal to canceling the settings in the first line. The running result is as follows.

execstart2post1post2

Before all the startup settings, you can add a hyphen (-) to indicate "suppressing errors". That is, when an error occurs, the execution of other commands is not affected. For example, EnvironmentFile =-/etc/sysconfig/sshd (pay attention to the conjunction number after the equal sign) means that even if the/etc/sysconfig/sshd file does not exist, no error will be thrown.

6.2 start Type

The Type field defines the Startup Type. You can set the following values.

Simple (default): the process started in the ExecStart field is the main process. The forking: ExecStart field is started in the fork () mode. At this time, the parent process will exit, and the child process will become the main process oneshot: similar to simple, but only once, Systemd starts other services only after it is executed: similar to simple, but will wait until the D-Bus signal starts notify: similar to simple, after the service is started, a notification is sent, and then Systemd starts other service idle: similar to simple, but the service will be started until all other tasks are completed. One application scenario is to make the output of the service not mixed with the output of other services.

The following is an oneshot example. When a laptop is started, you must turn off the touchpad. The configuration file can be written in this way.

[Unit]Description=Switch-off Touchpad[Service]Type=oneshotExecStart=/usr/bin/touchpad-off[Install]WantedBy=multi-user.target

In the preceding configuration file, the Startup type is set to oneshot, which indicates that this service only needs to run once and does not need to run for a long time.

If you want to open the configuration file at a later time after it is disabled, modify the configuration file as follows.

[Unit]Description=Switch-off Touchpad[Service]Type=oneshotExecStart=/usr/bin/touchpad-off startExecStop=/usr/bin/touchpad-off stopRemainAfterExit=yes[Install]WantedBy=multi-user.target

In the preceding configuration file, the RemainAfterExit field is set to yes, indicating that the service is still executed after the process exits. In this case, once the systemctl stop command is used to stop the service, the command specified by ExecStop will be executed, and the touchpad will be re-enabled.

6.3 restart

The Service block has some fields that define the restart behavior.

KillMode field: defines how Systemd stops the sshd service.

In the preceding example, if KillMode is set to process, only the master process is stopped and no sshd sub-process is stopped. That is, the SSH session opened by the sub-process is still connected. This setting is not very common, but it is very important for sshd. Otherwise, when you stop the service, it will be killed together with the SSH session opened by yourself.

The following values can be set for the KillMode field.

Control-group (default): All Sub-processes in the current control group will be killed. process: only the main process mixed is killed. The main process will receive the SIGTERM signal, and the sub-process will receive the SIGKILL Signal none: no process is killed, but the stop command of the service is executed.

Next is the Restart field.

Restart field: defines the Restart mode of Systemd after sshd exits.
In the above example, if Restart is set to on-failure, sshd will be restarted if any unexpected failure occurs. If sshd stops normally (for example, execute the systemctl stop command), it will not restart.

The Restart field can be set as follows.

No (default): on-success will not be restarted after exit: on-failure will be restarted only when the exit status code is 0: during abnormal exit (the exit status code is not 0), including the signal termination and timeout, The on-abnormal will be restarted. Only when the signal is terminated or timed out will the on-abort be restarted: only when the uncaptured signal is terminated will the on-watchdog be restarted: timed out and always be restarted: always restarted for whatever reason

We recommend that you set the daemon to on-failure. For services that are allowed to exit with an error, you can set it to on-abnormal.

The last is the RestartSec field.

RestartSec field: the number of seconds that need to be waited before Systemd restarts the service. In the preceding example, wait for 42 seconds.
VII. [Install] Block

The Install block defines how to Install this configuration file, that is, how to enable startup.

WantedBy field: indicates the Target of the service.

Target indicates a service group, indicating a group of services. Wantedbypolicmulti user.tar get indicates that the Target of sshd is Multi user.tar get.

This setting is very important, because when executing the systemctl enable sshd. service command, a symbolic link of sshd. service will be placed in the Multi user.tar get. wants subdirectory under the/etc/systemd/systemdirectory.

Systemd has the default start Target.

$ systemctl get-defaultmulti-user.target

The above result indicates that the default start Target is Multi user.tar get. All services in this group will be started. This is why the systemctl enable command can be set to boot.

The systemctl list-dependencies command and the systemctl isolate command are also useful when Target is used.

# View all services included in the multi-user.target $ systemctl list-dependencies multi-user.target # switch to another target # shutdown.tar get is shutdown status $ sudo systemctl isolate shutdown.tar get

In general, there are two commonly used targets: one is Multi user.target, and the other is graphical.target, which depends on multi user.tar get. The official document provides a clear Target dependency diagram.

8. Target configuration file

Target also has its own configuration file.

$ systemctl cat multi-user.target[Unit]Description=Multi-User SystemDocumentation=man:systemd.special(7)Requires=basic.targetConflicts=rescue.service rescue.targetAfter=basic.target rescue.service rescue.targetAllowIsolate=yes

Note: The Target configuration file does not contain the start command.

The main fields in the output result are as follows.

Requires field: Run basic.tar get together. Conflicts field: Conflict field. If rescue.serviceor rescue.targetis running, multi user.tar get cannot run, and vice versa. After: Export multi-user.targetis started After basic.tar get, rescue. service, and rescue.tar get, if they have been started. AllowIsolate: allows the use of the systemctl isolatecommand to switch to multi user.tar get.
9. modify the configuration file and restart

After modifying the configuration file, you need to reload the configuration file and restart the relevant services.

# Reload the configuration file $ sudo systemctl daemon-reload # restart related services $ sudo systemctl restart foobar

Original article from: http://www.ruanyifeng.com /... /Systemd-tutorial-part-two.html Author: Ruan Yifeng

Address: http://www.linuxprobe.com/systemd-bestry-artikel.html


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.