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

Django应用systemd启动超时但手动运行正常问题求助

Django应用通过systemd启动超时但实际可访问的问题

环境与手动启动情况

  • 部署环境:树莓派局域网服务器,应用路径/var/www/mybig_app/,依赖虚拟环境/var/www/mybig_app/venv/
  • 网络配置:gunicorn 19.9.0绑定localhost:8003,通过nginx转发至3003端口
  • 手动启动正常:在/var/www/mybig_app/目录下执行以下任一命令,等待约5秒后,局域网设备可正常访问应用所有功能:
    python manage.py runserver localhost:8003
    
    或
    /var/www/mybig_app/venv/bin/gunicorn mybig_app.wsgi:application --bind localhost:8003
    

systemd配置与问题现象

  1. 配置service文件与软链接:
    ln -s /var/www/mybig_app/infrastructure/systemd/mybig_app.service /etc/systemd/system/
    ln -s /var/www/mybig_app/infrastructure/systemd/mybig_app.service /etc/systemd/system/multi-user.target.wants/
    
  2. 加载并启用服务:
    sudo systemctl daemon-reload
    sudo systemctl enable mybig_app.service
    
  3. 启动异常:执行sudo systemctl start mybig_app.service后命令卡住,等待15秒超时后提示:
    Job for mybig_app.service failed because a timeout was exceeded.
    See "systemctl status mybig_app.service" and "journalctl -xe" for details.
    
    日志显示启动超时后终止服务,但卡住期间局域网设备仍能正常访问和使用应用。

猜想与已尝试操作

猜想

  • 可能与mybig_app.service配置有关(但相同流程在其他应用上正常,仅修改了项目名称)
  • 项目依赖库较旧(始于2018年)
  • 已在service文件中设置更长超时参数:
    [Service]
    ...
    RestartSec=15s
    TimeoutStartSec=15s
    TimeoutSec=15s
    

已尝试操作

  • 删除并重新创建虚拟环境
  • 重启服务器
  • 将超时时间增加至115秒

问题根源

问题出在service文件的Type=notify配置上。

systemd的Type=notify模式要求进程启动后主动向systemd发送就绪通知,确认服务完全启动。但你使用的gunicorn 19.9.0版本不支持向systemd发送就绪信号——gunicorn直到20版本才添加该功能。

手动启动时gunicorn正常运行并处理请求,但通过systemd以Type=notify启动时,systemd会一直等待就绪信号,直到超时后终止进程(此时进程实际已在处理请求,所以设备仍能访问)。

解决方法

修改mybig_app.service的[Service]段,将Type=notify改为Type=simple,并移除NotifyAccess=all配置:

[Service]
WorkingDirectory=/var/www/mybig_app/
ExecStart=/var/www/mybig_app/venv/bin/gunicorn mybig_app.wsgi:application --bind localhost:8003

StandardOutput=file:/var/log/mybig_app/mybig_app-stdout.log
StandardError=file:/var/log/mybig_app/mybig_app-stderr.log

Restart=always
RestartSec=15s
TimeoutStartSec=15s
TimeoutSec=15s

KillSignal=SIGQUIT

# 替换为Type=simple
Type=simple
# 移除或注释NotifyAccess=all
# NotifyAccess=all

修改后重新加载配置并启动服务:

sudo systemctl daemon-reload
sudo systemctl start mybig_app.service

Type=simple是systemd默认服务类型,适用于启动后直接进入主循环的进程,无需发送就绪通知,完全匹配gunicorn 19.9.0的运行模式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:03:20