Python Flask项目部署到 ubuntu

来源:互联网 发布:阿里云修改dns 编辑:程序博客网 时间:2024/06/10 20:00

一、背景名词解释

    一般来说,从前端到后端的整体框架如下图所示:

  • 客户端:一般指浏览器或者移动终端;
  • Web服务器:web服务器的作用主要是接收客户端请求并返回处理结果,常用的Web服务器有Nginx、Apache等,Web服务器的挑战是数据的并发、并行和吞吐量。
  • Web框架:Web框架主要是对接收到的客户端请求进行处理,常用的Web框架有flask、Django等。Web框架的挑战是易于业务逻辑的开发。
  • WSGI:是Web服务器网关接口(Python Web Server Gateway Interface),是为Python语言定义的Web服务器和Web框架之间的一种简单而通用的接口,常用的有gunicorn等。

    在这里我们Web服务器选择为flask自带的web服务器、WSGI选择为gunicorn、而Web框架选择flask,平台为腾讯云CVM ubuntu服务器。

二、部署

第一步:登录腾讯云CVM

    这里就不说具体步骤了,可以直接在控制台用浏览器登录,或者终端直接ssh登录。

第二步:ubuntu环境下配置python开发环境

sudo apt-get updatesudo apt-get install python-dev python-pip python-virtualenv

第三步:下载源码并解压

可以使用scp命令

scp source_path username@ip:dest_path

或者直接利用链接下载

wget urlwget http://rickenwang-1253653367.cosgz.myqcloud.com/resources/signer-release.zip

下载后直接解压即可。

第四步:激活virtualenv环境并进行配置

  • 激活virtualenv环境
cd 到flask项目目录vitualenv venvsource venv/bin/activate
  • 配置环境
pip install gunicornpip install flaskpip install flask-script

第五步:启动服务

gunicorn -w 4 -b 0.0.0.0:5000 manage:app

到这里最简单的部署就完成了,但是启动后坑爹的是此时无法输入其他命令了,这时就有了我们的第六步。

第六步:用supervisor管理服务

pip install supervisorecho_supervisord_conf > supervisor.confvi supervisor.conf

supervisor.conf文件的底部添加

[program:myapp]command=flask_path/venv/bin/gunicorn -w4 -b0.0.0.0:2170 myapp:app    directory=flask_path                                              startsecs=0   stopwaitsecs=0    autostart=false                                                                        autorestart=false                                                             stdout_logfile=flask_path/log/gunicorn.log                          stderr_logfile=flask_path/log/gunicorn.err                     

supervisor基本的命令有:

supervisord -c supervisor.conf                             通过配置文件启动supervisorsupervisorctl -c supervisor.conf status                    察看supervisor的状态supervisorctl -c supervisor.conf reload                    重新载入 配置文件supervisorctl -c supervisor.conf start [all]|[appname]     启动指定/所有 supervisor管理的程序进程supervisorctl -c supervisor.conf stop [all]|[appname]      关闭指定/所有 supervisor管理的程序进程

最后使用如下命令启动服务:

supervisord -c supervisor.confsupervisorctl -c supervisor.conf start manage