编写一个基础 unit 文件

# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target

[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/venv/bin/python app.py
Restart=on-failure
RestartSec=5
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=-/opt/myapp/.env

[Install]
WantedBy=multi-user.target

关键字段说明:

  • Type=simple:主进程即服务本身,适合大多数常驻程序
  • Restart=on-failure:进程异常退出时自动重启,避免服务假死
  • EnvironmentFile=-:前缀 - 表示文件不存在也不报错

常用管理命令

sudo systemctl daemon-reload      # 修改 unit 文件后重新加载
sudo systemctl start myapp
sudo systemctl enable myapp       # 设置开机自启
sudo systemctl status myapp
sudo systemctl restart myapp
sudo systemctl stop myapp
sudo systemctl disable myapp

查看日志

journalctl -u myapp -f            # 实时跟踪日志
journalctl -u myapp --since today
journalctl -u myapp -p err        # 只看错误级别日志

资源限制

对 AI 推理等资源密集型服务,建议在 unit 中限制资源占用,避免单个服务拖垮整机:

[Service]
MemoryMax=16G
CPUQuota=400%

依赖与启动顺序

[Unit]
Requires=postgresql.service
After=postgresql.service

Requires 表示强依赖(依赖服务失败则本服务也失败),After 仅控制启动顺序,两者通常搭配使用。

定时任务:timer 单元替代 cron

# /etc/systemd/system/backup.timer
[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

相比 cron,systemd timer 具备更好的日志集成与依赖管理能力,适合逐步替代传统 crontab。

小结

掌握 unit 文件的编写规范和资源限制配置,是稳定运行自建服务(包括 AI 推理服务)的基础运维能力。