systemctl 是一个用于管理系统服务的命令行工具。它是 systemd 系统和服务管理器的主要命令行接口,用于启动、停止、重启、启用、禁用系统服务,以及查看服务状态和管理系统运行级别。

基本用法

systemctl 的基本语法如下:

systemctl [选项] 命令 服务名

选项:控制 systemctl 的行为。

命令:要执行的操作,如启动、停止、重启等。

服务名:要操作的服务的名称。

常用选项

start:启动服务。

stop:停止服务。

restart:重启服务。

reload:重新加载服务的配置文件。

enable:启用服务,使其在系统启动时自动启动。

disable:禁用服务,使其在系统启动时不自动启动。

status:查看服务的状态。

is-active:检查服务是否处于活动状态。

is-enabled:检查服务是否已启用。

使用示例

  1. 查看服务状态
 systemctl status nginx.service           # 查看nginx服务状态
  1. 启动服务
 systemctl start nginx.service            # 启动nginx服务
  1. 停止服务
 systemctl stop nginx.service            # 停止nginx服务
  1. 重启服务
 systemctl restart nginx.service         # 重启nginx服务
  1. 重新加载服务的配置文件
 cat /usr/lib/systemd/system/nginx.service   # 查看nginx服务涉及的配置文件
 systemctl reload nginx.service              # 修改后重新加载nginx服务
  1. 启用开机启动服务
 systemctl enable nginx.service 
 #在/etc/systemd/system/multi-user.target.wants目录下创建快捷方式,使得Nginx服务在系统启动时自动启动,因为multi-user.target.wants/目录中的服务会被 systemd 自动启动。
  1. 检查服务是否处于活动状态
 systemctl is-active nginx.service       # 检查nginx服务活动状态
  1. 检查服务是否已启用
 systemctl is-enabled nginx.service      # 检查nginx服务启用状态
  1. 查看所有服务的状态
 systemctl list-units --type=service     # 查看所有服务的状态

创建服务

/etc/systemd/system/下创建test.service

nano /etc/systemd/system/test.service

写入如下内容:

[Unit]
Description = Service description
After = network.target syslog.target
Wants = network.target

[Service]
Type = simple
ExecStart = /path/to/bin/file #欲启动的程序

[Install]
WantedBy = multi-user.target