原文:How To Use Systemctl to Manage Systemd Services and Units
稍微翻译了一下,然后根据自己的项目改了一些例子.
Introduction
Systemd is an init system and system manager
,它正在广泛地成为Linux机器的新标准。虽然对于 systemd
是否优于传统的 SysV init system
,有相当多的意见,但大多数发行版计划采用或已经采用。
由于它的大量采用,使您熟悉systemd
是非常值得的,因为它将使管理服务器变得相当容易。学习和使用包含systemd
的工具和守护程序将帮助您更好地理解它提供的能力、灵活性和功能,或者至少帮助您以最少的麻烦完成您的工作。
在本指南中,我们将讨论 systemctl
命令,它是控制init system 的中心管理工具。我们将介绍如何管理服务、检查状态、更改系统状态以及使用配置文件。
请注意,尽管 systemd
已经成为许多Linux发行版的默认初始化系统,但它并没有在所有发行版中普遍实现。当您浏览本教程时,如果您的终端输出错误
bash: systemctl is not installed
,那么您的机器可能安装了一个不同的init system。
Service Management
init system的基本目的是初始化在Linux内核启动后必须启动的组件(传统上称为“ userland” 组件)。在系统运行时,init system 还用于管理服务器的服务和 daemons (守护进程)。考虑到这一点,我们将从一些简单的服务管理操作开始。
在 systemd
中,大多数操作的目标是“units
”,这是 systemd
知道如何管理的资源。单元按它们所代表的资源类型进行分类,并使用称为单元文件的文件来定义它们。每个单元的类型可以从文件末尾的后缀推断出来。
对于服务管理任务,目标单元将是服务单元,其中包含带有 .service
后缀的单元文件。但是,对于大多数服务管理命令,实际上可以省略。服务后缀,因为 systemd
足够聪明,知道您可能希望在使用服务管理命令时使用服务。
Starting and Stopping Services
To start a systemd
service, executing instructions in the service's unit file, use the start
command. If you are running as a non-root user, you will have to use sudo since this will affect the state of the operating system:
sudo systemctl start application.service
As we mentioned above,systemd
knows to look for *.service
files for service management commands, so the command could just as easily be typed like this:
sudo systemctl start application
Although you may use the above format for general administration, for clarity, we will use the .service
suffix for the remainder of the commands to be explicit about the target we are operating on.
To stop a currently running service, you can use thestop
command instead:
sudo systemctl stop application.service
Restarting and Reloading
To restart a running service, you can use therestart
command:
sudo systemctl restart application.service
If the application in question is able to reload its configuration files (without restarting), you can issue thereload
command to initiate that process:
sudo systemctl reload application.service
If you are unsure whether the service has the functionality to reload its configuration, you can issue the reload-or-restart
command. This will reload the configuration in-place if available. Otherwise, it will restart the service so the new configuration is picked up:
sudo systemctl reload-or-restart application.service
Enabling and Disabling Services
The above commands are useful for starting or stopping commands during the current session. To tell systemd
to start services automatically at boot, you must enable them.
To start a service at boot, use the enable
command:
sudo systemctl enable application.service
这将从系统的服务文件副本 (usually in /lib/systemd/system
or /etc/systemd/system
) 中创建一个符号链接到磁盘上的位置,在那里systemd查找自动启动文件 (usually /etc/systemd/system/some_target.target.wants.
We will go over what a target is later in this guide).
To disable the service from starting automatically, you can type:
sudo systemctl disable application.service
This will remove the symbolic link that indicated that the service should be started automatically.
Keep in mind that enabling a service does not start it in the current session. If you wish to start the service and enable it at boot, you will have to issue both the start and enable commands.
Checking the Status of Services
To check the status of a service on your system, you can use thestatus
command:
systemctl status application.service
这将为您提供服务状态、cgroup层次结构和前几条日志。
For instance, when checking the status of an Nginx server, you may see output like this:
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Tue 2015-01-27 19:41:23 EST; 22h ago
Main PID: 495 (nginx)
CGroup: /system.slice/nginx.service
├─495 nginx: master process /usr/bin/nginx -g pid /run/nginx.pid; error_log stderr;
└─496 nginx: worker process
Jan 27 19:41:23 desktop systemd[1]: Starting A high performance web server and a reverse proxy server...
Jan 27 19:41:23 desktop systemd[1]: Started A high performance web server and a reverse proxy server.
This gives you a nice overview of the current status of the application, notifying you of any problems and any actions that may be required.
There are also methods for checking for specific states. For instance, to check to see if a unit is currently active (running), you can use the is-active
command:
systemctl is-active application.service
This will return the current unit state, which is usually active or inactive. The exit code will be "0" if it is active, making the result simpler to parse programmatically.
To see if the unit is enabled, you can use the is-enabled
command:
systemctl is-enabled application.service
This will output whether the service isenabled
ordisabled
and will again set the exit code to "0" or "1" depending on the answer to the command question.
A third check is whether the unit is in a failed state. This indicates that there was a problem starting the unit in question:
systemctl is-failed application.service
如果运行成功返回active
, 出现错误则返回失败.
如果该单元被强制停止,它可能返回unknown
或inactive
。
0
的退出状态表示发生错误失败,1
的退出状态表示其他status。
System State Overview
The commands so far have been useful for managing single services, but they are not very helpful for exploring the current state of the system. There are a number of systemctl
commands that provide this information.
Listing Current Units
To see a list of all of the active units that systemd knows about, we can use the list-units
command:
systemctl list-units
This will show you a list of all of the units that systemd currently has active on the system.
The output has the following columns:
- UNIT: The systemd unit name
- LOAD: Whether the unit's configuration has been parsed by systemd. The configuration of loaded units is kept in memory.
- ACTIVE: A summary state about whether the unit is active. This is usually a fairly basic way to tell if the unit has started successfully or not.
- SUB: This is a lower-level state that indicates more detailed information about the unit. This often varies by unit type, state, and the actual method in which the unit runs.
- DESCRIPTION: A short textual description of what the unit is/does.
systemctl list-units --all
systemctl list-units --all --state=inactive
systemctl list-units --type=service
Listing All Unit Files
systemctl list-unit-files
Unit Management
So far, we have been working with services and displaying information about the unit and unit files that systemd knows about. However, we can find out more specific information about units using some additional commands.
Displaying a Unit File
To display the unit file that systemd has loaded into its system, you can use the cat command (this was added in systemd version 209). For instance, to see the unit file of the atd scheduling daemon, we could type:
systemctl cat freeradiusd.service
[Unit]
Description=FreeRADIUS multi-protocol policy server
After=syslog.target network.target mariadb.target
Documentation=man:radiusd(8) man:radiusd.conf(5) http://wiki.freeradius.org/ http://networkradius.com/doc/
[Service]
EnvironmentFile=-$FREERADIUS_DSTDIR/etc/sysconfig/radiusd
ExecStartPre=$FREERADIUS_DSTDIR/sbin/radiusd $FREERADIUS_OPTIONS -Cxm -lstdout
ExecStart=$FREERADIUS_DSTDIR/sbin/radiusd $FREERADIUS_OPTIONS -fm
ExecReload=/usr/sbin/radiusd -C
ExecReload=/bin/kill -HUP $MAINPID
[Install]
WantedBy=multi-user.target
Displaying Dependencies
systemctl list-dependencies radiusd.service
[root@liam ~]# systemctl list-dependencies radiusd.service
radiusd.service
├─system.slice
└─basic.target
├─alsa-restore.service
├─alsa-state.service
├─microcode.service
├─rhel-autorelabel-mark.service
├─rhel-autorelabel.service
├─rhel-configure.service
├─rhel-dmesg.service
├─rhel-loadmodules.service
├─paths.target
├─slices.target
│ ├─-.slice
│ └─system.slice
├─sockets.target
│ ├─avahi-daemon.socket
...
Checking Unit Properties
systemctl show radiusd.service
[root@liam~]# systemctl show radiusd.service
Id=radiusd.service
Names=radiusd.service
Requires=basic.target
Wants=system.slice
WantedBy=multi-user.target
Conflicts=shutdown.target
Before=shutdown.target multi-user.target
After=syslog.target network.target mariadb.target systemd-journald.socket basic.target system.slice
Documentation=man:radiusd(8) man:radiusd.conf(5) http://wiki.freeradius.org/ http://networkradius.com/doc/
Description=FreeRADIUS multi-protocol policy server
LoadState=loaded
ActiveState=active
SubState=running
FragmentPath=/usr/lib/systemd/system/radiusd.service
UnitFileState=enabled
InactiveExitTimestamp=Thu 2018-01-25 06:01:04 UTC
InactiveExitTimestampMonotonic=47013559
ActiveEnterTimestamp=Thu 2018-01-25 06:01:04 UTC
ActiveEnterTimestampMonotonic=47088382
ActiveExitTimestampMonotonic=0
InactiveEnterTimestamp=Thu 2018-01-25 06:00:31 UTC
...
If you want to display a single property, you can pass the -p
flag with the property name. For instance, to see the conflicts that the sshd.service unit has, you can type:
[root@liam~]# systemctl show radiusd.service -p FragmentPath
FragmentPath=/usr/lib/systemd/system/radiusd.service
Masking and Unmasking Units
We saw in the service management section how to stop or disable a service, but systemd also has the ability to mark a unit as completely unstartable, automatically or manually, by linking it to /dev/null. This is called masking the unit, and is possible with the mask command:
sudo systemctl mask nginx.service
This will prevent the Nginx service from being started, automatically or manually, for as long as it is masked.
If you check the list-unit-files, you will see the service is now listed as masked:
systemctl list-unit-files
kmod-static-nodes.service static
ldconfig.service static
mandb.service static
messagebus.service static
nginx.service masked
quotaon.service static
rc-local.service static
rdisc.service disabled
rescue.service static
If you attempt to start the service, you will see a message like this:
sudo systemctl start nginx.service
Failed to start nginx.service: Unit nginx.service is masked.
To unmask a unit, making it available for use again, simply use the unmask command:
sudo systemctl unmask nginx.service
This will return the unit to its previous state, allowing it to be started or enabled.
网友评论