[python] nginx + uwsgi + django 環境部署
第一次做 web server 環境部署,從週一開始至少看了超過100篇文章了吧...
一堆文章不是排版很差,就是程式碼直接貼到文章裡,沒有排版沒有上色,看得眼睛很累,所以就來轉貼整理其中一篇。
原文在這裡:點我
pip3 install uwsgi安裝 uwsgi ,安裝成功後,用下面的指令來確認 uwsgi 是否能正常啟動 web 服務。
uwsgi --http :8000 --wsgi-file ProjectName/wsgi.py(注意 ProjectName 要換成自己的項目名稱,並確認檔案位置正確)
uwsgi 支持通過 ini 等配置檔案來啟動的,所以我們將使用配置檔案來啟動 uwsgi ,專案目錄下新建一個目錄 script (這個看個人喜好,也可以不用,為了方便管理,只要確認檔案位置正確就行),在新目錄 script 下新增 uwsgi.ini 配置檔案,配置內容如下
# uwsig 使用配置文件啟動 [uwsgi] # 專案目錄 chdir = /home/path/to/project/example/ # 指定專案的 application module = example.wsgi # 指定 socket 的檔案路徑 # socket = :8000 # 要用 browser 連的時候用這個 http = :8000 # 啟用主線程 master = true # 自動移除 unix Socket 和 pid 檔案,當服務停止的時候 vacuum = true buffer-size = 32768
這是主要的配置,還有更多選項可以設定,不過這些已經足夠正常啟動 uwsgi 了。
這裡需要注意的一點的是,前面提到過 uwsgi 也是一個 web 服務器同樣能完成 nginx 的工作,在這裡 nginx 並不是必須的,但是為了生產環境的性能和服務穩定經常和 nginx 搭配使用, nginx 和 uwsgi 使用 socket 來保持聯繫,因此如果想單獨使用 uwsgi 作為 web 服務器或者測試 uwsgi 服務器的話,上面配置項中的 socket 需要改為 http ,等配好了 nginx ,又需要要改回 socket 連線。
現在使用 uwsgi.ini 來啟動 uwsgi 服務(注意配置文件的實際位置及當前目錄位置),正常的話 uwsgi 服務已經啟動了,可以在瀏覽器中訪問測試,大家可以把配置中的 http 改為 socket 再測試一下,改成 socket 的話畫面就不能正常訪問了。
uwsgi --ini uwsgi.ini
我現在就還是卡在這裡...最後把設定一個一個關掉去測試,發現開了 daemonize 後,只要一執行行程就會被關掉。
daemonize = /var/log/uwsgi/yourproject.log # background the process & log不關的話就會直接在前台執行...雖然這樣也可以用啦
接下來配置 nginx,nginx 的安裝就不多說了,安裝成功後,找到 nginx 配置文件,通常在 /etc/nginx/ 或 /etc/nginx/conf.d/ 目錄底下,前面有提到過,我是在 nginx 下配置了兩個站點,配置都在 /etc/nginx/conf.d/default.conf 中,其他情況大家可以在 nginx 配置文件的同級目錄下新建一個你專案的 nginx 配置文件,比如新建一個 ProjectName.conf ,只要確定能被 nginx 正常載入就OK。
重點是這兩個配置,確認 uwsgi_params 檔案位置正確就可以了,其中 uwsgi_pass 就是 nginx 與 uwsgi 保持聯繫的關鍵配置。
uwsgi_pass 127.0.0.1:8000; include /etc/nginx/uwsgi_params;
重新啟動 nginx ,或者是前面加上 sudo
service nginx reload
配置好 nginx 後,重啟一下 nginx ,同時確認 uwsgi.ini 中 socket 配置是開啟而 http 配置項是關閉的,再重啟一下 uwsgi 服務,到這裡 nginx、uwsgi、django 的環境部署已經完成。
這是官方說明文件的範例。
# demo.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:///path/to/your/mysite/mysite.sock; # for a file socket
server 127.0.0.1:8001 ; # for a web port socket ( we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 8000 ;
# the domain name it will serve for
server_name 10.120.16.198 ; # substitute your machine's IP address or FQDN
charset utf-8 ;
# max upload size
client_max_body_size 75M ; # adjust to taste
location /static {
alias /path/to/bulk_print/Demo/static_file ; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django ;
include /path/to/your/mysite/uwsgi_params ; # the uwsgi_params file you installed
}
}
目前雖然是 nginx 和 uwsgi 都有安裝測試成功,不過 uwsgi 沒辦法在背景執行,就先暫停了。
留言
張貼留言