跳转至

10 - 服务管理与进程控制(systemd) ⚙️

前提条件 ✅

  • 已完成第一阶段所有内容(基础部署、apt 源、SSH 安全加固、fail2ban 等)
  • 以 ops 用户登录(具有 sudo 权限)
  • 系统运行在 Debian 12 Bookworm
  • 虚拟机环境:VMware Workstation Pro

详细步骤 🛠️

  1. systemd 核心概念速览
  2. service:最常见的服务单元(如 ssh、nginx、docker)
  3. target:服务组(如 multi-user.target 相当于 runlevel 3)
  4. timer:定时任务(替代 cron 的现代方式)
  5. socket:按需激活服务

  6. 查看系统和服务状态

    systemctl status                # 当前默认 target 和基本信息
    systemctl get-default           # 当前默认运行级别(通常 multi-user.target)
    systemctl list-units --type=service --state=running
    systemctl list-unit-files --type=service | grep enabled
    

  7. 服务基本操作

    # 以 ssh 为例
    sudo systemctl status ssh
    
    sudo systemctl start ssh
    sudo systemctl stop ssh
    sudo systemctl restart ssh
    sudo systemctl reload ssh       # 平滑重载配置(不中断连接)
    
    sudo systemctl enable ssh       # 开机自启
    sudo systemctl disable ssh      # 取消开机自启
    
    # 屏蔽服务(防止被意外启动)
    sudo systemctl mask avahi-daemon
    sudo systemctl unmask avahi-daemon
    

  8. 日志查看与实时跟踪(journalctl)

    journalctl -u ssh -n 200                  # ssh 最近 200 行日志
    journalctl -u ssh -f                      # 实时跟踪(类似 tail -f)
    journalctl -u ssh --since "today"         # 今天的所有 ssh 日志
    journalctl -b -p warning..emerg           # 本次启动的警告及以上级别日志
    journalctl --disk-usage                   # 查看日志占用空间
    

  9. 创建自定义 systemd 服务(生产常用)
    示例:创建一个简单的后台循环脚本服务

先创建测试脚本:

sudo mkdir -p /opt/testservice
sudo nano /opt/testservice/hello.sh

脚本内容:

#!/bin/bash
while true; do
    echo "$(date) - Hello from systemd service" >> /var/log/hello.log
    sleep 60
done

赋予执行权限:

sudo chmod +x /opt/testservice/hello.sh

创建服务单元文件:

sudo nano /etc/systemd/system/hello.service

内容:

[Unit]
Description=Simple Hello World Service
After=network.target

[Service]
Type=simple
ExecStart=/opt/testservice/hello.sh
Restart=always
User=ops
StandardOutput=append:/var/log/hello.log
StandardError=append:/var/log/hello.log

[Install]
WantedBy=multi-user.target

加载、启动、验证:

sudo systemctl daemon-reload
sudo systemctl enable hello
sudo systemctl start hello
sudo systemctl status hello
tail -f /var/log/hello.log

  1. 清理与优化
    sudo journalctl --vacuum-time=30d     # 删除 30 天前日志
    sudo systemctl reset-failed           # 清除失败状态
    

实践任务 🎯

  1. 查看当前系统所有运行中的服务,找出内存占用前 5 的服务
  2. 临时停止 ssh 服务,再启动,确认 2222 端口恢复监听
  3. 创建上述 hello.service 示例服务,启用开机自启,验证日志是否正常写入
  4. 用 journalctl -u hello -f 实时观察服务输出

自测问题 ❓

  1. systemctl enablesystemctl start 的区别是什么?
  2. 如何让服务在网络完全就绪后再启动?
  3. journalctl -b -p err 显示的是什么内容?
  4. 如果一个服务一直重启(Restart=always),如何临时停止而不删除文件?

总结 📌

systemd 是 Debian 现代运维的核心,掌握服务状态查看、启动控制、日志追踪和自定义单元是后续所有服务类章节的基础。
生产环境中,优先使用 systemctl + journalctl 排查问题,而不是旧的 service 命令或 /var/log 下的文本日志。