Linux systemctl服务管理完全指南:systemd服务的启动、停止、启用与自建服务(2026)

📝 512 字 · ☕ 2 分钟阅读

Linux systemctl服务管理完全指南:systemd服务的启动、停止、启用与自建服务(2026)

前言:为什么需要理解systemctl

管理Linux服务器,最核心的操作就是管理服务。无论是重启Nginx、查看MySQL状态,还是让某个程序开机自启,都离不开 systemctl 命令。现代Linux发行版(Ubuntu 16.04+、Debian 8+、CentOS 7+、RHEL 7+)全面采用 systemd 作为初始化系统,而 systemctl 就是systemd的主控命令。

掌握 systemctl,就等于掌握了Linux服务管理的钥匙。本文从日常操作自建服务单元,覆盖所有高频场景,附真实命令输出,可以直接在你的VPS上验证。

环境准备

  • Linux系统:Ubuntu 22.04/24.04 或 CentOS 7+/Rocky Linux(本文以Ubuntu 24.04演示)
  • sudo或root权限
  • 已安装 systemd(几乎是标配)
$ cat /etc/os-release | head -3
PRETTY_NAME="Ubuntu 24.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"

$ systemctl --version
systemd 255 (255.4-1ubuntu8)
+PAM +AUDIT +SELINUX +APPARMOR +IMA +SMACK +SECCOMP +GCRYPT -GNUTLS +OPENSSL +ACL +BLKID +CURL +ELFUTILS +FIDO2 +IDN2 -IDN +IPTC +KMOD +LIBCRYPTSETUP +LIBFDISK +PCRE2 +PWQUALITY +P11KIT +QRENCODE +TPM2 +BZIP2 +LZ4 +XZ +ZLIB +ZSTD +BPF_FRAM

一、服务状态管理:查看、启动与停止

1.1 查看所有服务状态

$ systemctl list-units --type=service --all | head -20
  UNIT                          LOAD   ACTIVE SUB     DESCRIPTION
  accounts-daemon.service       loaded active running Accounts Service
  acpid.service                 loaded active running ACPI event daemon
  apparmor.service              loaded active running AppArmor initialization
  apport.service                loaded active running LSB: automatic crash report generation
  atd.service                   loaded active running Deferred execution scheduler
  ...
  nginx.service                 loaded active running A high performance web server and a reverse proxy server

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

关键字段解读:

  • LOAD:单元定义是否成功加载
  • ACTIVE:高级激活状态(active/inactive)
  • SUB:低层子状态(running/exited/dead等)
  • DESCRIPTION:服务描述

1.2 查看单个服务状态

$ systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2026-05-18 08:30:12 UTC; 2h 15min ago
       Docs: man:nginx(8)
   Main PID: 1234 (nginx)
      Tasks: 3 (limit: 2345)
     Memory: 8.2M
        CPU: 124ms
     CGroup: /system.slice/nginx.service
             ├─1234 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             └─1235 nginx: worker process

status 输出中,关键信息

  • Loaded 行显示服务单元路径和是否开机自启(enabled/disabled)
  • Active 行显示当前运行状态和运行时长
  • Main PID 主进程号,排错时非常有用

1.3 启动、停止与重启服务

# 启动服务
$ sudo systemctl start nginx.service
$ systemctl is-active nginx.service
active

# 停止服务
$ sudo systemctl stop nginx.service
$ systemctl is-active nginx.service
inactive

# 重启服务(完整的 Stop + Start)
$ sudo systemctl restart nginx.service

# 重载配置(不中断服务)
$ sudo systemctl reload nginx.service

💡 小技巧: reloadrestart 的区别很重要。修改Nginx配置后,用 reload 可以不中断现有连接完成配置重载,而 restart 会断开所有连接。生产环境优先使用 reload

二、开机自启管理

2.1 启用和禁用开机自启

# 设置开机自启
$ sudo systemctl enable nginx.service
Synchronizing state of nginx.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.
Executing: /usr/lib/systemd/systemd-sysv-install enable nginx

# 禁用开机自启
$ sudo systemctl disable nginx.service
Removed /etc/systemd/system/multi-user.target.wants/nginx.service.

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

