之前部署 Nginx 时用到的 systemctl enable --now nginx,背后就是 systemd。它负责管理 Linux 上所有服务的生命周期。

一、常用命令

systemctl start  nginx   # 启动
systemctl stop   nginx   # 停止
systemctl restart nginx   # 重启
systemctl status  nginx   # 查看状态
systemctl enable  nginx   # 开机自启
journalctl -u nginx -f     # 实时看服务日志

二、编写自己的 service

假设有一个 Python 程序要做成服务,新建 /etc/systemd/system/myapp.service

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

[Service]
ExecStart=/app/.venv/bin/python /app/main.py
Restart=always
User=app

[Install]
WantedBy=multi-user.target

三、生效

systemctl daemon-reload       # 重新加载配置
systemctl enable --now myapp   # 启用并启动
Restart=always 表示进程崩溃后自动重启,是保证服务高可用的关键配置。

四、小结

把程序托管给 systemd,比用 nohup、screen 更专业、更可靠。学会写 unit 文件,是 Linux 运维的基本功。