在 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 # 测试接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值