自学内容网 自学内容网

linux 部署flask项目

linux python环境安装:  https://blog.csdn.net/weixin_41934979/article/details/140528410

1.创建虚拟环境

python3.12 -m venv .venv

2.激活环境

 . .venv/bin/activate

 3.安装依赖包(pip3.12 install -r requirements.txt)

pip3.12 install -r requirements.txt

4.测试启动项目

python3.12 app.py

5.在虚拟环境中安装gunicorn

pip install gunicorn

6.安装配置Supervisor

6.1安装Supervisor

CentOS

首先,安装 EPEL 扩展源(如果尚未安装):

sudo yum install epel-release

 然后,使用 yum 命令安装 Supervisor:

sudo yum install supervisor

Ubuntu 

sudo apt install supervisor

查看版本,确认supervisor是否成功安装

supervisord --version
6.2配置supervisor

查看supervisor的配置

注意不同版本的Linux系统,不同版本supervisor,配置文件路径可能不同

CentOS

cat /etc/supervisord.conf

主要配置代码如下(主要看[include]下的文件路径):

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[include]
files = supervisord.d/*.ini

Ubuntu

cat /etc/supervisor/supervisord.conf
; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[include]
files = /etc/supervisor/conf.d/*.conf

创建.ini配置文件或者.conf配置文件(具体要看[include]下面路径是*.ini,还是*.conf),

文件要放进  [include]下的文件路径里

这里以Ubuntu为例

再次提醒.conf配置文件,文件要放进:[include]下的文件路径里,

放进/etc/supervisor/conf.d路径里

创建文件flaskapi.conf配置文件

 vi /etc/supervisor/conf.d/flaskapi.conf

内容如下:

[program:flaskapi] ; :右边是项目名称
command=/bin/bash -c ". .venv/bin/activate&&nohup python -m gunicorn -D -w 4 -b 0.0.0.0:8011 -t 120 app:app --access-logfile access.log --error-logfile error.log" ; 启动虚拟环境下的gunicorn,这里建议使用绝对路径
directory=/usr/projects/flask-api ; 程序的启动目录,这里是Flask网站根目录
user=root ; 用户名
autostart=true ; 在 supervisord 启动的时候也自动启动
autorestart=true ; 程序异常退出后自动重启
stopasgroup=true ; 它表示当该进程停止时,与该进程属于同一组的所有相关进程也会同时停止
killasgroup=true ; "杀死"整个组的进程
loglevel=info ; 日志级别设置为“信息”级别
6.3更新配置文件
supervisorctl update

启动supervisor服务 

 systemctl enable supervisor

查看服务状态 

systemctl status supervisor.service

7.curl测试是否能访问接口

curl http://localhost:8011/ -w '\n'

成功访问 

8.重启服务器flask是否开机自启 

重启后再次访问接口

curl http://localhost:8011/ -w '\n'

服务开机自启成功 

 

参考资料

https://blog.csdn.net/qq_39680564/article/details/102739143 


原文地址:https://blog.csdn.net/weixin_41934979/article/details/140614329

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!