systemctl
是 Linux 系统中用于管理 systemd
服务的核心命令行工具,用于控制系统服务的启动、停止、重启、查看状态等,是管理系统服务的标准方式(替代了传统的 service
和 chkconfig
命令)。
一、基本语法
systemctl [选项] 服务名.service
服务名后的
.service
可省略(如systemctl start nginx
等同于systemctl start nginx.service
)。
二、常用命令
1. 服务状态管理
status
输出解读:
若显示
active (running)
表示服务正常运行;若显示
inactive (dead)
表示服务已停止;若显示
failed
表示服务启动失败(会显示错误原因)。
2. 开机自启管理
3. 查看所有服务状态
# 查看所有已加载的服务(精简版)
systemctl list-units --type=service
# 查看所有服务(包括未加载的,详细版)
systemctl list-unit-files --type=service
# 过滤运行中的服务
systemctl list-units --type=service --state=running
4. 系统状态控制
systemctl
还可控制整个系统的运行级别(如关机、重启):
5. 其他实用命令
查看服务依赖关系:
systemctl list-dependencies nginx # 查看 nginx 依赖的服务
屏蔽 / 解除屏蔽服务(禁止手动或自动启动):
systemctl mask nginx # 屏蔽服务(比 disable 更彻底) systemctl unmask nginx # 解除屏蔽
6.服务脚本示例及参数详解
服务脚本示例
# 编写服务化脚本 cat << EOF> /etc/systemd/system/redis.service [Unit] Description=NGINX Web Server Documentation=http://nginx.org/en/docs/ After=network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/run/nginx.pid ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID User=nginx Group=nginx Restart=on-failure RestartSec=5s [Install] WantedBy=multi-user.target EOF # 启动redis服务 systemctl start redis # 设置开机启动 systemctl enable redis # 立即启动并开机启动 # systemctl enable redis --now
参数详解
[Unit]
段:定义服务元信息与依赖[Service]
段:定义服务运行参数(核心)[Install]
段:定义服务安装配置(开机自启相关)
三、注意事项
权限:管理系统服务通常需要
root
权限,普通用户需加sudo
(如sudo systemctl start nginx
)。服务文件路径:系统服务的配置文件通常位于
/usr/lib/systemd/system/
或/etc/systemd/system/
(自定义服务)。配置生效:修改服务配置文件后,需执行
systemctl daemon-reload
使配置生效。
systemctl
是 Linux 系统管理的核心工具,熟练掌握可高效管理服务生命周期和系统状态。