avatar Akirava's Blog

Debian 12 中 systemctl 与 systemd 服务的使用

1 注册 systemctl 服务

编辑 .service 文件

$ nano /etc/systemd/system/myapp.service

文件内容示例

[Unit]
Description=My Custom Application
After=network.target

[Service]
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=always
User=nobody
Group=nogroup

[Install]
WantedBy=multi-user.target

重新加载 systemd 配置

$ systemctl daemon-reload

启动服务

$ systemctl start myapp

开机自启

$ systemctl enable myapp

2 完全卸载一个 systemctl 服务

停止服务

$ systemctl stop myapp

禁用开机自启

$ systemctl disable myapp

删除服务文件

$ rm /etc/systemd/system/myapp.service

重载 systemd 配置

$ systemctl daemon-reload

(可选)清理残留信息

$ systemctl reset-failed myapp

3 查看服务日志(journalctl

查看服务日志

$ journalctl -u nginx

实时跟踪日志

$ journalctl -f -u nginx

最近 50 行日志

$ journalctl -u nginx -n 50

当前启动日志

$ journalctl -u nginx -b

按时间范围过滤

$ journalctl --since "1 hour ago" -u nginx

按错误级别过滤

$ journalctl -u nginx -p err