Systemctl命令指南:Linux服务管理工具

1. 简介

systemctl是Linux系统中用于管理systemd系统和服务的主要命令行工具。它集成了服务管理、系统状态查看、开机自启配置等多种功能,是现代Linux系统中不可或缺的系统管理工具。

主要功能

  • 管理系统服务(启动、停止、重启、重载)
  • 查看系统状态和服务状态
  • 管理服务开机自启动
  • 查看系统日志
  • 管理系统资源

2. 基本用法

查看系统状态

# 查看系统状态
systemctl status

# 查看所有运行中的服务
systemctl list-units --type=service

# 查看所有服务(包括未运行的)
systemctl list-units --type=service --all

# 查看系统启动耗时
systemctl list-units --type=service --state=active

常用命令格式

# 基本语法
systemctl [command] [unit]

# 常用命令示例
systemctl start service-name    # 启动服务
systemctl stop service-name     # 停止服务
systemctl restart service-name  # 重启服务
systemctl status service-name   # 查看服务状态

3. 服务管理

服务生命周期管理

# 启动服务
systemctl start nginx.service

# 停止服务
systemctl stop nginx.service

# 重启服务
systemctl restart nginx.service

# 重新加载配置
systemctl reload nginx.service

# 查看服务状态
systemctl status nginx.service

开机自启管理

# 启用开机自启
systemctl enable nginx.service

# 禁用开机自启
systemctl disable nginx.service

# 查看是否开机自启
systemctl is-enabled nginx.service

# 启用并立即启动服务
systemctl enable --now nginx.service

4. 系统分析

系统状态查看

# 查看系统启动时间
systemctl list-dependencies
systemd-analyze

# 查看启动耗时
systemd-analyze blame

# 查看系统运行级别
systemctl get-default

# 设置系统运行级别
systemctl set-default multi-user.target

依赖关系分析

# 查看服务依赖
systemctl list-dependencies nginx.service

# 查看服务的反向依赖
systemctl list-dependencies --reverse nginx.service

5. Unit文件管理

Unit文件操作

# 查看Unit文件
systemctl cat nginx.service

# 编辑Unit文件
systemctl edit nginx.service

# 重新加载Unit文件
systemctl daemon-reload

# 查看Unit文件位置
systemctl show -p FragmentPath nginx.service

创建自定义服务

[Unit]
Description=My Custom Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/my-service
Restart=always

[Install]
WantedBy=multi-user.target

6. 最佳实践

服务管理建议

  • 总是使用systemctl status检查服务状态和错误信息
  • 在修改配置后使用reload而不是restart(如果服务支持)
  • 使用enable --now来同时启用并启动服务
  • 定期检查failed状态的服务

安全建议

  • 限制服务的权限和资源使用
  • 使用安全相关的Unit选项(如PrivateTmp=true)
  • 定期审查开机自启动的服务
  • 使用journalctl监控服务日志

7. 常见问题排查

服务启动失败

# 查看详细状态
systemctl status service-name -l

# 查看服务日志
journalctl -u service-name

# 查看启动失败的服务
systemctl --failed

# 重置服务状态
systemctl reset-failed service-name

性能问题

# 查看资源使用情况
systemctl show service-name

# 查看CPU和内存限制
systemctl show service-name -p CPUShares -p MemoryLimit

# 修改资源限制
systemctl set-property service-name CPUShares=1000