django博客搭建(二)Nginx+Django+Uwsgi架构部署

(作者翻译整理自官方文档,https://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html,更详细了解请参考官方文档)
web 服务器可以直接位文件系统的文件(HTML,图像,CSS等)提供服务。但是,它不能直接与Django应用程序交互,
它需要一个能直接运行Djanog应用程序,向它发送客户端请求,并返回响应。
于是就出现了Web服务器网关接口:WSGI ,来做这件工作。
uWSGI是一个WSGI实现。它会创建一个Unix套接字,并通过WSGI协议向Web服务器提供响应。
他们的关系如下:
the web client <-> the web server <-> the socket <-> uwsgi <-> Django

安装和配置:
Django

安装Django,创建一个新的项目:

$pip install Django
$django-admin.py startproject mysite
$cd mysite

uWSGI
安装uWSGI:

$pip install uwsgi

创建文件test.py,测试

# test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"] # python3
    #return ["Hello World"] # python2

运行uwsgi

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

该选项的意思是:
HTTP:8000:使用HTTP协议,端口8000
WSGI-file test.py:加载指定的文件,test.py
直接访问127.0.0.1:8000,如果看到Hello World,说明以下组件工作正常:
the web client <-> uWSGI <-> Python
测试你的Django项目

首先,请确保你的mysite项目工作正常:

$python manage.py runserver 0.0.0.0:8000

如果它的工作正常,使用uWSGI运行它:

$uwsgi --http :8000 --module mysite.wsgi

module mysite.wsgi: 加载指定的wsgi模块
直接访问127.0.0.1:8000,如果一切正常,说明uWSGI可以serve你的Django应用程序,而以下组件正常工作:
the web client <-> uWSGI <-> Django

安装Nginx

$sudo apt-get install nginx
$sudo /etc/init.d/nginx start    # start nginx


访问127.0.0.1:8000,看到 “Welcome to nginx!”. 说明安装成功,以下组件正常:
the web client <-> the web server
为你的站点配置Nginx:
首先你需要uwsgi_params文件,该文件可在nginx的安装目录下(比如Ubuntu在/etc/nginx/),
或者从https://github.com/nginx/nginx/blob/master/conf/uwsgi_params下载
把它复制到你的项目目录,后面nginx会用到它。
现在,创建一个名为mysite_nginx.conf文件,内容如下:

# mysite_nginx.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 .example.com; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /path/to/your/mysite/media;  # your Django project's media files - amend as required
    }

    location /static {
        alias /path/to/your/mysite/static; # 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
    }
}

这个conf文件告诉nginx,媒体文件和静态文件处理请求路径和方式。让一台服务器处理静态/媒体文件,另一个处理Django应用程序,
这对于一个大的项目来说是很好的做法,这会做就好了。
在/etc/nginx/sites-enabled/ 这个文件夹下建立链接,让nginx可以看到:

$sudo ln -s ~/path/to/your/mysite/mysite_nginx.conf /etc/nginx/sites-enabled/

部署静态文件:
打开mysite/settings.py 添加:

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

然后运行:

$python manage.py collectstatic

重启 nginx:

$sudo /etc/init.d/nginx restart


添加一个名为media.png的图片到 /path/to/your/project/project/media 目录下,访问127.0.0.1:8000/media/media.png
如果到此仍然正常工作,至少确定nginx可以正确提供服务。

使用Unix套接字,而不是端口
编辑mysite_nginx.conf:

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)

重启Nginx
然后运行,

$uwsgi --socket mysite.sock --wsgi-file test.py

如果错误日志里出现
connect() to unix:///path/to/your/mysite/mysite.sock failed (13: Permission
denied)
尝试:

$uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive)

或者:

$uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=664 # (more sensible)

使用uwsgi和nginx运行Django应用程序

$uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=664

配置uWSGI以使用一个.ini文件来运行
创建一个名为`mysite_uwsgi.ini`文件:

# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /path/to/your/project
# Django's wsgi file
module          = project.wsgi
# the virtualenv (full path)
home            = /path/to/virtualenv

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
socket          = /path/to/your/project/mysite.sock
# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true

并使用该文件运行uswgi:

$uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

基本到此就完成.

更多请参考:
Django:https://docs.djangoproject.com/en/1.7/
Nginx:http://nginx.org/en/docs/
uWSGI:https://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html
如有疑问,欢迎交流

Pingbacks are open.

Trackbacks
  1. Educacion onlina on 05/21/2019 9:40 p.m. #

    ACLegend's Weblog - django博客搭建(二)Nginx Django Uwsgi架构部署

  2. ferrann on 08/12/2019 8:53 p.m. #

    ACLegend's Weblog - django博客搭建(二)Nginx+Django+Uwsgi架构部署

Trackback URL

Comments

32 Comments

  • Berncleak
    21 May 2019, 10:45 | Reply
    Vinyl connects you a bit more deeply; it’s that tactile ingredient that rounds out the experience in a more meaningful way. Here’s your music link. Get it on vinyl if you like what you hear, the difference is worth it. http://magdalenabus.tk/page/causes-of-burns/
  • Educacion onlina
    21 May 2019, 21:40 | Reply
    ACLegend's Weblog - django博客搭建(二)Nginx Django Uwsgi架构部署
  • gamefly free trial
    24 May 2019, 15:37 | Reply
    you're in point of fact a good webmaster. The website loading speed is amazing. It kind of feels that you are doing any unique trick. In addition, The contents are masterwork. you've performed a great activity on this topic!
  • gamefly free trial
    24 May 2019, 15:37 | Reply
    you're in point of fact a good webmaster. The website loading speed is amazing. It kind of feels that you are doing any unique trick. In addition, The contents are masterwork. you've performed a great activity on this topic!
  • Poker Online ,
    25 May 2019, 17:19 | Reply
    This blog was... how do I say it? Relevant!! Finally I have found something which helped me. Thanks!
  • Poker Online ,
    25 May 2019, 17:19 | Reply
    This blog was... how do I say it? Relevant!! Finally I have found something which helped me. Thanks!
  • how to get help in windows 10
    26 May 2019, 05:39 | Reply
    great submit, very informative. I ponder why the opposite experts of this sector don't understand this. You should proceed your writing. I am confident, you've a huge readers' base already!
  • how to get help in windows 10
    26 May 2019, 05:39 | Reply
    great submit, very informative. I ponder why the opposite experts of this sector don't understand this. You should proceed your writing. I am confident, you've a huge readers' base already!
  • NoniRit
    02 Jun 2019, 03:08 | Reply
    For symptoms associated with: Anxiety, weakness, neuralgic pain Plus and so should not be seen as an endorsement or recommendation by Homeopathy Plus. Please see a trusted healthcare practitioner for advice on health problems. Further information abou <a href=http://anoxia.info/hypoxic-ischemic-encephalopathy-in-adults>hypoxic ischemic encephalopathy prognosis</a>
  • UhaTig
    02 Jun 2019, 08:42 | Reply
    Be sure to mention any of the following: amantadine (Osmolex ER), amitriptyline, amoxapine, carbamazepine (Carbatrol, Tegretol), citalopram (Celexa), clopidogrel (Plavix), desipramine (Norpramin), dexamethasone, digoxin (Lanoxin), doxepin (Silenor), efavirenz (Sustiva, in Atripla), escitalopram (Lexapro), flecainide (Tambocor), fluoxetine (Prozac), fluvoxamine (Luvox), haloperidol (Haldol <a href=http://Haloperidol.nodes.top/art/haldol-decanoate-dosing/>Haldol decanoate dosing</a>
  • ScrolSek
    03 Jun 2019, 17:16 | Reply
    Han pasado 14 meses y el tema de los talones va mejor aunque me duelen y se me inflaman los tobillos, el problema es la espalda, no puedo caminar ni 100 metros que me empieza un dolor en la zona dorso-lumbar y me canso muchГ­simo, el traumatГіlogo me dice que es normal que toda la carga del cuerpo se posa sobre la zona lumbar y que llevo toda esa zona afectada, me ha cambiado por completo la <a href=http://escoliosislumbar.info/charlie-douglas-wikipedia-estenosis-lumbar-cirugia>blue river</a>
  • PozziSew
    04 Jun 2019, 17:11 | Reply
    Xuan Thai is a producer for MSNBC in New York. She previously lived in Washington DC where she covered the White House during the Bush and Obama administrations. <a href=http://reflexology.nodes.top/art/reflexology-treatment/>Reflexology treatment</a>
  • mbscash
    05 Jun 2019, 23:57 | Reply
    certainly like your web site but you need to check the spelling on several of your posts. Many of them are rife with spelling problems and I in finding it very bothersome to inform the truth on the other hand I will surely come again again.
  • mbscash
    05 Jun 2019, 23:57 | Reply
    certainly like your web site but you need to check the spelling on several of your posts. Many of them are rife with spelling problems and I in finding it very bothersome to inform the truth on the other hand I will surely come again again.
  • CocoSnofs
    07 Jun 2019, 04:12 | Reply
    It was near a chapel and burial ground that were also destroyed by the farmer of the time. The old wall formed part of the boundary of the detached portion or enclave of the neighbouring parish of Methven. <a href=http://massage.nodes.top/art/prenatal-yoga-near-me/>Prenatal yoga near me</a>
  • DENdelo
    10 Jun 2019, 06:45 | Reply
    implants and reconstruction surgery, claims involving birth injuries such as cerebral palsy, profound neurological damage, including quadriplegia and paraplegia, claims arising from negligently performed operations and in accident and emergency <a href=http://denta.top/art/childrens-dental-care/>Children's dental care</a>
  • WINsat
    10 Jun 2019, 22:20 | Reply
    Lower back pain. Constipation. Physical problems with the coccyx, anus and genitals are associated with the First Chakra. Constipation. Physical problems with the coccyx, anus and genitals are associated with the First Chakra. <a href=http://wisdomteethremoval.denta.top/art/wisdom-teeth-removal-procedure/>Wisdom teeth removal procedure</a>
  • DOLItam
    14 Jun 2019, 09:32 | Reply
    Looking for a medical-grade chemical peel option? Vivesse Med Spa in Bloomfield, CT offers a wide variety of facial chemical peels. Learn more today! <a href=http://chemicalpeel.in/acne-scars-before-and-after-chemical-peel-do-they-look>acne scars before and after chemical peel</a>
  • SuttiCob
    16 Jun 2019, 12:21 | Reply
    Yeast feeds on sugar, making these secretions the most likely factor in overgrowth. People with diabetes also have increased levels of glycogen, a polysaccharide that the body uses to store glucose. <a href=http://yeastinfection.nodes.top/art/what-are-the-symptoms-of-a-yeast-infection/>What are the symptoms of a yeast infection</a>
  • Tesjed
    20 Jun 2019, 17:48 | Reply
    Your dentist will be able to remove plaque that hardens into tartar and clean around your gums in those hard to reach areas. Getting regular treatment will prevent plaque buildup, receding gums, cavities and tooth loss, all of which are associated with periodontal disease. You should have your teeth cleaned professionally at least twice every year. <a href=http://tartaronteeth.cf/art/tartar-stains-on-teeth/>Tartar stains on teeth</a>
  • EGGsymN
    22 Jun 2019, 07:56 | Reply
    Dr. J. Eric Hibbs Park Cities Dental Care 5600 W. Lovers Lane #216 Dallas, TX, 75209 214-351-2311 <a href=http://eggrolls.ml/art/veggie-egg-roll-calories/>Veggie egg roll calories</a>
  • Bimfep
    26 Jun 2019, 16:49 | Reply
    Citi ® Double Cash Card – 18 month BT offer, a partner card, is a cash back credit card that rewards you with cash back on all your purchases! With this <a href=http://gaselectricity.in/kentile-floors-manufacturers-of-asbestos-products>fuel guage</a>
  • agen bola online
    30 Jun 2019, 02:35 | Reply
    Wow, amazing blog structure! How long have you ever been running a blog for? you make blogging look easy. The entire look of your website is excellent, as smartly as the content material!
  • agen bola online
    30 Jun 2019, 02:36 | Reply
    Wow, amazing blog structure! How long have you ever been running a blog for? you make blogging look easy. The entire look of your website is excellent, as smartly as the content material!
  • TenCeal
    01 Jul 2019, 05:48 | Reply
    Though these do not work for everyone, they can help to increase the flow of biotin and other vital vitamins to the scalp and increasing the speed at which your hair will grow. Regardless of where you start when experiencing hair loss, it is important to <a href=http://biotin24.cf/art/biotin-uses/>Biotin uses</a>
  • AcuraDon
    07 Jul 2019, 02:52 | Reply
    Forum rules Do NOT post the full text of published articles. If you would like to discuss a news story please link to it and, at most, include a brief summary of the <a href=http://acjointarthritis.cf/art/arthritis-in/>Arthritis in</a>
  • QrlDuh
    08 Jul 2019, 02:32 | Reply
    they didnt try to push me into anything at all. free consultations and I am very happy with my botox result, their cost is cheaper than back home. I do believe they are offering a reputable service, i will definitely come back and recommend this place to everyone. <a href=http://botoxinjectionsites.cf/art/botox-glabellar-injection-sites/>Botox glabellar injection sites</a>
  • Yulzep
    13 Jul 2019, 09:22 | Reply
    We had left the nails up from last years harvest and so I just put them right back up in the same spot as last time. Why mess with a good thing? We should only have to let them cure for a couple more weeks. <a href=http://flakynails.cf/art/how-to-fix-flaky-nails/>How to fix flaky nails</a>
  • CepBync
    13 Jul 2019, 13:35 | Reply
    Moreover, the team is deeply committed to developing an alternative cryptocurrency backed by superior technical knowledge. What has started as an alternative to Bitcoin (BTC), today has built its own unique blockchain network. <a href=http://bitcoinpor.top/bitcoin-de-carteira-de-bitcoin-android-de-codigo/>bitcoin wallet for android</a>
  • ETHsor
    19 Jul 2019, 19:20 | Reply
    <>1,297, -20] If hes going to invest in bitcoin, he should do it by himself. Why drag a minor into it instead of all the other singers in the company? Why drag a minor into it instead of all the other singers in the company? <a href=https://bitcoinfr.biz/sql-avec-bert-bitcoin-crash-2016/>bitcoin crash</a>
  • progressive web app games
    26 Jul 2019, 18:41 | Reply
    Try any board or card [progressive web app games](http://ppgadvisors.co.uk/__media__/js/netsoltrademark.php?d=adanayorum.com%2F__media__%2Fjs%2Fnetsoltrademark.php%3Fd%3D3win8.city%2Fother-games%2Flpe88%2F21-lpe88 "progressive web app games") and then strip as well as you losing. It just isn't surprise that one of such popular genre is naughty gaming programs. These games are not in order to those who are dating. http://ppgadvisors.co.uk/__media__/js/netsoltrademark.php?d=adanayorum.com%2F__media__%2Fjs%2Fnetsoltrademark.php%3Fd%3D3win8.city%2Fother-games%2Flpe88%2F21-lpe88
  • ferrann
    12 Aug 2019, 20:53 | Reply
    ACLegend's Weblog - django博客搭建(二)Nginx+Django+Uwsgi架构部署
Post your comment

cancel reply