使用django開發一個上線標準的mooc網站(十六)使用Uwsgi+Nginx搭建生產環境並將代碼上線

使用Uwsgi+Nginx搭建生產環境並將代碼上線

本文參考了:

Django + Uwsgi + Nginx 實現生產環境部署www.cnblogs.com圖標基於nginx和uWSGI在Ubuntu上部署Djangowww.jianshu.com

1.在kali 2.0(32位)中安裝配置python虛擬環境virtualenvwrapper

root@kali:~# pip install virtualenvwrappernroot@kali:~# mkdir ~/.virtualenvsnroot@kali:~# vi .bashrcn# 在該文件最後添加:nexport WORKON_HOME=~/.virtualenvsnsource /usr/local/bin/virtualenvwrapper.shnroot@kali:~# source ~/.bashrcnroot@kali:~# mkvirtualenv mxonlinen(mxonline) root@kali:~# workonnmxonlinen

2.安裝Uwsgi

(mxonline) root@kali:~# pip install uwsgin

基本測試

Create a file called test.py:

# test.pyndef application(env, start_response):n start_response(200 OK, [(Content-Type,text/html)])n #return [b"Hello World"] # python3n return ["Hello World"] # python2n

運行測試

uwsgi --http :8000 --wsgi-file test.py n

3.後來在kali中的虛擬python環境中沒能安裝成功:

(mxonline) root@kali:~# pip install MySQL-pythonnCollecting MySQL-pythonn Using cached MySQL-python-1.2.5.zipn Complete output from command python setup.py egg_info:n sh: 1: mysql_config: not foundn Traceback (most recent call last):n File "<string>", line 1, in <module>n File "/tmp/pip-build-vf5ulo/MySQL-python/setup.py", line 17, in <module>n metadata, options = get_config()n File "setup_posix.py", line 43, in get_confign libs = mysql_config("libs_r")n File "setup_posix.py", line 25, in mysql_confign raise EnvironmentError("%s not found" % (mysql_config.path,))n EnvironmentError: mysql_config not foundn n ----------------------------------------nCommand "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-vf5ulo/MySQL-python/n

一直沒能找到安裝方法,後來發現kali自帶的python中已經自己安裝好了:

root@kali:~# pythonnPython 2.7.14 (default, Sep 17 2017, 18:50:44) n[GCC 7.2.0] on linux2nType "help", "copyright", "credits" or "license" for more information.n>>> import MySQLdbn>>> n

所以決定就不使用python虛擬環境而直接使用kali的python環境並測試:

root@kali:~# pip install uwsginroot@kali:~# uwsgi --http :8000 --wsgi-file test.py n

如果埠佔用,使用

lsof -i :8000n

列出佔用埠的程序的pid號,並使用以下命令殺掉所有佔用埠的程序

sudo kill -9 pid n

運行成功後,使用瀏覽器訪問頁面:

4.準備環境

(1)python所需要的包

requirements.txt

Django==1.9ndjango-crispy-forms==1.6.1ndjango-formtools==1.0ndjango-pure-pagination==0.3.0ndjango-simple-captcha==0.4.6nDjangoUeditor==1.8.143nhttplib2==0.9.2nPillow==3.4.2ndjango-import-export>=0.5.1ndjango-reversion>=2.0.0n

安裝:

root@kali:~# pip install -r requirements.txtn

(2)MySQL環境

kali默認已安裝MySQL開源版即MariaDB,將其設為開機啟動即可:

root@kali:~# update-rc.d mysql enablennusage: update-rc.d [-f] <basename> removen update-rc.d [-f] <basename> defaultsn update-rc.d [-f] <basename> defaults-disabledn update-rc.d <basename> disable|enable [S|2|3|4|5]n -f: forcen

參考:

  1. 修改mysql用戶密碼 - jyGinger - 博客園
  2. 解決 MariaDB無密碼就可以登錄的問題

遷移資料庫:

C:Documents and SettingsAdministrator>mysqldump -u root -p mxonline > mxonline20180111.sqln

導入到伺服器上:

root@kali:~/mxonline# mysql -u root -p < mxonline20180111.sql n

(注意,在DOS下生成的SQL文件可能沒有創建資料庫和實用資料庫的語句,在sql文件中加上即可。)

5.git clone編寫好的代碼

root@kali:~# git clone git@github.com:xxxxxxxx/mxonline.gitnCloning into mxonline...ngit@github.com: Permission denied (publickey).nfatal: Could not read from remote repository.nnPlease make sure you have the correct access rightsnand the repository exists.n

解決報錯:

