You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 安装screen:
    sudo apt update && sudo apt install screen
    
  2. 启动新会话:
    screen
    
  3. 在会话内启动Gunicorn:
    gunicorn --bind 0.0.0.0:8000 myapp.wsgi
    
  4. 按下Ctrl+A+D脱离会话,此时关闭终端服务仍会运行
  5. 重新连接会话:
    screen -r
    

用tmux(功能更强的替代):

  1. 安装tmux:
    sudo apt update && sudo apt install tmux
    
  2. 启动新会话:
    tmux
    
  3. 启动Gunicorn后,按下Ctrl+B+D脱离会话
  4. 重新连接:
    tmux attach
    

方案3:用systemd服务(生产环境首选,稳定+开机自启)

生产环境下,用systemd管理服务是最可靠的方式,支持开机自动启动、状态监控、日志管理:

  1. 创建Gunicorn的systemd服务文件:

    sudo nano /etc/systemd/system/gunicorn.service
    
  2. 写入以下配置(注意替换你的用户名、项目路径、虚拟环境路径):

    [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.target
    
    • User:运行服务的系统用户(比如你的登录用户)
    • WorkingDirectory:Django项目的根目录(包含manage.py的目录)
    • ExecStart:Gunicorn的完整路径,如果用了虚拟环境,要写虚拟环境bin目录下的gunicorn
  3. 重新加载systemd配置:

    sudo systemctl daemon-reload
    
  4. 启动Gunicorn服务:

    sudo systemctl start gunicorn
    
  5. 设置开机自启:

    sudo systemctl enable gunicorn
    
  6. 常用管理命令:

    • 查看服务状态:sudo systemctl status gunicorn
    • 重启服务:sudo systemctl restart gunicorn
    • 停止服务:sudo systemctl stop gunicorn

内容的提问来源于stack exchange,提问作者CanKURT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:15:59