注:本文为 "Linux systemd" 相关合辑。
英文引文,机翻未校。
如有内容异常,请看原文。
Mastering Systemd in Linux: A Comprehensive Guide
精通 Linux 中的 Systemd:全面指南
Last Updated: Jan 16, 2026
In the world of Linux, the init system is responsible for bootstrapping the user space and managing system processes. Historically, SysVinit was the dominant init system, but in recent years, systemd has emerged as a modern alternative. Systemd is a system and service manager for Linux operating systems. It aims to address some of the limitations of traditional init systems, offering faster boot times, better parallelization, and more advanced features for managing services and processes. This blog post will provide a comprehensive overview of systemd, covering its fundamental concepts, usage methods, common practices, and best practices to help you make the most of this powerful tool.
在 Linux 领域,init 系统负责初始化用户空间并管理系统进程。传统上,SysVinit 是主流的 init 系统,而近年来,systemd 已成为一种现代化替代方案。systemd 是面向 Linux 操作系统的系统与服务管理器,其设计目标是解决传统 init 系统的部分局限,提供更快的启动速度、更优的并行处理能力,以及更丰富的服务与进程管理功能。本文将对 systemd 进行全面介绍,涵盖其基础概念、使用方法、常规实践与优化实践,助力读者充分运用这一强大工具。
Fundamental Concepts of Systemd
Systemd 的基础概念
Units
单元
Systemd organizes resources and services using units. A unit represents a systemd object that systemd knows how to manage. There are different types of units, each serving a specific purpose.
systemd 通过单元对资源与服务进行组织管理。单元是 systemd 可识别并管理的对象,存在多种类型,每种类型对应特定用途。
- Service Units : These are the most common type of units. They are used to manage services, such as network daemons or application processes. Service units have a
.servicefile extension. For example, thehttpd.serviceunit manages the Apache HTTP server.
服务单元 :这是最常见的单元类型,用于管理网络守护进程、应用程序进程等服务。服务单元文件以.service为后缀,例如httpd.service单元用于管理 Apache HTTP 服务器。 - Socket Units : A socket unit has a
.socketfile extension. It is used to manage network or IPC sockets. Systemd can use socket units to implement socket activation, where a service is started only when a connection is made to its associated socket.
套接字单元 :套接字单元文件以.socket为后缀,用于管理网络或进程间通信套接字。systemd 可通过套接字单元实现套接字激活机制,即仅当对应套接字接收到连接时才启动相关服务。 - Target Units : Target units (
.target) are used to group other units. They are similar to runlevels in traditional init systems. For example, themulti-user.targetis equivalent to the traditional runlevel 3, which represents a multi-user non-graphical environment.
目标单元 :目标单元文件以.target为后缀,用于对其他单元进行分组,功能与传统 init 系统中的运行级别类似。例如multi-user.target对应传统运行级别 3,代表多用户非图形化环境。
Targets
目标
Targets are special units that are used to group other units together. They act as synchronization points during the boot process or when changing the system state. For example, the graphical.target is used to represent a graphical desktop environment. When systemd reaches this target, it activates all the units that are required for a graphical session.
目标是一类特殊单元,用于将多个单元组合在一起,在系统启动或状态切换过程中作为同步节点。例如 graphical.target 代表图形化桌面环境,当 systemd 加载至该目标时,会启动所有图形化会话所需的单元。
Dependencies
依赖关系
Systemd allows units to have dependencies on other units. A unit can specify that it requires another unit to be active before it can start. For example, a mysql.service might depend on the network.target because it needs network connectivity to function properly. Dependencies can be defined using the Requires, Wants, After, and Before directives in the unit files.
systemd 支持单元之间建立依赖关系,一个单元可设定需在另一单元启动后自身才能运行。例如 mysql.service 通常依赖 network.target,因其正常运行需要网络连通。依赖关系可通过单元文件中的 Requires、Wants、After、Before 指令进行定义。
Usage Methods
使用方法
Unit Management
单元管理
Systemd provides a set of commands to manage units. Here are some common commands:
systemd 提供一系列命令用于单元管理,常用命令如下:
-
List all loaded units :
列出所有已加载单元:bashsystemctl list-unitsThis command lists all the units that are currently loaded by systemd. You can also filter the output by unit type, for example, to list only service units:
该命令列出 systemd 当前加载的所有单元,也可按单元类型过滤输出,例如仅列出服务单元:
bashsystemctl list-units --type=service -
Start a unit :
启动单元:bashsystemctl start httpd.serviceThis command starts the
httpdservice if it is not already running.该命令用于启动尚未运行的
httpd服务。 -
Stop a unit :
停止单元:bashsystemctl stop httpd.serviceThis command stops the
httpdservice if it is currently running.该命令用于停止正在运行的
httpd服务。 -
Restart a unit:
-
重启单元:
bashsystemctl restart httpd.serviceThis command restarts the
httpdservice, which is useful when you have made configuration changes.该命令用于重启
httpd服务,适用于配置修改后的生效场景。 -
Enable a unit :
设置单元开机自启:bashsystemctl enable httpd.serviceEnabling a unit means that it will be automatically started at boot time.
设置单元自启后,该单元会在系统启动时自动运行。
-
Disable a unit :
取消单元开机自启:bashsystemctl disable httpd.serviceDisabling a unit prevents it from starting automatically at boot time.
取消单元自启后,该单元不会在系统启动时自动运行。
Target Switching
目标切换
You can switch between different targets using the systemctl isolate command. For example, to switch to the rescue.target (a minimal system state for troubleshooting):
可通过 systemctl isolate 命令在不同目标间切换,例如切换至 rescue.target(用于故障排查的最小化系统状态):
bash
systemctl isolate rescue.target
Common Practices
常规实践
Writing a Simple Service Unit
编写简易服务单元
Let's create a simple service unit for a custom script. Suppose we have a Python script named my_script.py located at /usr/local/bin/my_script.py.
下面为自定义脚本创建一个简易服务单元,假设存在 Python 脚本 my_script.py,路径为 /usr/local/bin/my_script.py。
First, create a new service unit file at /etc/systemd/system/my_script.service with the following content:
首先在 /etc/systemd/system/my_script.service 路径创建服务单元文件,内容如下:
sh
[Unit]
Description=My Custom Python Script
After=network.target
[Service]
ExecStart=/usr/bin/python3 /usr/local/bin/my_script.py
Restart=always
[Install]
WantedBy=multi-user.target
In the [Unit] section, we provide a description of the service and specify that it should start after the network is available. In the [Service] section, we define the command to start the service. The Restart=always option ensures that the service will be restarted if it fails. In the [Install] section, we specify that this service should be started when the multi-user.target is reached.
[Unit] 段用于声明服务描述并设定网络就绪后启动;[Service] 段定义服务启动命令,Restart=always 表示服务异常退出时自动重启;[Install] 段指定该服务在系统进入 multi-user.target 时启动。
To make systemd aware of the new unit file, run:
执行以下命令使 systemd 识别新单元文件:
bash
systemctl daemon-reload
Then, you can start and enable the service:
随后可启动并设置该服务开机自启:
bash
systemctl start my_script.service
systemctl enable my_script.service
Managing Services
服务管理
Once you have a service unit, you can manage it using the systemctl commands mentioned earlier. For example, to check the status of the my_script service:
服务单元创建完成后,可通过前文所述 systemctl 命令进行管理,例如查看 my_script 服务状态:
bash
systemctl status my_script.service
Best Practices
优化实践
Unit File Organization
单元文件管理
- Separate system and user units : System-wide units should be placed in
/etc/systemd/system/, while user-specific units should be placed in~/.config/systemd/user/. This separation helps in maintaining a clear structure and makes it easier to manage different types of units.
区分系统单元与用户单元 :系统级单元存放于/etc/systemd/system/目录,用户级单元存放于~/.config/systemd/user/目录,该分类方式可保持结构清晰,便于不同类型单元的管理。 - Use descriptive names : When naming unit files, use clear and descriptive names that reflect the purpose of the unit. For example, instead of
script.service, usemy_custom_backup_script.service.
使用语义化命名 :单元文件命名应清晰直观,体现单元用途,例如使用my_custom_backup_script.service而非script.service。
Error Handling and Logging
异常处理与日志
-
Logging : Systemd uses
journaldfor logging. You can view the logs of a specific service using the following command:
日志记录 :systemd 通过journald实现日志管理,可通过以下命令查看指定服务日志:bashjournalctl -u my_script.serviceThis will show all the log entries related to the
my_scriptservice.该命令会输出与
my_script服务相关的全部日志条目。 -
Error handling in unit files : In the service unit file, you can set appropriate restart policies. For example,
Restart=on-failurewill restart the service only if it fails, which helps in handling transient errors.
单元文件异常处理 :可在服务单元文件中配置重启策略,例如Restart=on-failure表示仅服务异常退出时重启,适用于处理临时性故障。
Conclusion
总结
Systemd is a powerful and versatile system and service manager in Linux. It provides a modern approach to managing system resources, offering features like faster boot times, better parallelization, and advanced dependency management. By understanding its fundamental concepts, usage methods, common practices, and best practices, you can effectively use systemd to manage your Linux system's services and processes. Whether you are a system administrator or a developer, mastering systemd can greatly enhance your Linux experience.
systemd 是 Linux 中功能强大且通用性强的系统与服务管理器,采用现代化方式管理系统资源,具备启动速度快、并行处理能力强、依赖管理完善等特点。掌握其基础概念、使用方法、常规实践与优化实践,可高效运用 systemd 管理 Linux 系统服务与进程。无论是系统管理员还是开发人员,精通 systemd 均可显著提升 Linux 操作与运维效率。
Systemd Dependencies: Ensuring Services Start in the Correct Order
Systemd 依赖关系:保障服务按正确顺序启动
30 July 2025
by: Service Management
Effectively managing system services is crucial for the smooth operation of any Linux-based system. Systemd, the widely adopted system and service manager, provides powerful mechanisms for defining dependencies between services. This tutorial will guide you through the process of setting up systemd dependencies, ensuring that your services start in the correct order and in a reliable manner.
高效管理系统服务对 Linux 系统稳定运行至关重要。作为广泛应用的系统与服务管理器,systemd 提供了完善的服务依赖定义机制。本教程将讲解 systemd 依赖配置方法,保障服务按正确顺序可靠启动。
Executive Summary
内容概述
This comprehensive guide explains how to manage service startup order using systemd dependencies. We'll cover the fundamental concepts of systemd service units and how to define dependencies between them using directives like Requires, Wants, After, and Before. You'll learn through practical examples how to configure these dependencies to ensure that your services start in the correct sequence, preventing errors and ensuring system stability. This tutorial will also address common issues and provide troubleshooting tips to help you master systemd service management. Whether you're a system administrator, a developer, or simply a Linux enthusiast, this guide will equip you with the knowledge to effectively manage systemd service dependencies.
本指南全面讲解如何通过 systemd 依赖管理服务启动顺序,涵盖 systemd 服务单元基础概念,以及通过 Requires、Wants、After、Before 指令定义依赖的方法。结合实操案例,读者可掌握依赖配置技巧,避免服务启动异常,保障系统稳定。同时,本文将梳理常见问题并提供排查思路,助力读者精通 systemd 服务管理。无论系统管理员、开发人员还是 Linux 爱好者,均可通过本文掌握 systemd 服务依赖管理方法。
How do I view systemd service dependencies?
如何查看 systemd 服务依赖关系?
You can view a service's dependencies by using the systemctl show command with the service name.
可通过 systemctl show 命令搭配服务名查看服务依赖关系。
- Use the command
systemctl show(e.g.,systemctl show yourservice.service).
执行命令systemctl show(例如systemctl show yourservice.service)。 - Look for the
Requires,Wants,After, andBeforefields in the output. These fields list the dependencies of the service.
在输出结果中查找Requires、Wants、After、Before字段,这些字段记录了服务的依赖信息。 - For a graphical representation of dependencies, consider using
systemd-analyze plotand analyzing the resulting SVG file.
如需可视化展示依赖关系,可使用systemd-analyze plot命令生成 SVG 文件进行分析。
How do I create a basic systemd service unit file?
如何创建基础 systemd 服务单元文件?
You can create a basic systemd service unit file by defining the [Unit], [Service], and [Install] sections.
通过定义 [Unit]、[Service]、[Install] 三个段落,即可创建基础 systemd 服务单元文件。
-
Create a new file: Use a text editor like
nanoorvimto create a new file with a.serviceextension in the/etc/systemd/system/directory. For example,sudo nano /etc/systemd/system/myservice.service.
创建新文件 :使用nano、vim等文本编辑器,在/etc/systemd/system/目录下创建.service后缀文件,例如sudo nano /etc/systemd/system/myservice.service。 -
[Unit] Section: This section contains metadata and dependency information. Add a description:
[Unit] 段落:该段落包含元数据与依赖信息,添加描述语句:sh[Unit] Description=My Custom Service -
[Service] Section: This section defines how the service is executed. Include the following:
[Service] 段落:该段落定义服务执行方式,添加如下内容:sh[Service] ExecStart=/path/to/your/executable Restart=on-failureReplace
/path/to/your/executablewith the actual path to the program or script you want to run as a service.Restart=on-failureensures that the service restarts automatically if it crashes.将
/path/to/your/executable替换为待运行程序或脚本的实际路径,Restart=on-failure表示服务崩溃时自动重启。 -
[Install] Section: This section specifies how the service should be enabled.
[Install] 段落:该段落设定服务自启规则。sh[Install] WantedBy=multi-user.targetWantedBy=multi-user.targetmeans the service will start when the system enters the multi-user mode (normal operation).
WantedBy=multi-user.target表示系统进入多用户模式(常规运行状态)时启动该服务。 -
Save the file: Save the file and exit the text editor.
保存文件:保存文件并退出文本编辑器。 -
Reload systemd: Run
sudo systemctl daemon-reloadto reload systemd and recognize the new service file.
重载 systemd :执行sudo systemctl daemon-reload重载 systemd 使其识别新服务文件。 -
Enable the service: Run
sudo systemctl enable myservice.serviceto enable the service to start on boot.
设置服务开机自启 :执行sudo systemctl enable myservice.service配置服务开机自启。 -
Start the service: Run
sudo systemctl start myservice.serviceto start the service immediately.
启动服务 :执行sudo systemctl start myservice.service立即启动服务。 -
Check the status: Run
sudo systemctl status myservice.serviceto verify that the service is running correctly.
查看服务状态 :执行sudo systemctl status myservice.service确认服务正常运行。
How do I configure Requires and Wants in systemd?
如何在 systemd 中配置 Requires 与 Wants?
Requires and Wants are used to define dependencies between systemd services. Requires creates a strong dependency, while Wants creates a weaker dependency.
Requires 与 Wants 用于定义 systemd 服务间的依赖关系,其中 Requires 为强依赖,Wants 为弱依赖。
-
RequiresDirective: This directive specifies that the service will only start if the listed dependency services are also running. If any of theRequiresservices fail to start, the current service will also fail.
Requires指令:该指令指定当前服务仅在依赖服务运行时启动,若任一依赖服务启动失败,当前服务也会启动失败。sh[Unit] Description=My Service that Requires Another Service Requires=another.service After=another.serviceIn this example,
myservice.servicerequiresanother.serviceto be running. TheAfter=another.servicedirective ensures thatmyservice.servicestarts afteranother.servicehas started.本例中
myservice.service依赖another.service,After=another.service确保myservice.service在another.service启动后运行。 -
WantsDirective: This directive specifies that the service would like the listed dependency services to be running, but it's not essential. If any of theWantsservices fail to start, the current service will still attempt to start.
Wants指令:该指令指定当前服务期望依赖服务运行,但非必需条件,即便依赖服务启动失败,当前服务仍会尝试启动。sh[Unit] Description=My Service that Wants Another Service Wants=another.service After=another.serviceIn this example,
myservice.servicewantsanother.serviceto be running, but it will still start even ifanother.servicefails to start. This is useful for optional dependencies.本例中
myservice.service期望another.service运行,即便another.service启动失败,myservice.service仍会启动,适用于可选依赖场景。 -
Best Practices:
实践建议:
- Use
Requiresfor essential dependencies that must be running for the service to function correctly.
对服务正常运行必需的依赖使用Requires。 - Use
Wantsfor optional dependencies that enhance the service but are not strictly required.
对提升服务功能但非必需的可选依赖使用Wants。 - Always include an
Afterdirective alongsideRequiresorWantsto define the startup order explicitly.
搭配Requires或Wants使用时,需同时添加After指令明确启动顺序。
How do I use After and Before to define startup order?
如何通过 After 与 Before 定义启动顺序?
After and Before directives specify the order in which systemd services should be started or stopped relative to each other.
After 与 Before 指令用于设定 systemd 服务之间的启动与停止先后顺序。
-
AfterDirective: This directive specifies that the service should start only after the listed services have started successfully.
After指令:该指令指定当前服务在所列服务启动完成后再运行。sh[Unit] Description=My Service that Starts After Another Service After=another.serviceIn this example,
myservice.servicewill start afteranother.servicehas started. This ensures that any prerequisites are met before the service starts.本例中
myservice.service在another.service启动后运行,保障服务启动前前置条件已满足。 -
BeforeDirective: This directive specifies that the service should start before the listed services start.
Before指令:该指令指定当前服务在所列服务启动前运行。sh[Unit] Description=My Service that Starts Before Another Service Before=another.serviceIn this example,
myservice.servicewill start beforeanother.servicestarts. This is useful when a service needs to be initialized before another service depends on it.本例中
myservice.service在another.service启动前运行,适用于某服务需先初始化再被其他服务依赖的场景。 -
Example Scenario: Consider a web application that depends on a database server. The web application service should start
Afterthe database server service. This ensures that the database server is running and ready to accept connections before the web application attempts to connect.
场景示例:某 Web 应用依赖数据库服务,Web 应用服务应配置为在数据库服务启动后运行,保障数据库服务就绪后 Web 应用再尝试建立连接。
How do I troubleshoot common systemd dependency issues?
如何排查常见的 systemd 依赖问题?
Troubleshooting systemd dependency issues involves checking service status, reviewing logs, and verifying dependency configurations.
排查 systemd 依赖问题需依次检查服务状态、查看日志、校验依赖配置。
-
Check Service Status: Use
systemctl statusto check the status of the service. Look for error messages or indications of dependency issues.
检查服务状态 :使用systemctl status查看服务状态,关注报错信息与依赖异常提示。bashsystemctl status myservice.service -
Review Logs: Use
journalctl -uto review the logs for the service. Look for error messages related to dependencies or startup failures.
查看日志 :使用journalctl -u查看服务日志,定位与依赖或启动失败相关的报错信息。bashjournalctl -u myservice.serviceYou can also use
journalctl -xeto see detailed error messages for the entire system.也可通过
journalctl -xe查看系统全局详细报错信息。 -
Verify Dependency Configurations: Double-check the
Requires,Wants,After, andBeforedirectives in the service unit files to ensure they are correctly configured. Typos or incorrect service names can cause dependency failures.
校验依赖配置 :复核服务单元文件中Requires、Wants、After、Before指令的配置正确性,拼写错误或服务名错误均会导致依赖失效。 -
Reload Systemd: After making changes to the service unit files, reload systemd using
systemctl daemon-reloadto apply the changes.
重载 systemd :修改服务单元文件后,执行systemctl daemon-reload使配置生效。 -
Example Scenario: If a service fails to start due to a missing dependency, the logs will usually indicate which dependency is missing or failed to start. Check the status of the missing dependency and ensure it's configured correctly.
场景示例:若服务因依赖缺失启动失败,日志通常会标注缺失或启动失败的依赖项,检查该依赖服务状态并修正配置即可。
FAQ
常见问题
How do I reload systemd configuration?
如何重载 systemd 配置?
You can reload the systemd configuration by running the command sudo systemctl daemon-reload. This command reloads the systemd manager configuration, applying any changes you've made to service unit files.
执行 sudo systemctl daemon-reload 可重载 systemd 配置,该命令会加载服务单元文件的修改内容并生效。
What is the difference between Requires and Wants in systemd?
systemd 中 Requires 与 Wants 的区别是什么?
Requires specifies a hard dependency: if the required service fails, the dependent service also fails. Wants specifies a soft dependency: if the wanted service fails, the dependent service will still attempt to start.
Requires 为强依赖,依赖服务启动失败则当前服务启动失败;Wants 为弱依赖,依赖服务启动失败不影响当前服务启动。
How can I see the startup order of services?
如何查看服务启动顺序?
You can use the command systemd-analyze blame to see a list of services sorted by their startup time. This can help you identify slow-starting services and potential bottlenecks in the startup process.
执行 systemd-analyze blame 可按启动耗时排序显示服务列表,便于定位启动缓慢的服务与流程瓶颈。
Conclusion
总结
Understanding and effectively configuring systemd dependencies is a crucial skill for managing Linux systems. By using directives like Requires, Wants, After, and Before, you can ensure that your services start in the correct order, preventing errors and ensuring system stability. Remember to always check service status, review logs, and verify dependency configurations to troubleshoot any issues. By mastering systemd dependencies, you can significantly improve the reliability and performance of your Linux systems.
理解并合理配置 systemd 依赖是 Linux 系统管理的核心技能。通过 Requires、Wants、After、Before 指令可规范服务启动顺序,避免运行异常,保障系统稳定。排查问题时需依次检查服务状态、查看日志、校验依赖配置。精通 systemd 依赖管理,可显著提升 Linux 系统的可靠性与运行性能。
Start Systemd Service After Specific Service
让 Systemd 服务在指定服务之后启动
Last updated: March 18, 2024
Written by: baeldung
Reviewed by: Hiks Gerganov
1. Overview
1. 概述
Starting services in the right order is crucial for the smooth working of a Linux system. The init system, systemd, is responsible for starting, stopping, and managing services during the boot process. Therefore, it plays a central role in managing services on Linux systems.
服务按正确顺序启动对 Linux 系统稳定运行至关重要。init 系统 systemd 负责系统启动过程中服务的启动、停止与管理,是 Linux 服务管理的核心组件。
In some cases, it's useful to start one service after another specific service. We can achieve this by configuring service dependencies in systemd.
部分场景下需要让某服务在指定服务之后运行,可通过配置 systemd 服务依赖实现该需求。
In this article, we'll learn and apply service dependencies in systemd and configure a service to start after another specific service. We'll also discuss the use of the After and Requires directives in the service unit file.
本文将讲解 systemd 服务依赖的原理与应用,实现服务在指定服务后启动,并介绍服务单元文件中 After 与 Requires 指令的使用方法。
2. Understanding Systemd and Services
2. Systemd 与服务基础认知
systemd is a modern init system and system manager for Linux systems. It replaces the traditional init system, SysVinit, and provides several improvements like parallel service startup, improved logging, and dynamic management of system processes.
systemd 是 Linux 系统的现代化 init 系统与系统管理器,替代传统 SysVinit,具备服务并行启动、日志优化、系统进程动态管理等优势。
During the boot process, systemd starts and manages processes known as services . These occupy three categories:
系统启动过程中,systemd 启动并管理的进程称为服务,主要分为三类:
- system services
系统服务 - user services
用户服务 - target units
目标单元
System services begin at boot and are necessary for the system's proper functioning. User services are services that are triggered on demand by a specific user. Target units are groups of services that are started and stopped together.
系统服务在开机时启动,是系统正常运行的必需组件;用户服务由特定用户按需触发;目标单元是统一启停的服务组。
systemd provides a simple and consistent interface for controlling services through the systemctl command. This command can start, stop, restart, and check the current status of services. It also provides a way to configure service dependencies. It ensures that the services start in the correct order, avoiding potential conflicts and errors.
systemd 通过 systemctl 命令提供统一的服务控制接口,可实现服务的启动、停止、重启与状态查询,同时支持服务依赖配置,保障服务按序启动,避免冲突与异常。
3. Configuring Service Dependencies
3. 服务依赖配置
A simple way to configure service dependencies in Linux is to use systemctl and modify the service file. The service unit file lists all the dependencies along with information about the service.
Linux 中配置服务依赖的简易方法是使用 systemctl 命令修改服务文件,服务单元文件会记录服务信息与全部依赖关系。
Configuring a service to run after another service can be done with the edit subcommand of systemctl :
通过 systemctl 的 edit 子命令可配置服务在另一服务之后运行:
bash
$ systemctl edit <service_name>.service
On running the above command, the service file opens in a text editor. We can add the After or Requires directives to define what service this service should be started after.
执行上述命令后,服务文件会在文本编辑器中打开,添加 After 或 Requires 指令即可设定前置依赖服务。
3.1. Understanding the After Directive
3.1. After 指令解析
The After directive makes sure that the current service starts after the specified service.
After 指令用于确保当前服务在指定服务启动后运行。
In order to configure service1 to run after service2, we can add a line to the unit file of service1 :
若要配置 service1 在 service2 之后运行,可在 service1 单元文件中添加如下语句:
bash
After=service2.service
To define multiple services in the After directive, we simply place the name of each service separated by a space:
如需在 After 指令中指定多个前置服务,直接用空格分隔服务名即可:
bash
After=service2.service service3.service service4.service
The current service will start once all specified services have run successfully.
当前服务会在所有指定服务启动完成后运行。
3.2. Understanding the Requires Directive
3.2. Requires 指令解析
The Requires directive specifies that the current service requires the specified service to be running. Similar to After, this directive stops the current service when the specified service stops.
Requires 指令指定当前服务依赖指定服务运行,与 After 类似,若指定服务停止,当前服务也会随之停止。
Let's check out the Requires directive format:
Requires 指令格式如下:
bash
Requires=<service_name>.service
Thus, we can configure service1 to start service2 automatically by adding a line to service1's unit file :
在 service1 单元文件中添加如下语句,可配置 service1 依赖 service2 并自动启动 service2:
bash
Requires=service2.service
It is critical to note that the After directive only sets a dependency between services and doesn't guarantee the order of service start-up. If service1 and service2 have After for each other, they'll cause a loop and systemd may fail to start.
需要注意,After 指令仅设定服务间依赖关系,不保证启动顺序;若 service1 与 service2 互相配置 After,会形成循环依赖,导致 systemd 启动异常。
Let's now restart service1 to bring all the changes into effect:
重启 service1 使配置生效:
bash
$ systemctl restart service1.service
Importantly, the Requires directive takes precedence over the After directive, and it also creates a service ordering relationship.
Requires 指令优先级高于 After 指令,同时会建立服务启动顺序关联。
4. Conclusion
4. 总结
In this article, we discussed the concept of service dependencies in systemd and how to configure a service to start after another specific service. In particular, we learned about the systemctl command and the use of the After and Requires directives in the service unit file.
本文讲解了 systemd 服务依赖的概念,以及配置服务在指定服务后启动的方法,重点介绍了 systemctl 命令与服务单元文件中 After、Requires 指令的应用。
reference
- Mastering Systemd in Linux: A Comprehensive Guide --- 2026
https://linuxvox.com/blog/systemd-in-linux/ - Systemd Dependencies: Ensuring Services Start in the Correct Order - 2025
https://dohost.us/index.php/2025/07/30/systemd-dependencies-ensuring-services-start-in-the-correct-order/ - Start Systemd Service After Specific Service | 2024
https://www.baeldung.com/linux/systemd-service-start-order