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

如何通过Azure DevOps Pipeline部署Python控制器并解决gunicorn运行问题

解决Azure DevOps Pipeline中Gunicorn进程随任务终止的问题

问题原因

Azure DevOps Agent执行Pipeline任务时会创建专属shell会话,会话内启动的后台进程(包括用--daemon参数的Gunicorn)会在会话结束(Pipeline任务完成)时被系统终止;若Gunicorn前台运行,则会阻塞任务导致Pipeline无法正常结束。


方案一:用systemd托管Gunicorn服务(推荐)

将Gunicorn注册为系统服务,由systemd负责进程的启动、监控和自动重启,不受Agent会话生命周期影响。

  1. 创建systemd服务文件
    在部署服务器上创建/etc/systemd/system/python-api.service,内容如下(替换占位符为实际信息):
[Unit]
Description=Python REST API Service
After=network.target

[Service]
User=deploy-user
WorkingDirectory=$(System.DefaultWorkingDirectory)
ExecStart=/usr/local/bin/gunicorn -w 1 -b 0.0.0.0:8081 controller:app
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
  • WorkingDirectory可直接使用Pipeline内置变量$(System.DefaultWorkingDirectory),对应Agent拉取代码的目录。
  • Restart=always确保进程崩溃后自动重启。
  1. 修改Pipeline脚本步骤
    替换原脚本中的Gunicorn启动命令为systemd服务管理命令:
# 安装依赖
pip3 install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir --user -r requirements.txt

# 更新服务配置并重启
sudo systemctl daemon-reload
sudo systemctl restart python-api.service

方案二:使用nohup分离进程(临时应急方案)

通过nohup让Gunicorn忽略会话结束信号,同时后台运行并输出日志:

# 安装依赖
pip3 install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir --user -r requirements.txt

# 启动Gunicorn并分离进程
nohup /usr/local/bin/gunicorn -w 1 -b 0.0.0.0:8081 controller:app > gunicorn-run.log 2>&1 &

该方案无需额外配置,但缺少进程监控和自动重启机制,仅适合临时测试场景。


更优的Python REST API自动化部署方案

  1. 容器化部署
    将应用打包为Docker镜像,通过Pipeline拉取最新镜像并重启容器。容器化实现了环境一致性,避免依赖冲突,还可配合Docker Compose管理服务,简化多组件应用的部署流程。

  2. 进程管理工具(如supervisord)
    使用supervisord管理应用进程,支持进程监控、日志收集、自动重启等功能,适合需要同时管理多个后台进程的场景,配置灵活且轻量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:21:24