root@kali:~# ssh-keygen -t rsa -C "xxxxxxxx@github.com" nGenerating public/private rsa key pair.nEnter file in which to save the key (/root/.ssh/id_rsa): nEnter passphrase (empty for no passphrase): nEnter same passphrase again: nYour identification has been saved in /root/.ssh/id_rsa.nYour public key has been saved in /root/.ssh/id_rsa.pub.nThe key fingerprint is:nSHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxx@github.comnThe keys randomart image is:n+---[RSA 2048]----+nn+----[SHA256]-----+nroot@kali:~# cd .sshnroot@kali:~/.ssh# lsnid_rsa id_rsa.pub known_hostsnroot@kali:~/.ssh# sz id_rsa.pub # 發送公鑰文件到我的管理終端並拷貝其中的公鑰到github網站上n

再次嘗試git clone:

root@kali:~/.ssh# git clone git@github.com:xxxxxxxx/mxonline.gitnCloning into mxonline...nremote: Counting objects: 1510, done.nremote: Compressing objects: 100% (1052/1052), done.nremote: Total 1510 (delta 489), reused 1404 (delta 383), pack-reused 0nReceiving objects: 100% (1510/1510), 50.74 MiB | 136.00 KiB/s, done.nResolving deltas: 100% (489/489), done.n

測試django程序本身可以執行:

root@kali:~/mxonline# pwdn/root/mxonlinenroot@kali:~/mxonline# python manage.py runserver 0.0.0.0:8000n...nImportError: No module named import_export.adminn

發現還有幾個xadmin的依賴包沒有安裝:

root@kali:~/mxonline# pip install django-import-exportnroot@kali:~/mxonline# pip install django-reversionn

安裝完成後,繼續嘗試:

root@kali:~/mxonline# python manage.py runserver 0.0.0.0:8000nPerforming system checks...n...ndjango.db.utils.OperationalError: (1698, "Access denied for user root@localhost")n

通過觀察報錯信息,懷疑是settings.py中的資料庫地址設置與環境配置有點小衝突,解決:

