You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为使用Poetry的FastAPI服务配置Systemd守护进程单元并修复启动错误?

解决Systemd启动FastAPI服务时exit-code 127错误

问题根源

exit code 127的核心原因是systemd执行环境找不到poetry命令。普通用户shell会加载~/.profile或~/.bashrc这类配置文件,把poetry的安装路径加入系统PATH,但systemd启动服务时不会加载这些用户级配置,导致默认PATH里没有poetry的位置。

解决方案

方案1:修改启动脚本,使用poetry绝对路径

  1. 在终端执行以下命令,获取poetry的绝对路径:

    which poetry
    

    输出类似/root/.local/bin/poetry(根据你的安装路径可能不同)。

  2. 修改/root/my-dir/script.sh,把poetry替换成刚才得到的绝对路径:

    #!/bin/bash
    /root/.local/bin/poetry run python main.py
    
  3. 重新加载systemd配置并重启服务:

    sudo systemctl daemon-reload
    sudo systemctl restart gunicorn
    

方案2:在Systemd服务文件中指定PATH环境变量

修改/etc/systemd/system/gunicorn.service的[Service]段,添加Environment行,将poetry所在目录加入PATH:

[Unit]
Description=gunicorn daemon for FastAPI app
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/root/my-dir
Environment="PATH=/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
ExecStart=/root/my-dir/script.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

之后执行以下命令使配置生效:

sudo systemctl daemon-reload
sudo systemctl restart gunicorn

额外检查

确保启动脚本有可执行权限(可再次确认):

chmod +x /root/my-dir/script.sh

内容的提问来源于stack exchange,提问作者CarloDiPalma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 07:42:47