天天看點

Python Flask,項目部署,Gunicorn伺服器

Gunicorn(綠色獨角獸)是一個Python WSGI的HTTP伺服器 (web伺服器)。

項目部署方式: nginx + gunicorn + flask

安裝gunicorn: $ pip install gunicorn

安裝gunicorn成功後,通過指令行的方式可以檢視gunicorn的使用資訊:

$ gunicorn -h   # 檢視指令行選項

$ gunicorn 運作檔案名稱:Flask程式執行個體名   # 直接運作,預設啟動的127.0.0.1::8000

$ gunicorn -w 4 -b 127.0.0.1:5001 -D --access-logfile ./logs/log.txt 運作檔案名稱:Flask程式執行個體名   # 指定程序數和端口号。 -w:(worker)表示程序數。 -b:(bind)表示綁定ip位址和端口号。-D:表示守護程序方式啟動(背景運作)

安裝Nginx:

$ sudo apt-get install nginx

/usr/local/nginx/conf/nginx.conf(Nginx配置檔案,配置Nginx):

# 。。。

# 負載均衡
upstream my_flask { 
      server 127.0.0.1:5000; 
      server 127.0.0.1:5001; 
}

server {
    # 監聽80端口
    listen 80;
    # 本機
    server_name localhost; 

    # 會比對"/"開頭的所有url
    location / {
        # 請求轉發到gunicorn伺服器
        proxy_pass http://my_flask;
        # 設定請求頭,并将頭資訊傳遞給伺服器端
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# 。。。
           

啟動nginx: $ sudo sbin/nginx

停止nginx: $ sudo sbin/nginx -s stop

重新開機nginx: $ sudo sbin/nginx -s reload

檢視: $ ps aux | grep nginx