菜单

Administrator
发布于 2026-10-10 / 2 阅读
0
0

Linux 进阶 L16:systemd——Linux 的服务大总管

Linux 进阶 L16:systemd——Linux 的服务大总管

学到现在,你天天跟 systemctl start/stop/status 打交道,但 systemd 到底是个啥?今天把它讲透。

systemd 是什么

Linux 开机后运行的第一个进程,PID 永远是 1。它是整个系统的"大总管":启动所有服务、死了的服务自动拉起来、管日志、还能当定时任务用。

systemctl:跟它打交道的命令

systemctl status sshd        # 看服务状态(最常用)
systemctl start docker       # 启动
systemctl stop docker        # 停止
systemctl restart nginx      # 重启
systemctl reload nginx       # 重载配置(不断服务)
systemctl enable docker      # 开机自启
systemctl disable docker     # 取消开机自启

reload 和 restart 的区别:reload 只重读配置文件,服务不中断;restart 是整个杀掉重开。

读懂 status 输出

systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled)
     Active: active (running) since Thu 2026-10-09 23:06:55 UTC

Loaded:配置文件在哪,enabled 表示开机自启。Active:running 正常,dead 挂了,failed 启动失败。

服务配置文件

cat /lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
After=network-online.target

[Service]
ExecStart=/usr/bin/dockerd -H fd://
Restart=always

[Install]
WantedBy=multi-user.target

[Unit]:描述和依赖。[Service]:怎么启动,Restart=always 挂了自动重启。[Install]:开机启动时带上它。

自己写一个服务

sudo vim /etc/systemd/system/myapp.service
[Unit]
Description=我的小应用
After=network.target

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

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp

journalctl:查服务日志

journalctl -u sshd              # 看 sshd 的日志
journalctl -u sshd -f           # 实时跟
journalctl -u nginx --since "1 hour ago"
journalctl -p err -b            # 本次开机的错误

systemd timer:定时任务

[Unit]
Description=每天凌晨 2 点备份
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable --now backup.timer
systemctl list-timers

小结

命令

干啥

systemctl status/start/stop/restart

服务启停查

systemctl enable/disable

开机自启开关

systemctl daemon-reload

重载配置

journalctl -u 服务名

查服务日志


评论