如何在Linux服务器上保持django_q集群持续运行?
Django Q集群后台持续运行解决方案
首先要明确:官方文档提到的「无需使用监管程序即可运行」是指Django Q自带内部进程管理,可自动恢复崩溃的工作进程,并非指其默认以后台守护进程形式运行,shell会话关闭时发送的SIGHUP信号依然会终止前台运行的qcluster进程,可通过以下几种方案解决:
方案1:nohup 临时后台运行
适合临时测试、快速部署场景,无需额外配置:
- 执行命令启动后台进程,所有输出会写入指定日志文件:
nohup python manage.py qcluster > qcluster_output.log 2>&1 & - 如需停止服务,先查找进程ID再执行kill即可:
ps aux | grep qcluster kill 对应的进程ID
方案2:systemd 系统服务(生产环境首选)
稳定性最高,支持开机自启、异常自动重启、日志统一管理:
- 新建systemd服务文件
/etc/systemd/system/django-q.service,替换文件中路径、用户等信息为实际配置:
[Unit] Description=Django Q Cluster Service After=network.target mysql.service redis.service # 可追加依赖的其他服务如数据库、缓存 [Service] User=www-data # 替换为你的服务器运行用户 Group=www-data # 替换为对应的用户组 WorkingDirectory=/www/your_django_project_root # 替换为Django项目根目录路径 ExecStart=/www/your_virtualenv/bin/python manage.py qcluster # 替换为虚拟环境Python路径(无虚拟环境可直接写python) Restart=always RestartSec=5 StandardOutput=journal+console StandardError=journal+console [Install] WantedBy=multi-user.target
- 执行以下命令完成配置:
- 重载systemd配置:
sudo systemctl daemon-reload - 启动Django Q服务:
sudo systemctl start django-q - 设置开机自动启动:
sudo systemctl enable django-q - 查看服务运行状态:
sudo systemctl status django-q - 实时查看运行日志:
journalctl -u django-q -f
方案3:screen/tmux 终端复用
适合需要随时查看qcluster实时终端输出的场景:
以screen为例操作步骤如下:
- 安装screen:
Debian/Ubuntu系统:sudo apt install screen
CentOS/RHEL系统:sudo yum install screen - 创建名为django-q的会话:
screen -S django-q - 在新打开的会话窗口中正常执行启动命令:
python manage.py qcluster - 按快捷键
Ctrl + A + D脱离会话,此时进程会继续在后台运行,关闭shell也不会终止 - 如需重新进入会话查看输出:
screen -r django-q
内容的提问来源于stack exchange,提问作者Lazaron Shyta
相关产品推荐
相关产品推荐

