部署Django Channels:退出服务器Shell后如何保持Daphne运行?
我太懂你现在的困扰了——刚在DigitalOcean的Ubuntu 16.04.4上折腾好Andrew Godwin的multichat示例,结果退出服务器Shell的瞬间,Daphne直接罢工,这搁谁都头疼。毕竟生产环境咱要的是服务能稳稳当当跑着,下面给你几个实用方案,尤其是生产环境最靠谱的systemd配置方法:
方案一:用systemd管理Daphne(生产环境首选)
Ubuntu默认的systemd是专门管后台服务的利器,能让Daphne常驻后台、开机自启,甚至意外挂了还能自动重启,完美适配生产场景。
创建systemd服务配置文件
先打开编辑器创建服务文件:sudo nano /etc/systemd/system/daphne.service然后把下面内容粘进去,记得把
your_username、/path/to/your/project、your_project换成你自己的实际信息:[Unit] Description=Daphne ASGI server for Django Channels multichat After=network.target [Service] User=your_username WorkingDirectory=/path/to/your/project ExecStart=/path/to/your/venv/bin/daphne -b 0.0.0.0 -p 8001 your_project.asgi:application Restart=always RestartSec=3 [Install] WantedBy=multi-user.target简单解释下关键配置:
WorkingDirectory填你的Django项目根目录ExecStart要指向虚拟环境里的daphne命令,还有正确的ASGI应用路径Restart=always确保服务崩了能自动拉起来
启用并启动服务
执行这几条命令让配置生效:sudo systemctl daemon-reload sudo systemctl start daphne sudo systemctl enable daphne这下Daphne就彻底后台常驻了,就算你退出Shell、服务器重启,它都会乖乖自己跑起来。
检查状态和日志
想确认服务是否正常运行:sudo systemctl status daphne看实时运行日志:
sudo journalctl -u daphne -f
方案二:用nohup临时运行(适合测试场景)
如果只是临时测功能,不想折腾systemd,nohup能快速让Daphne后台跑:
nohup /path/to/your/venv/bin/daphne -b 0.0.0.0 -p 8001 your_project.asgi:application &
nohup会让进程忽略退出信号,退出Shell也不影响&把进程扔到后台- 运行日志默认存在当前目录的
nohup.out里
不过这个方法缺点很明显:服务器重启后进程不会自动启动,崩了也没人管,只能临时用用。
方案三:用screen/tmux保持会话(适合调试)
要是你需要时不时进去看Daphne的运行状态,终端复用工具screen或tmux就很合适:
用screen:
- 先装screen(没装的话):
sudo apt-get install screen - 创建一个专属会话:
screen -S daphne_session - 在会话里启动Daphne,然后按
Ctrl+A再按D,就能脱离会话(此时Daphne还在后台跑) - 下次登录服务器,重新连会话:
screen -r daphne_session
用tmux(功能更强大):
- 安装tmux:
sudo apt-get install tmux - 创建会话:
tmux new -s daphne_session - 启动Daphne后,按
Ctrl+B再按D脱离会话 - 重新连接:
tmux attach -t daphne_session
同样,这种方法也不适合生产环境,服务器重启会话就没了,主要用来调试和临时观察运行状态。
总结一句:生产环境无脑选systemd,稳得一批;测试调试用nohup、screen/tmux凑活就行。
内容的提问来源于stack exchange,提问作者nusantara




