`systemd` 中的 Unit 和 Target 是什么?

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: 【6月更文挑战第12天】这篇我们来了解一下 systemd 的服务配置文件中 [Unit] 和 [Install] 这两部分内容和涉及到的概念。

上一篇(在 Linux 系统中将 Spring Boot 应用作为系统服务运行)介绍了如何使用 systemd 将一个 Spring Boot 工程配置为一个系统服务并随系统启动。对于日常的开发而言,这种部署方式和配置已经很少在新的项目中用到了,但是需要的时候,还是得去查一下用法,下次再用到不知道就到什么时候了,不如这次多了解了解 systemd

以下是上次用到的服务配置内容:

[Unit]
Description=xxx
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/path/to/bin/start.sh
ExecReload=/path/to/bin/restart.sh
ExecStop=/path/to/bin/stop.sh
PrivateTmp=true

[Install]
WantedBy=multi-user.target

以上内容可以看到明显的三个部分,中间 [Service] 的部分,是服务启动方式的配置。这篇我们来了解一下 [Unit] 和 [Install] 这两部分。

[Unit] 部分包含两行配置。我们先来看一下 Unit 具体是指什么。

systemd 可以管理的各种系统资源,都可以称为 Unit,Unit 一共有 12 种,其中就包括我们使用的 Service Unit。你可以使用下面的命令查看系统中运行的所有 Unit:

systemctl list-units

也可以指定类型:

systemctl list-units --type=service

在上述的配置文件中,Unit 部分添加了两行配置。

  • Description 是这个 Unit 的描述,可以在这里简单描述这个 Unit 是用来做什么的。
  • After 指的是启动的时机,在 After 后面列出了其他的 Unit,代表如果这些 Unit 要启动,则当前的 Unit 在它们之后启动。这里还可以配置一个 Before 字段,作用于 After 类似。

我们之前介绍过的这几个命令:

# 启动服务
systemctl start xxx
# 停止服务
systemctl stop xxx
# 重启服务
systemctl restart xxx
# 查看启动状态
systemctl status xxx

其实就是 systemd 操作 Unit 的命令,通过 systemctl 来完成。

接下来介绍 Target。Target 其实也是 Unit 的一种,叫作 Target Unit,但它也表示一组 Unit,包含多个相关的 Unit,当系统启动一个 Target 的时候,就表示启动其中所有的 Unit,多个 Targe 可以同时启动。

上面的配置文件中,在 Intstall 部分就配置了我们的服务的 Target 是 multi-user.target。当 通过 systemctl enable xxx.service 命令的时候,systemd 就会在 /etc/systemd/system/multi-user.target.wants 目录为这个配置文件创建一个符号连接。

一个 Target 就类似于系统的一个状态点,multi-user.target 表示多用户命令行状态,它是最常用的 Target 之一,另外一个常用的 Target 是 graphical.target,表示图形用户状态,它依赖于前者。

以上就是 Unit 和 Target 的介绍。

目录
相关文章
|
10月前
|
Ubuntu 网络安全
Unit firewalld.service could not be found.
Unit firewalld.service could not be found.
350 0
|
27天前
|
Ubuntu Linux
Ubuntu 报错:System has not been booted with systemd as init system (PID 1). Can‘t operate.
系统未使用 `systemd` 初始化导致错误。解决方法是通过 `apt` 安装。首先备份并更换`sources.list`,添加阿里云镜像源,然后更新源并以管理员权限运行 `apt-get install systemd -y` 和 `apt-get install systemctl -y` 安装所需组件。
|
7月前
|
Ubuntu Docker 容器
System has not been booted with systemd as init system (PID 1). Can‘t operate.
System has not been booted with systemd as init system (PID 1). Can‘t operate.
126 0
|
Linux Docker 容器
docker报错:System has not been booted with systemd as init system (PID 1). Can‘t operate.
docker报错:System has not been booted with systemd as init system (PID 1). Can‘t operate.
1122 0
|
Linux 网络安全 Docker
Docker报错:Unit firewalld.service could not be found
Docker报错:Unit firewalld.service could not be found
286 0
|
关系型数据库 Linux Windows
|
存储 Unix Linux