Ubuntu部署Django后断开连接服务终止,如何让服务持续运行?
让Gunicorn在Ubuntu后台持续运行的几种方案
方案1:用nohup直接后台启动(快速临时方案)
这是最简单的临时后台运行方式,适合快速测试:
- 执行命令:
nohup gunicorn --bind 0.0.0.0:8000 myapp.wsgi & - 可选:指定日志文件避免输出到默认的
nohup.out:nohup gunicorn --bind 0.0.0.0:8000 myapp.wsgi > /var/log/gunicorn.log 2>&1 & - 停止服务:先查找Gunicorn进程ID,再杀掉
ps aux | grep gunicorn kill <进程ID>
方案2:用screen/tmux(适合临时调试,可恢复会话)
如果需要后续重新连接查看服务输出,用终端会话工具更方便:
用screen:
- 安装screen:
sudo apt update && sudo apt install screen - 启动新会话:
screen - 在会话内启动Gunicorn:
gunicorn --bind 0.0.0.0:8000 myapp.wsgi - 按下
Ctrl+A+D脱离会话,此时关闭终端服务仍会运行 - 重新连接会话:
screen -r
用tmux(功能更强的替代):
- 安装tmux:
sudo apt update && sudo apt install tmux - 启动新会话:
tmux - 启动Gunicorn后,按下
Ctrl+B+D脱离会话 - 重新连接:
tmux attach
方案3:用systemd服务(生产环境首选,稳定+开机自启)
生产环境下,用systemd管理服务是最可靠的方式,支持开机自动启动、状态监控、日志管理:
创建Gunicorn的systemd服务文件:
sudo nano /etc/systemd/system/gunicorn.service写入以下配置(注意替换你的用户名、项目路径、虚拟环境路径):
[Unit] Description=Gunicorn daemon for Django myapp API After=network.target [Service] User=your_username Group=www-data WorkingDirectory=/home/your_username/django-project ExecStart=/home/your_username/django-project/venv/bin/gunicorn --bind 0.0.0.0:8000 myapp.wsgi [Install] WantedBy=multi-user.targetUser:运行服务的系统用户(比如你的登录用户)WorkingDirectory:Django项目的根目录(包含manage.py的目录)ExecStart:Gunicorn的完整路径,如果用了虚拟环境,要写虚拟环境bin目录下的gunicorn
重新加载systemd配置:
sudo systemctl daemon-reload启动Gunicorn服务:
sudo systemctl start gunicorn设置开机自启:
sudo systemctl enable gunicorn常用管理命令:
- 查看服务状态:
sudo systemctl status gunicorn - 重启服务:
sudo systemctl restart gunicorn - 停止服务:
sudo systemctl stop gunicorn
- 查看服务状态:
内容的提问来源于stack exchange,提问作者CanKURT
相关产品推荐
相关产品推荐

