systemd 与 systemctl

📂 运维学习

systemd 与 systemctl

是什么

现代 Linux(包括 Ubuntu/CentOS)管理服务的核心。之前的服务管理脚本(sysvinit)又乱又慢,systemd 统一了启动、管理、日志,开机速度快。

常用命令

BASH
systemctl status nginx      # 查看服务状态
systemctl start nginx       # 启动服务
systemctl stop nginx        # 停止服务
systemctl restart nginx     # 重启服务
systemctl enable nginx      # 开机自启
systemctl disable nginx     # 取消开机自启
systemctl list-units        # 列出运行中的服务

服务单位文件

每个服务对应一个 .service 文件,路径在 /etc/systemd/system/

INI
[Unit]
Description=My App
After=network.target

[Service]
ExecStart=/usr/bin/python3 /opt/app/app.py
Restart=always
User=ubuntu

[Install]
WantedBy=multi-user.target

改完要执行:

BASH
systemctl daemon-reload

日志

systemd 自带的日志系统叫 journald:

BASH
journalctl -u nginx            # 查看 nginx 的日志
journalctl -u nginx -f         # 实时滚动日志
journalctl -u nginx --since "2 hours ago"

应用场景

部署自己的 Python/Node 项目时,不用 nohup 挂后台,写一个 .service 文件交给 systemd,开机自启 + 崩溃自动重启(Restart=always),比手写守护脚本靠谱得多。