常用的 systemctl 操作
目录
systemctl 是 systemd 系统和服务管理器的主要控制工具。以下是常用的 systemctl 操作:
服务管理操作
1. 启动/停止/重启服务
# 启动服务
sudo systemctl start service-name
# 停止服务
sudo systemctl stop service-name
# 重启服务
sudo systemctl restart service-name
# 重载服务(不重启,重新加载配置)
sudo systemctl reload service-name
# 尝试重启(如果正在运行就重启)
sudo systemctl try-restart service-name
2. 启用/禁用服务
# 启用服务开机自启
sudo systemctl enable service-name
# 禁用服务开机自启
sudo systemctl disable service-name
# 启用并立即启动服务
sudo systemctl enable --now service-name
# 禁用并停止服务
sudo systemctl disable --now service-name
3. 查看服务状态
# 查看服务状态
sudo systemctl status service-name
# 简洁状态显示
sudo systemctl status service-name --no-pager -l
# 检查服务是否活跃
sudo systemctl is-active service-name
# 检查服务是否启用
sudo systemctl is-enabled service-name
# 检查服务是否失败
sudo systemctl is-failed service-name
系统状态查看
4. 列出服务
# 列出所有已加载的服务单元
systemctl list-units --type=service
# 列出所有单元(包括未加载的)
systemctl list-units --all
# 列出失败的服务
systemctl --failed
# 列出所有已启用的服务
systemctl list-unit-files --state=enabled
# 列出所有可用的服务
systemctl list-unit-files --type=service
5. 日志查看
# 查看服务的实时日志
sudo journalctl -u service-name -f
# 查看服务的所有日志
sudo journalctl -u service-name
# 查看最近100行日志
sudo journalctl -u service-name -n 100
# 查看今天以来的日志
sudo journalctl -u service-name --since today
# 查看指定时间段的日志
sudo journalctl -u service-name --since "2024-01-01" --until "2024-01-02"
系统管理操作
6. 系统控制
# 重启系统
sudo systemctl reboot
# 关闭系统
sudo systemctl poweroff
# 进入救援模式
sudo systemctl rescue
# 进入紧急模式
sudo systemctl emergency
# 挂起系统
sudo systemctl suspend
# 休眠系统
sudo systemctl hibernate
7. 系统状态
# 查看系统状态
systemctl status
# 查看系统启动时间
systemctl show --property=ActiveSince
# 查看系统运行时间
systemctl show --property=RuntimeSec
实用技巧和组合命令
8. 常用组合
# 查看服务的详细状态和最近日志
sudo systemctl status service-name && sudo journalctl -u service-name -n 20
# 重启服务并跟踪日志
sudo systemctl restart service-name && sudo journalctl -u service-name -f
# 查看服务的依赖关系
systemctl list-dependencies service-name
# 重新加载所有修改过的单元文件
sudo systemctl daemon-reload
9. 服务文件操作
# 编辑服务文件
sudo systemctl edit service-name # 创建覆盖文件
sudo systemctl edit --full service-name # 编辑完整文件
# 显示服务文件内容
systemctl cat service-name
# 显示服务的属性值
systemctl show service-name
# 显示服务的环境变量
systemctl show service-name -p Environment
10. 资源监控
# 查看服务的资源使用情况
systemd-cgtop
# 查看指定服务的cgroup信息
systemctl status service-name | grep CGroup
# 查看服务的内存使用
systemctl show service-name -p MemoryCurrent
实际应用示例
# 部署新服务后的标准操作流程
sudo systemctl daemon-reload # 重新加载配置
sudo systemctl enable service-name # 启用开机启动
sudo systemctl start service-name # 启动服务
sudo systemctl status service-name # 检查状态
sudo journalctl -u service-name -f # 跟踪日志
# 排查服务问题
sudo systemctl status service-name # 查看状态
sudo journalctl -u service-name -n 50 # 查看最近50条日志
sudo systemctl restart service-name # 尝试重启
这些命令涵盖了日常系统管理中的大部分需求,熟练掌握这些操作可以有效地管理和维护 systemd 服务。
Do not communicate by sharing memory; instead, share memory by communicating.

浙公网安备 33010602011771号