flask部署

技术 · 2021-12-30 · 48 人浏览

flask部署

安装虚拟环境

pip3 install virtualenv

安装Flask,Gunicorn,Supervisor

pip3 install flask gunicorn supervisor

安装环境

pip3 install -r requirements.txt

使用gunicorn启动程序

当我们部署到服务器上时,需要一个性能更优的 WSGI服务器。

终端输入:

gunicorn --workers=4 --bind=0.0.0.0:8080 app:app

workers 用来定义工作线程的数量,一般 worker 的数量为 (2×$num_cores)+1。官方文档中介绍到虽然这个公式并不十分科学,但它基于这样一个假设: 对于给定的核心数,一个工作线程将从套接字读取或写入数据,而另一个工作线程处理请求。

bind 用来绑定程序运行的主机地址和端口。

如果设置了SSL证书,命令为:

gunicorn --keyfile=<私钥文件> --certfile=<SSL证书文件> --ca-certs=<CA证书文件> --bind=0.0.0.0:443app:app

安装并配置 Nginx

我们需要 Nginx 作为反向代理使用。

输入以下命令安装 nginx:

apt-get install nginx -y

安装完成后进入:

cd /etc/nginx/sites-enabled

删除 default 文件:

rm default

编辑新的配置文件,命名为 app

server {    listen 80;
    server_name _; # 如果有域名可以写到这里
    access_log  /var/log/nginx/access.log;    
    error_log  /var/log/nginx/error.log;
    location / {        
        proxy_pass         http://127.0.0.1:8080/;        
        proxy_redirect     off;
        proxy_set_header   Host                 $host;        
        proxy_set_header   X-Real-IP            $remote_addr;        
        proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;            
        proxy_set_header   X-Forwarded-Proto    $scheme;    
        }
 }

输入:

nginx -t

测试一下 nginx 配置有无问题。

没有问题的话重启服务:

service nginx restart

有关 nginx 的配置完成。

使用 supervisor 管理进程

Supervisor 是一个 客户端/服务器系统,允许其用户在类 UNIX操作系统上控制进程。当进程被意外杀死,Supervisor 可以主动将其拉起。

使用如下命令构建配置文件:

echo_supervisord_conf > /etc/supervisord.conf

编辑配置文件,加入以下内容:

[program:gunicorn]
user = root             ; root 用户启动
directory = /root/person       ; flask 文件所在目录
command = /usr/local/bin/gunicorn --workers=4 --bind=0.0.0.0:8000 app:app ; 程序启动命令(第一个 app 是 flask 的文件名,第二个是 application 的缩写)
startsecs = 5           ; 启动 5 秒后没有异常退出,视作正常启动
autostart = true        ; 在 supervisord 启动时自动启动
autorestart = true      ; 程序异常退出后重启
redirect_stderr = true  ; stderr 也重定向至 
stdoutstdout_logfile = /root/logs/gunicorn.log ; stdout 日志文件,需要手动创建日志存放目录

gunicorn 路径可以这样找到:

bash ➜ ~ which gunicorn/usr/local/bin/gunicorn

输入:

supervisord -c /etc/supervisord.conf

启动服务。

supervisor 常用命令如下:(具体可查看官方文档[3])

supervisorctl status                # Get all process status info.
supervisorctl stop gunicorn         # Stop a process.
supervisorctl start gunicorn        # Start a process.
supervisorctl restart gunicorn      # Restart a process Note: restart does not reread config files.
supervisorctl reread                # Reload the daemon’s configuration files, without add/remove (no restarts).
supervisorctl update                # Reload config and add/remove as necessary, and will restart affected programs.

全部配置完成就实现了 flask 的部署。

flask 环境部署
Theme Jasmine by Kent Liao