systemd是现代linux发行版默认初始化系统,需掌握服务状态查看(status/is-active/is-enabled)、启停重启(start/stop/restart/reload/try-restart)、开机自启管理(enable/disable/mask/unmask)及日志排查(journalctl/show)。

linux系统中,systemd是现代发行版(如centos 7+、ubuntu 16.04+、debian 8+)默认的初始化系统和服务管理器。掌握systemd服务启动与管理,是运维和开发人员的必备技能。
查看服务状态与基本信息
使用systemctl status可快速检查服务运行状况:
- systemctl status sshd —— 查看SSH服务是否运行、最近日志、启用状态
- systemctl is-active sshd —— 仅返回 active/inactive/failed,适合脚本判断
- systemctl is-enabled sshd —— 返回 enabled/disabled,确认开机是否自启
- systemctl list-unit-files –type=service | grep enabled —— 列出所有开机自启的服务
启动、停止、重启与重载服务
基础操作需配合sudo(除非已获特权):
- systemctl start nginx —— 立即启动服务(不写入开机启动)
- systemctl stop nginx —— 立即停止服务
- systemctl restart nginx —— 停止后立即启动,常用于配置更新后生效
- systemctl reload nginx —— 仅重载配置(要求服务支持SIGHUP),比restart更轻量
- systemctl try-restart nginx —— 仅在服务已运行时才重启,避免误启未启用的服务
设置开机自启与禁用服务
启用或禁用服务影响/etc/systemd/system/下的软链接:
- systemctl enable nginx —— 创建符号链接,使服务开机自动启动
- systemctl disable nginx —— 移除链接,取消开机自启(已运行的服务不受影响)
- systemctl mask nginx —— 彻底禁止启动(创建指向red”>/dev/NULL的硬链接),需unmask才能恢复
- systemctl unmask nginx —— 解除mask限制
排查服务失败原因
服务启动失败时,别只看status输出,要结合日志深入定位: