如何在Ubuntu(Nginx+Gunicorn)服务器上保持django-q持续运行
让Django-Q在Ubuntu服务器后台持续运行的方法
方法一:使用systemd(推荐,Ubuntu标准服务管理)
这是最稳定可靠的方案,能让Django-Q以系统服务身份运行,支持开机自启、崩溃自动重启。
- 创建systemd服务配置文件
sudo nano /etc/systemd/system/django-q.service
- 写入以下配置(替换占位符为你的实际信息)
[Unit] Description=Django-Q Worker Service After=network.target [Service] User=your_server_username Group=www-data WorkingDirectory=/your/django/project/root/path ExecStart=/your/virtualenv/path/bin/python manage.py qcluster Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
User:替换为运行服务的服务器用户名WorkingDirectory:Django项目根目录(包含manage.py的文件夹)ExecStart:虚拟环境内python的绝对路径,加上manage.py qcluster命令
- 重载systemd并启动服务
sudo systemctl daemon-reload sudo systemctl start django-q sudo systemctl enable django-q # 设置开机自启
- 查看服务状态或日志
sudo systemctl status django-q # 查看详细日志 journalctl -u django-q -f
方法二:使用nohup(快速临时方案)
适合临时测试,无需开机自启的场景:
nohup /your/virtualenv/path/bin/python manage.py qcluster &
nohup会让程序忽略终端关闭信号,输出默认写入当前目录的nohup.out文件&将进程放到后台运行
停止进程的话,先查找PID再终止:
ps aux | grep qcluster kill -9 <找到的进程ID>
方法三:使用screen/tmux(会话持久化)
适合需要随时重新连接查看进程输出的场景:
用screen:
- 安装screen
sudo apt install screen
- 创建新会话
screen -S django-q
- 在会话内运行Django-Q命令
/your/virtualenv/path/bin/python manage.py qcluster
- 按
Ctrl+A再按D脱离会话,关闭终端后进程仍会运行 - 重新连接会话
screen -r django-q
- 关闭会话:在会话内按
Ctrl+D,或者执行screen -S django-q -X quit
用tmux(更现代的替代):
- 安装tmux
sudo apt install tmux
- 创建新会话
tmux new -s django-q
- 运行Django-Q命令后,按
Ctrl+B再按D脱离会话 - 重新连接会话
tmux attach -t django-q
- 关闭会话
tmux kill-session -t django-q
内容的提问来源于stack exchange,提问作者pmm21 assistant
相关产品推荐
相关产品推荐

