Ubuntu 下使用 systemd 实现 Python 代理服务开机自启动
Ubuntu 下使用 systemd 实现 Python 代理服务开机自启动
在 Ubuntu 系统中,为了让一个 Python 编写的代理程序(xf_proxy.py)能够在系统启动时自动运行,并具备自动重启、日志管理等能力,我采用了 systemd 服务。本文记录了配置过程中遇到的典型问题及解决过程。
一、准备工作
代理脚本位于 /home/qwe/xf_proxy.py,使用虚拟环境 myenv 中的 Python 解释器。手动运行正常:
/home/qwe/myenv/bin/python3 /home/qwe/xf_proxy.py
代理监听 127.0.0.1:8080。
二、创建 systemd 服务单元文件
使用 root 权限创建 /etc/systemd/system/xf_proxy.service,初始内容如下:
[Unit]
Description=Xunfei Proxy for OpenClaw
After=network.target
[Service]
Type=simple
User=qwe
WorkingDirectory=/home/qwe
ExecStart=/home/qwe/myenv/bin/python3 /home/qwe/xf_proxy.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
三、启动失败及排查
1. 错误 status=217/USER
执行 sudo systemctl start xf_proxy.service 后,状态显示:
Active: failed (Result: exit-code)
Main PID: ... code=exited, status=217/USER
Failed to determine user credentials: No such process
原因:systemd 无法解析用户名 qwe(尽管用户存在)。
解决:改用用户 UID:
User=1000 # 通过 id qwe 获取
修改后重试,错误依旧。
2. 错误 status=200/CHDIR
即使将 User 改为 UID 或删除用户行(以 root 运行),仍出现:
code=exited, status=200/CHDIR
Changing to the requested working directory failed: No such file or directory
原因:systemd 默认开启了 ProtectHome=yes 安全策略,阻止服务访问 /home 目录。
排查:使用 systemctl show xf_proxy.service | grep ProtectHome 确认设置。
解决:在 [Service] 段添加 ProtectHome=no,允许访问 /home,并且删除WorkingDirectory:
ProtectHome=no
# WorkingDirectory=/home/qwe
四、最终成功的服务配置
经过调整,服务文件内容如下:
[Unit]
Description=Xunfei Proxy for OpenClaw
After=network.target
[Service]
Type=simple
# WorkingDirectory=/home/qwe
ExecStart=/home/qwe/myenv/bin/python3 /home/qwe/xf_proxy.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
ProtectHome=no
[Install]
WantedBy=multi-user.target
执行以下命令生效:
sudo systemctl daemon-reload
sudo systemctl start xf_proxy.service
sudo systemctl status xf_proxy.service
输出显示 Active: active (running),并看到 Flask 服务启动日志:
* Running on http://127.0.0.1:8080
五、管理开机自启动
启用开机自启
sudo systemctl enable xf_proxy.service
禁用开机自启
sudo systemctl disable xf_proxy.service
手动控制服务
sudo systemctl start xf_proxy.service # 启动
sudo systemctl stop xf_proxy.service # 停止
sudo systemctl restart xf_proxy.service # 重启
查看服务日志
sudo journalctl -u xf_proxy.service -f # 实时跟踪
六、总结
通过 systemd 管理服务时,需要关注:
- 用户解析(可使用 UID 避免用户名识别问题)
- 安全策略(
ProtectHome等可能导致工作目录访问失败) - 工作目录是否存在且可访问
按照以上步骤,代理服务可稳定实现开机自启动,并具备自动恢复能力。
浙公网安备 33010602011771号