在Mac OS上部署Nginx和FastCGI以及Flask架構的教程

來源:互聯網
上載者:User
最近在學習Flask,本文介紹一下如何部署Flask開發的應用,同時也學習一下Nginx的使用,這隻是在Mac上的一個實驗。
應用

這裡使用的應用就是官方的文檔中給出的Flaskr。
安裝Nginx

使用HomeBrew安裝Nginx:

$ brew install nginx

HomeBrew會自動安裝Nginx及其依賴的程式。在我的電腦上安裝的是Nginx 1.6.2,設定檔的路徑是/usr/local/etc/nginx/nginx.conf。

啟動Nginx的命令:

$ nginx

Nginx的預設連接埠是8080,用瀏覽器開啟localhost:8080,顯示如下所示的頁面說明Nginx已經工作了。

配置Nginx

修改Nginx的設定檔:

server {  listen 80;  server_name localhost;  charset utf-8;  location / { try_files $uri @flaskr; }  location @flaskr {    include fastcgi_params;    fastcgi_param PATH_INFO $fastcgi_script_name;    fastcgi_param SCRIPT_NAME "";    fastcgi_pass unix:/tmp/flaskr-fcgi.sock;  }}

重新啟動Nginx:

$ nginx -s quit$ sudo nginx

因為使用了80連接埠,啟動Nginx時需要加上sudo。

啟動完成後,訪問localhost:

訪問時出現了錯誤,這是因為我們的應用還沒有啟動。
FastCGI Server

Nginx是一個靜態WEB伺服器,不能直接運行我們的Python應用,當Nginx接受到請求時,會通過FastCGI轉寄給我們的應用,應用是運行在FastCGI Server上的,這個server接收Nginx的請求並調用我們的程式,將結果返回給Nginx,Nginx再將結果返回給使用者。

我們要使用的FastCGI Server是flup,安裝方法:

$ pip install flup

在應用目錄下建立一個fcgi檔案,例如flaskr.fcgi:

#!/usr/bin/pythonfrom flup.server.fcgi import WSGIServerfrom flaskr import appif __name__ == '__main__':  WSGIServer(app, bindAddress='/tmp/flaskr-fcgi.sock').run()

同時給fcgi檔案可執行檔許可權:

$ chmod +x flaskr.fcgi

手動啟動server:

$ screen$ ./flaskr.fcgi

使用screen使server在後台運行,或者:

$ nohup ./flaskr.fcgi &

再次訪問localhost就可以看到我們的應用了。
遇到的問題

第一次運行FastCGI server後,任然無法訪問,查看Nginx的日誌後發現Nginx伺服器沒有許可權訪問socket檔案,修改nginx.conf添加user配置:

複製代碼 代碼如下:

user wzy;

啟動的時候Nginx報錯:

nginx: [emerg] getgrnam("wzy") failed in /usr/local/etc/nginx/nginx.conf:2

Google一下後發現要加上使用者組才行,改成這樣:

複製代碼 代碼如下:

user wzy wheel;

再次啟動Nginx後一切正常了。

Nginx配置項user的使用方法:

Syntax: user user [group];Default: user nobody nobody;

如果忽略group,Nginx會使用和user名稱一樣的使用者組,例如我設定user wzy,那麼Nginx啟動的時候會去尋找使用者組wzy,我的電腦上沒有這個使用者組,所以Nginx會報錯。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.