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配置与问题现象
- 配置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/ - 加载并启用服务:
sudo systemctl daemon-reload sudo systemctl enable mybig_app.service - 启动异常:执行
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
相关产品推荐
相关产品推荐

