使用Gunicorn和nginx进行Flask服务部署
Gunicorn ‘Green Unicorn’ 是一个 UNIX 下的 WSGI HTTP 服务器
在 Gunicorn 上运行 Flask 应用
修改下面myproject为自己的服务文件名即可
$ gunicorn myproject:app
使用如下命令即可启动多个应用实例:
$ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app
输出如下内容代表服务创建成功:
[2020-02-11 14:50:24 +0800] [892] [INFO] Starting gunicorn 20.0.4
[2020-02-11 14:50:24 +0800] [892] [INFO] Listening at: http://0.0.0.0:5555 (892)
[2020-02-11 14:50:24 +0800] [892] [INFO] Using worker: sync
[2020-02-11 14:50:24 +0800] [895] [INFO] Booting worker with pid: 895
[2020-02-11 14:50:24 +0800] [896] [INFO] Booting worker with pid: 896
[2020-02-11 14:50:24 +0800] [898] [INFO] Booting worker with pid: 898
[2020-02-11 14:50:24 +0800] [899] [INFO] Booting worker with pid: 899
使用Nginx进行负载均衡
修改配置文件:修改服务端口的url即可
worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { server { listen 5556; # nginx端口 server_name localhost; location / { proxy_pass http://localhost:5555/run; #服务端口的url,将当前请求代理到URL参数指定的服务器上,URL可以是主机名或者IP地址加PORT的形式 } } }
多机负载:
worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { upstream my.net{
#my.net是自定义的,在server结构中引用即可 #代理服务器为 两台机器192.168.22.136 192.168.22.147 # server servername:port server 192.168.22.136:80 max_fails=1 fail_timeout=300s; server 192.168.22.147:80 max_fails=1 fail_timeout=300s; } server { listen 5556; # nginx端口 server_name localhost; location / { proxy_pass http:mynet; } } }
从配置文件启动:
sudo nginx -c nginx.conf
凤舞九天