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

将含WebSocket与Celery的Django应用从Heroku迁移至Azure App Service遇阻

解决Django + Daphne + Celery迁移到Azure App Service的两个核心问题

我之前帮朋友处理过几乎一模一样的迁移场景,给你整理几个经过验证的方案,应该能解决你的问题:

一、让Daphne在Azure App Service正常运行(支持WebSocket)

Azure其实完全支持Daphne,你之前启动失败大概率是环境变量或配置没到位,按以下步骤检查:

  1. 确认依赖和WebSocket设置
    • 确保requirements.txt里包含daphne(建议指定稳定版本,比如daphne==4.0.0),以及Django、Celery等核心依赖。
    • 登录Azure Portal,进入你的App Service → 配置 → 常规设置,找到「Web sockets」选项,务必开启它(默认可能是关闭的,这会直接导致WebSocket连接失败)。
  2. 调整Daphne启动命令
    Azure的端口变量在Linux环境用$PORT,Windows环境用%PORT%,如果你用的是Linux容器,直接用这个命令作为启动项:
    daphne backend.asgi:application --port $PORT --bind 0.0.0.0 -v 0
    
    如果启动时提示找不到backend模块,记得添加PYTHONPATH配置:
    export PYTHONPATH=/home/site/wwwroot:$PYTHONPATH && daphne backend.asgi:application --port $PORT --bind 0.0.0.0 -v 0
    
    (/home/site/wwwroot是Azure Linux App Service的默认项目根目录)

二、同时启动Daphne和Celery Worker进程

Azure App Service默认只允许一个启动命令,所以需要用进程管理器或后台脚本管理多个进程,推荐两种方案:

方案1:用Bash脚本(快速上手)

  1. 在项目根目录创建start.sh脚本,内容如下:
    #!/bin/bash
    # 设置Python路径,确保能找到项目模块
    export PYTHONPATH=/home/site/wwwroot:$PYTHONPATH
    # 后台启动Daphne
    daphne backend.asgi:application --port $PORT --bind 0.0.0.0 -v 0 &
    # 前台启动Celery Worker(Azure需要一个前台进程维持Web App运行)
    celery worker -A backend --loglevel=debug --concurrency=8
    
  2. 给脚本添加执行权限:
    本地运行chmod +x start.sh,或者在Azure App Service的SSH终端里执行同样的命令。
  3. 在Azure App Service的启动命令中设置为:
    ./start.sh
    

方案2:用Supervisord(更稳定,生产环境推荐)

如果需要进程监控和自动重启(比如某个进程崩溃后自动恢复),推荐用Supervisord:

  1. 在requirements.txt中添加Supervisor依赖:
    supervisor==4.2.5
    
  2. 在项目根目录创建supervisord.conf配置文件:
    [supervisord]
    nodaemon=true  # 让Supervisord在前台运行,满足Azure的要求
    
    [program:daphne]
    command=daphne backend.asgi:application --port %(ENV_PORT)s --bind 0.0.0.0 -v 0
    directory=/home/site/wwwroot
    autostart=true
    autorestart=true
    stdout_logfile=/dev/stdout  # 把日志输出到Azure的日志系统
    stdout_logfile_maxbytes=0
    stderr_logfile=/dev/stderr
    stderr_logfile_maxbytes=0
    
    [program:celery_worker]
    command=celery worker -A backend --loglevel=debug --concurrency=8
    directory=/home/site/wwwroot
    autostart=true
    autorestart=true
    stdout_logfile=/dev/stdout
    stdout_logfile_maxbytes=0
    stderr_logfile=/dev/stderr
    stderr_logfile_maxbytes=0
    
  3. 在Azure App Service的启动命令中设置为:
    supervisord -c supervisord.conf
    

额外注意事项

  • Celery Broker配置:推荐用Azure Redis Cache作为Celery的消息队列,确保settings.py中的CELERY_BROKER_URL正确指向Azure Redis的连接字符串,并且Redis的防火墙规则允许App Service访问(可以设置为「允许所有Azure服务访问此资源」)。
  • 日志排查:如果启动失败,去Azure Portal的App Service → 日志 → 日志流查看实时日志,这是排查问题最有效的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:52:57