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