Flask + uWSGI + Nginx 項目部署方案

Nginx 前言

Nginx有幾個優點:
1、負載均衡:根據請求情況和服務器負載情況,將請求分配給不同的web服務器,保證服務器性能。
2、反向代理:客戶端的請求由代理服務器分配給某web服務器,而不是客戶端指定的目標服務器。對於一些靜態文件,可以直接由反向代理處理,不經過web服務器。
3、安全性:客戶端無法得知真正的服務器IP地址,保證了服務器的安全。

Nginx 與 uWSGI 之前的關係??
uWSGI是python的一個庫,安裝了這個庫之後,我們可以使用命令uwsgi,通過這個命令和一些配置,我們能夠產生一個web服務器,通信協議爲 http 或 https。

Nginx 對於處理靜態文件更有優勢,性能更好。如果是小網站,沒有靜態文件需要處理,只用 uWSGI 也是可以的,但加上 Nginx 這一層,優勢可以很具體。

參考:Flask + uWSGI 項目部署流程

安裝 Nginx

安裝nginx的依賴
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel
安裝Nginx
yum install -y nginx
啓動
systemctl start nginx.service
開機自動啓動
systemctl enable nginx.service

編輯配置文件nginx.conf,如果不清楚配置文件路徑,可以使用 whereis nginx 查詢,一般會在 /etc/nginx 路徑下。
如果是不熟悉配置規則的朋友,建議先備份一份源文件再做修改。

配置

nginx.conf 配置(http):

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

    #gzip on;
    upstream flask {
        server 127.0.0.1:5200;
    }

    server {
        listen       8000;
        server_name  0.0.0.0;
        charset      utf-8;

        client_max_body_size  75M;

        location /static/(.*) {
            alias /home/project/flask/UploadFiles/uploadfiles/static/;
        }

        location / {
            uwsgi_pass  flask;
            include     /etc/nginx/uwsgi_params;
        }
    }
}

檢查配置文件語法是否有錯誤:nginx -t
在這裏插入圖片描述
檢查 nginx 狀態:systemctl status nginx
在這裏插入圖片描述
重啓 nginx 使配置文件生效:systemctl restart nginx

將原先的uWSGI服務先停止,修改項目路徑下的 uwsgi.ini配置文件,將端口設置改爲socket模式,註釋掉原來的http,改爲:socket = :5200

修改保存完成後,重新啓動:uwsgi --ini uwsgi.ini

遠端訪問

請求你的 公網IP:8000 是否正常訪問,Response Headers 中顯示對應的服務器版本信息。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章