将flask部署到服务器

声明,本博客写给自己看的,相当于云笔记,亲爱的陌生人请勿尝试!!!

所需环境

  • gunicorn
  • nginx
  • supervisor

gunicorn

  1. 安装gunicorn

    pip安装gunicorn

    pip install gunicorn
    

    其实不需要nginx,gunicorn便可运行简单的flask应用,创建如下文件

    #main.py
    from flask import Flask
    app = Flask(__name__)
    app.route('/')
    def index():
    	return 'hello world'
    if __name__ == '__main__':
    	app.run()
    

    然后运行gunicorn

    gunicorn -w 4 main:app -b 0.0.0.0:8000
    

    便可在浏览器中看到hello world信息了
    但是gunicorn对静态文件支持不好,所以仍需要使用nginx做反向代理

  2. gunicorn关闭操作如下

    pstree -ap|grep gunicorn
    

    得到以下结果

    
      |           |-grep,4698 --color=auto gunicorn
      |   `-gunicorn,4238 /usr/bin/gunicorn -w 4 run_app:app -b 0.0.0.0:8000
      |       |-gunicorn,4243 /usr/bin/gunicorn -w 4 run_app:app -b 0.0.0.0:8000
      |       |-gunicorn,4248 /usr/bin/gunicorn -w 4 run_app:app -b 0.0.0.0:8000
      |       |-gunicorn,4249 /usr/bin/gunicorn -w 4 run_app:app -b 0.0.0.0:8000
      |       `-gunicorn,4250 /usr/bin/gunicorn -w 4 run_app:app -b 0.0.0.0:8000
    
    

    重启gunicorn

    kill -HUP 4238
    

    关闭gunicorn

    kill -9 4238
    

nginx

  1. 安装nginx

    sudo yum install nginx -y
    
  2. 启动nginx

    service nginx start
    
  3. 配置nginx
    /etc/nginx/nginx.conf添加如下内容

            location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_redirect off;
            proxy_set_header Host $http_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;
            }
    
  4. 重新启动nginx

    service nginx restart
    
  5. 再次启动gunicorn便可看到flask应用已经在运行了

supervisor

supervisor能守护进程,当gunicorn挂了之后,能自动重启

  1. 安装supervisor
    easy_install supervisor
    mkdir /etc/supervisor
    echo_supervisord_conf > /etc/supervisor/supervisord.conf
    mkdir /etc/supervisor/conf.d
    
    每个应用单独写一个conf,再由supervisord.conf导入
  2. 修改supervisor.conf,在末尾加上
    [include]
    files = /etc/supervisor/conf.d/app.conf
    # your_app.conf为你的app配置
    
  3. 添加app.conf
    此处的message_app为groram_name
    [program:message_app]
    directory=/home/message
    command=gunicorn -w 4 run_app:app -b 0.0.0.0:8000
    
  4. 启动supervisor
    sudo supervisor -c supervisord.conf	#添加配置文件
    sudo supervisorctl start message_app #启动应用
    
  5. 常用命令
    sudo supervisorctl reload  #修改配置文件后重新加载
    sudo supervisorctl start app #启动app
    sudo supervisorctl stop app #停止app
    sudo supervisorctl restart app #重启app
    
将flask部署到服务器将flask部署到服务器 weixin_43904540 发布了3 篇原创文章 · 获赞 0 · 访问量 99 私信 关注
上一篇:Supervisor初体验


下一篇:KVM管理工具 WebVirtMgr