欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

使用 systemd 管理自定义服务:从入门到生产

时间:2026年08月12日 05:26:48 浏览:0

使用 systemd 管理自定义服务:从入门到生产


systemd 已成为 Linux 主流 init 系统,掌握自定义服务编写是运维必备技能。


1. 创建服务单元文件


以 Python Web 应用为例,创建 /etc/systemd/system/myapp.service


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

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/myapp
Environment="PATH=/opt/venv/bin"
ExecStart=/opt/venv/bin/python app.py
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

2. 管理服务生命周期


sudo systemctl daemon-reload        # 重新加载单元文件
sudo systemctl start myapp
sudo systemctl enable myapp # 开机自启
sudo systemctl status myapp # 查看状态
sudo systemctl restart myapp # 重启

3. 日志查看


journalctl -u myapp -f              # 实时跟踪
journalctl -u myapp --since "2025-01-01" --until "2025-01-02"

4. 环境变量与依赖



  • 使用 EnvironmentFile=-/etc/myapp.conf 加载外部配置文件。

  • After=network.target 确保网络就绪后再启动。


5. 常见问题排错



  • 启动失败:查看 systemctl status myapp 和 journal。

  • 权限不足:确保 User/Group 对工作目录和文件有读写权限。

  • 环境变量未加载:检查 EnvironmentEnvironmentFile 路径。


生产环境建议使用 Type=notify 配合 sd_notify 实现健康检查,或结合 ExecStartPre 执行前置检查。