104 DATABASES = {n105 default: {n106 ENGINE: django.db.backends.mysql,n107 NAME: "mxonline",n109 PASSWORD: "root",n110 HOST: "localhost",n111 }n

再次嘗試:

root@kali:~/mxonline# python manage.py runserver 0.0.0.0:8000nPerforming system checks...nn...nnSystem check identified no issues (0 silenced).nJanuary 11, 2018 - 22:11:40nDjango version 1.9, using settings MxOnline.settingsnStarting development server at http://0.0.0.0:8000/nQuit the server with CONTROL-C.n

6.準備環境:

(1)nginx:

確認nginx配置文件目錄:

root@kali:~/mxonline/MxOnline# nginx -tnnginx: the configuration file /etc/nginx/nginx.conf syntax is oknnginx: configuration file /etc/nginx/nginx.conf test is successfuln

檢查nginx的正常運行:

root@kali:~/mxonline# /etc/init.d/nginx restartn[ ok ] Restarting nginx (via systemctl): nginx.service.nroot@kali:~/mxonline# lsof -i:80nCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEnnginx 15619 root 6u IPv4 135441 0t0 TCP *:http (LISTEN)nnginx 15619 root 7u IPv6 135442 0t0 TCP *:http (LISTEN)nnginx 15620 www-data 3u IPv4 135473 0t0 TCP kali:http->10.0.0.1:13373 (ESTABLISHED)nnginx 15620 www-data 6u IPv4 135441 0t0 TCP *:http (LISTEN)nnginx 15620 www-data 7u IPv6 135442 0t0 TCP *:http (LISTEN)n

增加nginx配置

  • uwsgi_params文件拷貝到項目文件夾下。uwsgi_params文件在/etc/nginx/目錄下,也可以從這個頁面下載

root@kali:~/mxonline# cp /etc/nginx/uwsgi_params ./n

  • 在項目文件夾下創建文件mysite_nginx.conf,填入並修改下面內容:

# mysite_nginx.confnn# the upstream component nginx needs to connect tonupstream django {n # server unix:///path/to/your/mysite/mysite.sock; # for a file socketn server 127.0.0.1:8001; # for a web port socket (well use this first)n}n# configuration of the servernserver {n # the port your site will be served onn listen 8000;n # the domain name it will serve forn server_name localhost; # substitute your machines IP address or FQDNn charset utf-8;n n access_log /root/mxonline/nginx_access.log;n error_log /root/mxonline/nginx_error.log;nn # max upload sizen client_max_body_size 75M; # adjust to tastenn # Django median location /static {n alias /root/mxonline/static; # your Django projects static files - amend as requiredn }n n location /media {n alias /root/mxonline/media; # your Django projects media files - amend as requiredn }nn # Finally, send all non-media requests to the Django server.n location / {n uwsgi_pass django;n include /root/mxonline/uwsgi_params; # the uwsgi_params file you installed n }n}n

這個configuration文件告訴nginx從文件系統中拉起media和static文件作為服務,同時相應django的request。

/etc/nginx/sites-enabled目錄下創建本文件的連接,使nginx能夠使用它:

root@kali:~/mxonline# ln -s ~/mxonline/mysite_nginx.conf /etc/nginx/sites-enabled/n

部署static文件

在django的setting文件中,添加下面一行內容:

DEBUG = Falsen ...n# STATICFILES_DIRS = (n# os.path.join(BASE_DIR,"static"),n# )n...nSTATIC_ROOT = os.path.join(BASE_DIR, static)n# DEBUG = False時STATICFILES_DIRS失效,靜態路徑由http伺服器負責解析,解決方法為增加上邊的STATIC_ROOTn

然後運行:

root@kali:~/mxonline# python manage.py collectstatic nnYou have requested to collect static files at the destinationnlocation as specified in your settings:nn /root/mxonline/staticnnThis will overwrite existing files!nAre you sure you want to do this?nnType yes to continue, or no to cancel: yespython manage.py collectstatic n...nn241 static files copied to /root/mxonline/static.n

測試nginx

首先重啟nginx服務:

sudo /eroot@kali:~/mxonline# /etc/init.d/nginx restartn[ ok ] Restarting nginx (via systemctl): nginx.service.tc/init.d/nginx restartn

然後檢查media文件是否已經正常拉起:

在目錄/root/mxonline/media下添加文件1.mp4然後訪問 10.0.0.200:8000/media/1,成功後進行下一步測試。

(2)配置uWSGI

執行下面代碼測試能否讓nginx在頁面上顯示hello, world

前面已經在mysite_nginx.conf中配置了:

upstream django {n # server unix:///path/to/your/mysite/mysite.sock; # for a file socketn server 127.0.0.1:8001; # for a web port socket (well use this first)n}n

即用戶訪問nginx的靜態頁時,nginx同時會訪問uwsgi解析的動態頁面127.0.0.1:8001:

root@kali:~/mxonline# uwsgi --socket :8001 --wsgi-file test.pyn

訪問http://10.0.0.200:8000/ ,顯示hello world,如下圖

證明下面環節通暢:

the web client <-> the web server <-> the socket <-> uWSGI <-> Python

用UNIX socket取代TCP port我沒有試成功,以後有機會再嘗試下,這裡有些參考資料:

Django + Uwsgi + Nginx 的生產環境部署www.cnblogs.com圖標php fpm安裝curl後,nginx出現connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied)的錯誤www.cnblogs.com

人類身份驗證 - SegmentFaultsegmentfault.com

建立uWSGI的配置文件:

[uwsgi]nchdir=/root/mxonline/n# chmod-socket=666n# chown-socket=www-datannmodule=MxOnline.wsginenv=DJANGO_SETTINGS_MODULE=MxOnline.settingsnmaster=Truenvacuum=Truensocket=127.0.0.1:8001npidfile=/tmp/mysite.pidndaemonize=/root/mxonline/mysite.logn# gid=www-datan# uid=www-datanprocesses=2nthreads=2nmax-requests=2000n

導入配置:

root@kali:~/mxonline# uwsgi --ini uwsgi.ini n[uWSGI] getting INI configuration from uwsgi.inin

7.最終測試與配置:

root@kali:~/mxonline# /etc/init.d/nginx restartn[ ok ] Restarting nginx (via systemctl): nginx.service.n

開機自啟腳本:

root@kali:~# uwsgi --ini /root/mxonline/uwsgi.inin[uWSGI] getting INI configuration from /root/mxonline/uwsgi.ininroot@kali:~# /etc/init.d/nginx restartn[ ok ] Restarting nginx (via systemctl): nginx.service.n

開機後,自動啟動以下兩個語句即可實現應用啟動:

uwsgi --ini /root/mxonline/uwsgi.inin/etc/init.d/nginx restartn

最終完成了應用上線。

推薦閱讀:

製造業工廠設備維護系統如何建立?
漱口水廠家總結漱口水知識大全
我和跳樓的產婦說了同樣的話
圓珠筆頭的那個小圓珠是怎麼生產的,又是怎麼做到筆尖上的?
塑料中含水嗎?

TAG:Django框架 | uwsgi | 生产 |