# 查看所有开机自启的服务
$ systemctl list-unit-files --type=service --state=enabled | head -20
UNIT FILE                              STATE   PRESET
accounts-daemon.service                enabled enabled
atd.service                            enabled enabled
cron.service                           enabled enabled
nginx.service                          enabled enabled
rsyslog.service                        enabled enabled
ssh.service                            enabled enabled
systemd-timesyncd.service              enabled enabled
udisks2.service                        enabled enabled

2.2 启用但不立即启动 / 立即启动但不启用

# 设置开机自启但不立即启动(适合正在维护的服务)
$ sudo systemctl enable --now nginx.service   # 既启用到开机自启,又立即启动
$ sudo systemctl enable --no-start nginx.service  # 仅设置开机自启,不启动
$ sudo systemctl start --no-enable nginx.service   # 立即启动,但不设置开机自启

三、服务日志查看(journalctl)

systemd 统一管理日志,通过 journalctl 查看。这是排查服务崩溃、配置错误的第一工具

# 查看特定服务的日志
$ sudo journalctl -u nginx.service --no-pager | tail -20
May 18 08:30:12 ubuntu-server nginx[1234]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
May 18 08:30:12 ubuntu-server nginx[1234]: nginx: configuration file /etc/nginx/nginx.conf test is successful
May 18 08:30:12 ubuntu-server systemd[1]: Started A high performance web server and a reverse proxy server.

# 实时追踪日志(类似 tail -f)
$ sudo journalctl -u nginx.service -f

# 查看最近N分钟的日志
$ sudo journalctl -u nginx.service --since "5 min ago"

# 查看今日所有错误级别日志
$ sudo journalctl -p err --since today

# 清理旧日志(释放磁盘空间)
$ sudo journalctl --vacuum-time=7d

💡 对于长期运行的服务器,建议配置 /etc/systemd/journald.conf 中的 MaxUse=500M 限制日志大小,避免日志撑满 /var 分区。

四、实战:自建一个systemd服务单元

这是本文的核心——学会创建自己的 systemd 服务。我们以搭建一个Python 定时数据采集服务为例。

4.1 准备可执行脚本

先创建一个简单的Python脚本:

$ sudo mkdir -p /opt/data-collector
$ sudo tee /opt/data-collector/collect.py << 'EOF'
#!/usr/bin/env python3
import time
import logging
from datetime import datetime

