Skip to content

⚙️ systemd 服务管理

什么是 systemd?

从 CentOS 7 / Ubuntu 15 开始,Linux 默认用 systemd 替代了老迈的 SysV init。它是系统的"大管家"——管理服务启动、日志、定时任务、挂载点,几乎包揽了一切系统管理任务。

💡 提示: 💡 一句话理解:systemctl就是你跟 systemd 对话的命令行工具。管服务用systemctl start/stop/enable,看日志用journalctl。

服务管理核心命令

bash
# 启动/停止/重启/查看状态
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx       # 重新加载配置(不中断服务)
systemctl status nginx       # 查看状态 + 最近日志

 nginx.service - A high performance web server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
     Active: active (running) since Mon 2025-01-20 10:30:15 CST
   Main PID: 1234 (nginx)
      Tasks: 5 (limit: 4915)
     Memory: 12.3M
        CPU: 230ms
     CGroup: /system.slice/nginx.service
             ├─1234 nginx: master process /usr/sbin/nginx
             └─1235 nginx: worker process

# 开机自启 / 取消自启
systemctl enable nginx
systemctl disable nginx

# 同时启动 + 开机自启
systemctl enable --now nginx

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

# 查看所有已启用的服务(开机自启的)
systemctl list-unit-files --type=service --state=enabled

编写自定义 Service 文件

你自己的应用也能用 systemd 管理。比如一个 Node.js 后端:

bash
# 创建服务文件
cat > /etc/systemd/system/myapp.service << 'EOF'
[Unit]
Description=My Node.js Application
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node server.js
Restart=always
RestartSec=5
Environment=NODE_ENV=production
Environment=PORT=3000

# 安全加固
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/opt/myapp/data

[Install]
WantedBy=multi-user.target
EOF

# 重新加载 + 启动
systemctl daemon-reload
systemctl enable --now myapp
systemctl status myapp

💡 提示: 💡 常用 Unit 类型:.service— 服务(最常用).socket— Socket 激活(按需启动服务).timer— 定时任务(替代 cron).mount— 挂载点

journalctl 日志查看

bash
# 查看某个服务的日志
journalctl -u nginx -f              # 实时跟踪
journalctl -u nginx --since "1h ago" # 最近1小时
journalctl -u nginx --since "2025-01-20" --until "2025-01-21"

# 查看启动日志
journalctl -b                       # 本次启动
journalctl -b -1                    # 上次启动

# 按优先级过滤
journalctl -u nginx -p err          # 只看 error 及以上
journalctl -u nginx -p warning      # 只看 warning 及以上

# 磁盘占用(日志可能很大!)
journalctl --disk-usage
Archived and active journals take up 1.2G in the file system.

# 清理旧日志(保留最近 500MB)
journalctl --vacuum-size=500M