当前位置: 首页 > news >正文

在 Linux 中让 ​​Gunicorn​​ 在后台运行(作为守护进程),有几种常用方法:

在 Linux 中让 Gunicorn 在后台运行(作为守护进程),有几种常用方法:

方法 1:使用 & 直接后台运行

gunicorn -w 4 -b 0.0.0.0:8000 "sentiment_api_py.app:app" &

优点:简单快捷。

缺点:终端关闭后进程会被终止(除非配合 nohup)。

方法 2:使用 nohup(终端退出仍运行)

nohup gunicorn -w 4 -b 0.0.0.0:8000 "sentiment_api_py.app:app" &

日志:输出会保存到 nohup.out。

停止服务:

pkill gunicorn  # 终止所有 Gunicorn 进程

方法 3:使用 tmux 或 screen(会话管理)

tmux new -s my_gunicorn  # 创建新会话
gunicorn -w 4 -b 0.0.0.0:8000 "sentiment_api_py.app:app"

按 Ctrl+B, 再按 D 退出会话(进程保持运行)

重新连接会话:

tmux attach -t my_gunicorn

方法 4:用 systemd(生产环境推荐)
创建服务文件:

  sudo nano /etc/systemd/system/gunicorn.service

写入以下配置(根据你的路径修改):

  [Unit]

Description=Gunicorn for Flask App
After=network.target

[Service]
User=tree # 替换为你的用户名
Group=www-data
WorkingDirectory=/home/tree/sentiment # 项目路径
ExecStart=/home/tree/sentiment/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 “sentiment_api_py.app:app”
Restart=always

[Install]
WantedBy=multi-user.target

启动并设为开机自启:

  sudo systemctl daemon-reload

sudo systemctl start gunicorn
sudo systemctl enable gunicorn

常用命令:

  sudo systemctl status gunicorn  # 查看状态

sudo systemctl stop gunicorn # 停止
sudo journalctl -u gunicorn -f # 查看日志

方法 5:使用 supervisor(进程管理工具)
安装 Supervisor:

  sudo apt-get install supervisor

创建配置文件:

  sudo nano /etc/supervisor/conf.d/gunicorn.conf

写入配置:

  [program:gunicorn]

command=/home/tree/sentiment/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 “sentiment_api_py.app:app”
directory=/home/tree/sentiment
user=tree
autostart=true
autorestart=true
stderr_logfile=/var/log/gunicorn.err.log
stdout_logfile=/var/log/gunicorn.out.log

启动服务:

  sudo supervisorctl reread

sudo supervisorctl update
sudo supervisorctl start gunicorn

如何选择?
临时测试:用 nohup 或 tmux。

生产环境:用 systemd 或 supervisor(推荐 systemd,更简单)。

验证是否运行
ps aux | grep gunicorn # 查看进程
curl http://127.0.0.1:8000 # 测试接口

相关文章:

  • 论文笔记:Towards Explainable Traffic Flow Prediction with Large Language Models
  • Python爬虫实战:抓取百度15天天气预报数据
  • [神经网络]使用olivettiface数据集进行训练并优化,观察对比loss结果
  • Android 插件化
  • More SQL(Focus Subqueries、Join)
  • python完成批量复制Excel文件并根据另一个Excel文件中的名称重命名
  • 高效合并 Excel 表格实用工具
  • c++第三天(对象与构造函数)
  • MySQL 数据迁移Postgresql(openGuass) 之 pg_chameleon
  • 【Python办公】Excel简易透视办公小工具
  • EasyExcel使用导出模版后设置 CellStyle失效问题解决
  • C++ 异步编程与网络编程:工具、协议的层次与协同
  • 金砖国家人工智能高级别论坛在巴西召开,华院计算应邀出席并发表主题演讲
  • 多相电机驱动控制学习(2)——基于双dq的双三相PMSM学习(考虑互感/交叉耦合)
  • 网络协议入门:TCP/IP五层模型如何实现全球数据传输?
  • 学习STC51单片机18(芯片为STC89C52RCRC)
  • 微信小程序页面嵌套web-view点击系统导航返回时进行弹窗处理
  • WPF的基础控件:布局控件(StackPanel DockPanel)
  • RabbitMQ仲裁队列高可用架构解析
  • 720全景展示:VR全景的技术原理及应用
  • 广州珠吉网站建设/海外seo是什么
  • 建设学分银行网站策划书/外贸接单十大网站
  • 邯郸个人做网站/最近新闻报道
  • 一级a做爰片免费网站/360推广开户
  • 像美团这种网站怎么做/产品seo是什么意思
  • 海淀区网站建设公司/查网站排名