logging.basicConfig(
    filename='/var/log/data-collector.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

def collect_data():
    timestamp = datetime.now().isoformat()
    # 模拟数据采集
    logging.info(f"Data collected at {timestamp}")
    print(f"[{timestamp}] Collection completed")

if __name__ == "__main__":
    while True:
        collect_data()
        time.sleep(300)  # 每5分钟采集一次
EOF

$ sudo chmod +x /opt/data-collector/collect.py

4.2 创建service单元文件

$ sudo tee /etc/systemd/system/data-collector.service << 'EOF'
[Unit]
Description=Data Collector Service - 定时数据采集服务
Documentation=https://example.com/docs
After=network.target network-online.target
Wants=network-online.target

[Service]
Type=simple
User=nobody
Group=nogroup
WorkingDirectory=/opt/data-collector
ExecStart=/usr/bin/python3 /opt/data-collector/collect.py
Restart=always
RestartSec=10
StartLimitInterval=300
StartLimitBurst=5

# 安全加固
ProtectSystem=strict
ReadWritePaths=/var/log
PrivateTmp=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
EOF

单元文件字段详解:

  • [Unit] 段:描述信息和依赖关系。
  • After=network.target 确保网络就绪后启动。
  • Type=simple 表示 ExecStart 启动的进程就是主进程(最常用)。
  • Restart=always 进程退出后自动重启,无人值守必备。
  • RestartSec=10 重启前等待10秒,避免频繁重启。
  • ProtectSystem=strict 保护系统文件不被服务进程意外修改。
  • [Install] 段定义何时启用(通常是 multi-user.target)。

4.3 加载并启动自定义服务

# 重新加载 systemd 配置(每次修改service文件后必做)
$ sudo systemctl daemon-reload

# 启用开机自启
$ sudo systemctl enable data-collector.service
Created symlink /etc/systemd/system/multi-user.target.wants/data-collector.service → /etc/systemd/system/data-collector.service.

# 启动服务
$ sudo systemctl start data-collector.service

# 查看状态
$ sudo systemctl status data-collector.service
● data-collector.service - Data Collector Service - 定时数据采集服务
     Loaded: loaded (/etc/systemd/system/data-collector.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2026-05-18 10:00:00 UTC; 5s ago
   Main PID: 5678 (python3)
      Tasks: 1 (limit: 2345)
     Memory: 12.3M
        CPU: 45ms
     CGroup: /system.slice/data-collector.service
             └─5678 /usr/bin/python3 /opt/data-collector/collect.py

4.4 服务故障排查

# 启动失败时查看详细日志
$ sudo journalctl -u data-collector.service --no-pager

# 查看服务启动超时
$ sudo systemctl show data-collector.service | grep Timeout
TimeoutStartUSec=1min 30s
TimeoutStopUSec=1min 30s

# 手动测试 ExecStart 命令是否正常工作
$ sudo -u nobody /usr/bin/python3 /opt/data-collector/collect.py

五、systemctl进阶操作

5.1 屏蔽与取消屏蔽服务

# 屏蔽服务(防止手动和自动启动)
$ sudo systemctl mask nginx.service
Created symlink /etc/systemd/system/nginx.service → /dev/null.

# 取消屏蔽
$ sudo systemctl unmask nginx.service
Removed /etc/systemd/system/nginx.service.

maskdisable 更彻底——disable只是移除自启符号链接,仍然可以手动 start;而 mask 将服务链接到 /dev/null,任何启动尝试都会被忽略。

5.2 查看服务依赖树

# 查看某服务依赖了哪些其他服务
$ systemctl list-dependencies nginx.service
nginx.service
● ├─system.slice
● ├─network.target
● └─sysinit.target
●   └─systemd-sysusers.service

# 查看反向依赖(哪些服务依赖本服务)
$ systemctl list-dependencies --reverse nginx.service
nginx.service
● └─multi-user.target
●   └─graphical.target

5.3 管理target(运行级别)

# 查看当前运行的target
$ systemctl get-default
multi-user.target

# 切换到救援模式
$ sudo systemctl rescue

# 切换到图形界面模式
$ sudo systemctl isolate graphical.target

# 设置默认target
$ sudo systemctl set-default multi-user.target
Removed /etc/systemd/system/default.target.
Created symlink /etc/systemd/system/default.target → /lib/systemd/system/multi-user.target.

常见问题(FAQ)

Q1: systemctl start 后服务立即退出了,状态显示 inactive(dead),怎么办?

这通常是 Type 设置不当。如果程序启动后 fork 到后台运行(像 Nginx 的 daemon on),应使用 Type=forking 并设置 PIDFile。如果程序不会长时间驻留(执行完就退出),用 Type=oneshot。常规长时间运行的程序用 Type=simple。查看日志 journalctl -u your-service.service -xe 通常能直接定位原因。

Q2: 修改了.service文件后需要执行什么命令?

每次修改 /etc/systemd/system/*.service 后,必须执行 sudo systemctl daemon-reload 让systemd重新加载配置。然后再 restart 服务。如果不执行 daemon-reload,systemd 仍然使用旧配置,修改不会生效。这是一个非常常见的踩坑点。

Q3: 如何让服务在崩溃后自动重启?

在 service 文件的 [Service] 段加上 Restart=alwaysRestartSec=5。systemd 会自动重启退出的进程。还可以设置 StartLimitInterval=600StartLimitBurst=5 来限制10分钟内最多重启5次,防止无限重启导致系统资源耗尽。

Q4: systemctl enable 和 systemctl start 有什么区别?

enable 创建符号链接让服务在开机时自动启动,不影响当前运行状态start 立即启动服务,不影响开机自启设置。通常首次部署时需要 enable + start 两个命令都执行,或者用 enable --now 一步到位。日常管理重启用 restart,配置变更用 reload

总结

本文全面覆盖了 Linux systemctl 的核心操作:

  • 服务状态管理:start/stop/restart/reload/status
  • 开机自启控制:enable/disable/is-enabled
  • 日志追踪:journalctl 查看和排查服务问题
  • 自建服务单元:从零创建可自启的 systemd 服务
  • 进阶技巧:mask屏蔽、依赖树分析、target切换

掌握 systemctl 是Linux运维的基本功。建议在自己的VPS上动手练习一遍,尤其是 自建service文件 的流程——这在实际生产环境中会经常用到。

延伸阅读:

📤 分享这篇文章