Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Community
Tutorials
By:JustinEllingwood
Questions
19
Projects
23
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
LogIn
SignUp
Share
Menu
Contents
1/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
HowToServeDjangoApplicationswithuWSGIand
NginxonUbuntu14.04
Mar11,2015
Nginx,Deployment,Django,Python,PythonFrameworksUbuntu
Introduction
DjangoisapowerfulwebframeworkthatcanhelpyougetyourPythonapplicationorwebsiteofftheground.Djangoincludesa
simplifieddevelopmentserverfortestingyourcodelocally,butforanythingevenslightlyproductionrelated,amoresecureand
powerfulwebserverisrequired.
Inthisguide,wewilldemonstratehowtoinstallandconfiguresomecomponentsonUbuntu14.04tosupportandserveDjango
applications.WewillconfiguretheuWSGIapplicationcontainerservertointerfacewithourapplications.WewillthensetupNginxto
reverseproxytouWSGI,givingusaccesstoitssecurityandperformancefeaturestoserveourapps.
PrerequisitesandGoals
Inordertocompletethisguide,youshouldhaveafreshUbuntu14.04serverinstancewithanon-rootuserwith
sudoprivileges
configured.Youcanlearnhowtosetthisupbyrunningthroughourinitialserversetupguide.
WewillbeinstallingDjangowithintwodifferentvirtualenvironments.Thiswillallowyourprojectsandtheirrequirementstobe
handledseparately.Wewillbecreatingtwosampleprojectssothatwecanrunthroughthestepsinamulti-projectenvironment.
Oncewehaveourapplications,wewillinstallandconfiguretheuWSGIapplicationserver.Thiswillserveasaninterfacetoour
applicationswhichwilltranslateclientrequestsusingHTTPtoPythoncallsthatourapplicationcanprocess.WewillthensetupNginx
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
2/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
infrontofuWSGItotakeadvantageofitshighperformanceconnectionhandlingmechanismsanditseasy-to-implementsecurity
features.
Let'sgetstarted.
InstallandConfigureVirtualEnvandVirtualEnvWrapper
WewillbeinstallingourDjangoprojectsintheirownvirtualenvironmentstoisolatetherequirementsforeach.Todothis,wewillbe
installing
virtualenv,whichcancreatePythonvirtualenvironments,and virtualenvwrapper,whichaddssomeusability
improvementstothe
virtualenvworkflow.
Wewillbeinstallingbothofthesecomponentsusing
pip,thePythonpackagemanager.ThiscanbeacquiredfromtheUbuntu
repositories:
Inthisguide,weareusingPythonversion2.IfyourcodeusesPython3,youcaninstallthe
havetosubstitutethe
Nowthatyouhave
python3-pippackage.Youwillthen
pipcommandsinthisguidewiththe pip3commandwhenoperatingoutsideofavirtualenvironment.
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
3/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Withthesecomponentsinstalled,wecannowconfigureourshellwiththeinformationitneedstoworkwiththe
script.Ourvirtualenvironmentswillallbeplacedwithinadirectoryinourhomefoldercalled
throughanenvironmentalvariablecalled
virtualenvwrapper
Envforeasyaccess.Thisisconfigured
WORKON_HOME.Wecanaddthistoourshellinitializationscriptandcansourcethevirtual
environmentwrapperscript.
IfyouareusingPython3andthe
pip3command,youwillhavetoaddanadditionallinetoyourshellinitializationscriptaswell:
RegardlessofwhichversionofPythonyouareusing,youneedtorunthefollowingcommands:
Now,sourceyourshellinitializationscriptsothatyoucanusethisfunctionalityinyourcurrentsession:
source ~/.bashrc
Youshouldnowhavedirectorycalled
Envinyourhomefolderwhichwillholdvirtualenvironmentinformation.
CreateDjangoProjects
Nowthatwehaveourvirtualenvironmenttools,wewillcreatetwovirtualenvironments,installDjangoineach,andstarttwoprojects.
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
4/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
CreatetheFirstProject
Wecancreateavirtualenvironmenteasilybyusingsomecommandsthatthe
virtualenvwrapperscriptmakesavailabletous.
Createyourfirstvirtualenvironmentwiththenameofyourfirstsiteorprojectbytyping:
mkvirtualenv firstsite
Thiswillcreateavirtualenvironment,installPythonand
pipwithinit,andactivatetheenvironment.Yourpromptwillchangeto
indicatethatyouarenowoperatingwithinyournewvirtualenvironment.Itwilllooksomethinglikethis:
(firstsite)user@hostname:~$.Thevalueintheparenthesesisthenameofyourvirtualenvironment.Anysoftwareinstalled
through
pipwillnowbeinstalledintothevirtualenvironmentinsteadofontheglobalsystem.Thisallowsustoisolateourpackages
onaper-projectbasis.
OurfirststepwillbetoinstallDjangoitself.Wecanuse
pipforthiswithout sudosinceweareinstallingthislocallyinourvirtual
environment:
WithDjangoinstalled,wecancreateourfirstsampleprojectbytyping:
cd ~
django-admin.py startproject firstsite
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
5/43
12/7/2015
Thiswillcreateadirectorycalled
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
firstsitewithinyourhomedirectory.Withinthisisamanagementscriptusedtohandlevarious
aspectsoftheprojectandanotherdirectoryofthesamenameusedtohousetheactualprojectcode.
Moveintothefirstleveldirectorysothatwecanbeginsettinguptheminimumrequirementsforoursampleproject.
cd ~/firstsite
BeginbymigratingthedatabasetoinitializetheSQLitedatabasethatourprojectwilluse.Youcansetupanalternativedatabasefor
yourapplicationifyouwish,butthisisoutsideofthescopeofthisguide:
./manage.py migrate
Youshouldnowhaveadatabasefilecalled
db.sqlite3inyourprojectdirectory.Now,wecancreateanadministrativeuserby
typing:
./manage.py createsuperuser
Youwillhavetoselectausername,giveacontactemailaddress,andthenselectandconfirmapassword.
Next,openthesettingsfilefortheprojectwithyourtexteditor:
nano firstsite/settings.py
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
6/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
SincewewillbesettingupNginxtoserveoursite,weneedtoconfigureadirectorywhichwillholdoursite'sstaticassets.Thiswill
allowNginxtoservethesedirectly,whichwillhaveapositiveimpactonperformance.WewilltellDjangotoplacetheseintoa
directorycalled
staticinourproject'sbasedirectory.Addthislinetothebottomofthefiletoconfigurethisbehavior:
Saveandclosethefilewhenyouarefinished.Now,collectoursite'sstaticelementsandplacethemwithinthatdirectorybytyping:
./manage.py collectstatic
Youcantype"yes"toconfirmtheactionandcollectthestaticcontent.Therewillbeanewdirectorycalled
staticinyourproject
directory.
Withallofthatoutoftheway,wecantestourprojectbytemporarilystartingthedevelopmentserver.Type:
Thiswillstartupthedevelopmentserveronport
8080.Visityourserver'sdomainnameorIPaddressfollowedby 8080inyour
browser:
http://server_domain_or_IP:8080
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
7/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Youshouldseeapagethatlookslikethis:
Add
/admintotheendoftheURLinyourbrowser'saddressbarandyouwillbetakentotheadminloginpage:
Usingtheadministrativelogincredentialsyouselectedwiththe
createsuperusercommand,logintotheserver.Youwillthenhave
accesstotheadministrationinterface:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
8/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Aftertestingthisfunctionalityout,stopthedevelopmentserverbytypingCTRL-Cinyourterminal.Wecannowmoveontooursecond
project.
CreatetheSecondProject
Thesecondprojectwillbecreatedinexactlythesamewayasthefirst.Wewillabridgetheexplanationinthissection,seeingashow
youhavealreadycompletedthisonce.
Movebacktoyourhomedirectoryandcreateasecondvirtualenvironmentforyournewproject.InstallDjangoinsideofthisnew
environmentonceitisactivated:
cd ~
mkvirtualenv secondsite
pip install django
Thenewenvironmentwillbecreatedandchangedto,leavingyourpreviousvirtualenvironment.ThisDjangoinstanceisentirely
separatefromtheotheroneyouconfigured.Thisallowsyoutomanagethemindependentlyandcustomizeasnecessary.
Createthesecondprojectandmoveintotheprojectdirectory:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
9/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Initializethedatabaseandcreateanadministrativeuser:
./manage.py migrate
./manage.py createsuperuser
Openthesettingsfile:
nano secondsite/settings.py
Addthelocationforthestaticfiles,justasyoudidinthepreviousproject:
Saveandclosethefile.Now,collectthestaticelementsintothatdirectorybytyping:
./manage.py collectstatic
Finally,fireupthedevelopmentservertotestoutthesite:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
10/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Youshouldchecktheregularsiteat:
http://server_domain_or_IP:8080
Alsologintotheadminsite:
http://server_domain_or_IP:8080/admin
Whenyou'veconfirmedthateverythingisworkingasexpected,typeCTRL-Cinyourterminaltostopthedevelopmentserver.
BackingOutoftheVirtualEnvironment
SincewearenowdonewiththeDjangoportionoftheguide,wecandeactivateoursecondvirtualenvironment:
deactivate
IfyouneedtoworkoneitherofyourDjangositesagain,youshouldreactivatetheirrespectiveenvironments.Youcandothatbyusing
the
workoncommand:
workon firstsite
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
11/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Or:
workon secondsite
Again,deactivatewhenyouarefinishedworkingonyoursites:
deactivate
SettinguptheuWSGIApplicationServer
NowthatwehavetwoDjangoprojectssetupandreadytogo,wecanconfigureuWSGI.uWSGIisanapplicationserverthatcan
communicatewithapplicationsoverastandardinterfacecalledWSGI.Tolearnmoreaboutthis,readthissectionofourguideon
settingupuWSGIandNginxonUbuntu14.04.
InstallinguWSGI
Unliketheguidelinkedabove,inthistutorial,we'llbeinstallinguWSGIglobally.ThiswillcreatelessfrictioninhandlingmultipleDjango
projects.BeforewecaninstalluWSGI,weneedthePythondevelopmentfilesthatthesoftwarerelieson.Wecaninstallthisdirectly
fromUbuntu'srepositories:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
12/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Nowthatthedevelopmentfilesareavailable,wecaninstalluWSGIgloballythrough
pipbytyping:
Wecanquicklytestthisapplicationserverbypassingittheinformationforoneofoursites.Forinstance,wecantellittoserveourfirst
projectbytyping:
Here,we'vetolduWSGItouseourvirtualenvironmentlocatedinour
the
~/Envdirectory,tochangetoourproject'sdirectory,andtouse
wsgi.pyfilestoredwithinourinner firstsitedirectorytoservethefile.Forourdemonstration,wetoldittoserveHTTPon
port
8080.Ifyougotoserver'sdomainnameorIPaddressinyourbrowser,followedby :8080,youwillseeyoursiteagain(thestatic
elementsinthe
/admininterfacewon'tworkyet).Whenyouarefinishedtestingoutthisfunctionality,typeCTRL-Cintheterminal.
CreatingConfigurationFiles
RunninguWSGIfromthecommandlineisusefulfortesting,butisn'tparticularlyhelpfulforanactualdeployment.Instead,wewillrun
uWSGIin"Emperormode",whichallowsamasterprocesstomanageseparateapplicationsautomaticallygivenasetofconfiguration
files.
Createadirectorythatwillholdyourconfigurationfiles.Sincethisisaglobalprocess,wewillcreateadirectorycalled
/etc/uwsgi/sitestostoreourconfigurationfiles.Moveintothedirectoryafteryoucreateit:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
13/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Inthisdirectory,wewillplaceourconfigurationfiles.Weneedaconfigurationfileforeachoftheprojectsweareserving.TheuWSGI
processcantakeconfigurationfilesinavarietyofformats,butwewilluse
.inifilesduetotheirsimplicity.
Createafileforyourfirstprojectandopenitinyourtexteditor:
Inside,wemustbeginwiththe
[uwsgi]sectionheader.Allofourinformationwillgobeneaththisheader.Wearealsogoingtouse
variablestomakeourconfigurationfilemorereusable.Aftertheheader,setavariablecalled
project.Addavariablecalled
projectwiththenameofyourfirst
basewiththepathtoyouruser'shomedirectory:
[uwsgi]
project = firstsite
base = /home/user
Next,weneedtoconfigureuWSGIsothatithandlesourprojectcorrectly.Weneedtochangeintotherootprojectdirectorybysetting
the
chdiroption.Wecancombinethehomedirectoryandprojectnamesettingthatwesetearlierbyusingthe %(variable_name)
syntax.Thiswillbereplacedbythevalueofthevariablewhentheconfigisread.
Inasimilarway,wewillindicatethevirtualenvironmentforourproject.Bysettingthemodule,wecanindicateexactlyhowtointerface
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
14/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
withourproject(byimportingthe"application"callablefromthe
wsgi.pyfilewithinourprojectdirectory).Theconfigurationofthese
itemswilllooklikethis:
[uwsgi]
project = firstsite
base = /home/user
chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application
Wewanttocreateamasterprocesswith5workers.Wecandothisbyaddingthis:
[uwsgi]
project = firstsite
base = /home/user
chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application
master = true
processes = 5
NextweneedtospecifyhowuWSGIshouldlistenforconnections.InourtestofuWSGI,weusedHTTPandanetworkport.However,
sincewearegoingtobeusingNginxasareverseproxy,wehavebetteroptions.
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
15/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Insteadofusinganetworkport,sinceallofthecomponentsareoperatingonasingleserver,wecanuseaUnixsocket.Thisismore
secureandoffersbetterperformance.ThissocketwillnotuseHTTP,butinsteadwillimplementuWSGI's
uwsgiprotocol,whichisa
fastbinaryprotocolfordesignedforcommunicatingwithotherservers.Nginxcannativelyproxyusingthe
uwsgiprotocol,sothisis
ourbestchoice.
Wewillalsomodifythepermissionsofthesocketbecausewewillbegivingthewebserverwriteaccess.We'llsetthe
vacuumoption
sothatthesocketfilewillbeautomaticallycleanedupwhentheserviceisstopped:
[uwsgi]
project = firstsite
base = /home/user
chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application
master = true
processes = 5
socket = %(base)/%(project)/%(project).sock
chmod-socket = 664
vacuum = true
Withthis,ourfirstproject'suWSGIconfigurationiscomplete.Saveandclosethefile.
Theadvantageofsettingupthefileusingvariablesisthatitmakesitincrediblysimpletoreuse.Copyyourfirstproject'sconfiguration
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
16/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
filetouseasabaseforyoursecondconfigurationfile:
Openthesecondconfigurationfilewithyourtexteditor:
Weonlyneedtochangeasinglevalueinthisfileinordertomakeitworkforoursecondproject.Modifythe
projectvariablewith
thenameyou'veusedforyoursecondproject:
[uwsgi]
project = secondsite
base = /home/user
chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application
master = true
processes = 5
socket = %(base)/%(project)/%(project).sock
chmod-socket = 664
vacuum = true
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
17/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Saveandclosethefilewhenyouarefinished.Yoursecondprojectshouldbereadytogonow.
CreateanUpstartScriptforuWSGI
WenowhavetheconfigurationfilesweneedtoserveourDjangoprojects,butwestillhaven'tautomatedtheprocess.Next,we'll
createanUpstartscripttoautomaticallystartuWSGIatboot.
WewillcreateanUpstartscriptinthe
/etc/initdirectory,wherethesefilesarechecked:
StartbysettingadescriptionforyouruWSGIserviceandindicatingtherunlevelswhereitshouldautomaticallyrun.Wewillsetoursto
runonrunlevels2,3,4,and5,whicharetheconventionalmulti-userrunlevels:
Next,weneedtosettheusernameandgroupthattheprocesswillberunas.Wewillruntheprocessunderourownusernamesince
weownallofthefiles.Forthegroup,weneedtosetittothe
www-datagroupthatNginxwillrununder.Oursocketsettingsfromthe
uWSGIconfigurationfileshouldthenallowthewebservertowritetothesocket.Changetheusernamebelowtomatchyourusername
ontheserver:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
18/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Finally,weneedtospecifytheactualcommandtoexecute.WeneedtostartuWSGIinEmperormodeandpassinthedirectorywhere
westoredourconfigurationfiles.uWSGIwillreadthefilesandserveeachofourprojects:
Whenyouarefinished,saveandclosethefile.Wewon'tstartuWSGIyetsincewewillnothavethe
www-datagroupavailableuntil
afterweinstallNginx.
InstallandConfigureNginxasaReverseProxy
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
19/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
WithuWSGIconfiguredandreadytogo,wecannowinstallandconfigureNginxasourreverseproxy.Thiscanbedownloadedfrom
Ubuntu'sdefaultrepositories:
OnceNginxisinstalled,wecangoaheadandcreateaserverblockconfigurationfileforeachofourprojects.Startwiththefirst
projectbycreatingaserverblockconfigurationfile:
Inside,wecanstartourserverblockbyindicatingtheportnumberanddomainnamewhereourfirstprojectshouldbeaccessible.
We'llassumethatyouhaveadomainnameforeach:
server {
listen 80;
server_name firstsite.com www.firstsite.com;
}
Next,wecantellNginxnottoworryifitcan'tfindafavicon.Wewillalsopointittothelocationofourstaticfilesdirectorywherewe
collectedoursite'sstaticelements:
server {
listen 80;
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
20/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Afterthat,wecanusethe
uwsgi_passdirectivetopassthetraffictooursocketfile.Thesocketfilethatweconfiguredwascalled
server {
listen 80;
server_name firstsite.com www.firstsite.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/user/firstsite;
}
location / {
include
uwsgi_params;
uwsgi_pass
unix:/home/user/firstsite/firstsite.sock;
}
}
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
21/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Thatisactuallyalltheconfigurationweneed.Saveandclosethefilewhenyouarefinished.
Wewillusethisasabasisforoursecondproject'sNginxconfigurationfile.Copyitovernow:
Openthenewfileinyourtexteditor:
Here,you'llhavetochangeanyreferenceto
firstsitewithareferenceto secondsite.You'llalsohavetomodifythe
server_namesothatyoursecondprojectrespondstoadifferentdomainname.Whenyouarefinished,itwilllooksomethinglike
this:
server {
listen 80;
server_name secondsite.com www.secondsite.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/user/secondsite;
}
location / {
include
uwsgi_params;
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
22/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
uwsgi_pass
unix:/home/user/secondsite/secondsite.sock;
}
}
Saveandclosethefilewhenyouarefinished.
Next,linkbothofyournewconfigurationfilestoNginx's
sites-enableddirectorytoenablethem:
Checktheconfigurationsyntaxbytyping:
Ifnosyntaxerrorsaredetected,youcanrestartyourNginxservicetoloadthenewconfiguration:
Ifyourememberfromearlier,weneveractuallystartedtheuWSGIserver.Dothatnowbytyping:
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
23/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Youshouldnowbeabletoreachyourtwoprojectsbygoingtotheirrespectivedomainnames.Boththepublicandadministrative
interfacesshouldworkasexpected.
Conclusion
Inthisguide,we'vesetuptwoDjangoprojects,eachintheirownvirtualenvironments.We'veconfigureduWSGItoserveeachproject
independentlyusingthevirtualenvironmentconfiguredforeach.Afterwards,wesetupNginxtoactasareverseproxytohandle
clientconnectionsandservethecorrectprojectdependingontheclientrequest.
Djangomakescreatingprojectsandapplicationssimplebyprovidingmanyofthecommonpieces,allowingyoutofocusontheunique
elements.Byleveragingthegeneraltoolchaindescribedinthisarticle,youcaneasilyservetheapplicationsyoucreatefromasingle
server.
Heart
19
Share
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
Subscribe
24/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Author:
JustinEllingwood
SpinupanSSDcloudserverinunderaminute.
Simplesetup.Fullrootaccess.Straightforwardpricing.
DEPLOYSERVER
RelatedTutorials
HowtoDeployaSymfonyApplicationtoProductiononUbuntu14.04
SCROLLTOTOP
HowToDeployaClojureWebApplicationonUbuntu14.04
HowToDeployaHugoSitetoProductionwithGitHooksonUbuntu14.04
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
25/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
HowToInstallElasticsearch1.7,Logstash1.5,andKibana4.1(ELKStack)onCentOS7
HowToInstallElasticsearch1.7,Logstash1.5,andKibana4.1(ELKStack)onUbuntu14.04
23Comments
Leaveacomment...
LogIntoComment
rjuppa March17,2015
Works!Greattutorial!
Haveonequestion:Iuseenv.variableinmysettings.pylikeos.environ.get('DB_NAME'),
buttheyarenotworking.Anyideawhytheydontwork?
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
26/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
jellingwood March17,2015
@rjuppa:YoushouldbeabletopassinenvironmentalvariablesbysettingtheminyouruWSGIconfigurationfile.Djangowon't
beabletogetthemfromtheenvironmentitself.
Inyour
.inifileforyourapplications,tryaddingsomelineswiththeenvironmentalvariablesyouneed,likethis:
[uwsgi]
...
env=DB_NAME=your_name_here
Ihaven'ttestedtheabove,butIbelievethatshouldmakethatinformationavailabletoyourDjangoproject.
asb March17,2015
Environmentalvariablesfromyourloginshellarenotavailablefrominsidethe
virtualenvCheckoutthisgreatanswerover
onStackOverflowforinfoonhowyoucansetupahooktoexporttheneededvariables.
rjuppa March17,2015
[deleted]
tbrightbill June2,2015
Hithere,
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
27/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
FollowedthistutorialtotheT(greatjobbytheway!).However,Iamgettinga502badgatewayerror.IgottothepartwiththeDjango
server,anditworkedcorrectly,itstheUWSGIconfigthatmust'vecausedthe502.Anyideas?
tbrightbill June3,2015
Followedupabitmore.Frommyerror.logfile,Iamgettingapermissionserrorwithregardtotheproject.sock-permission
denied.Havechangedthesettingsinthe.inifileto777withnoluck.Anyadvicehelps!
jellingwood June3,2015
@tbrightbill:Ijustranthroughthisguideagainfromstarttofinishandwasn'tabletoreproducetheproblemyou'reseeing.If
youcanpostyour
anything.
juani.navarrog July19,2015
juani.navarrog July18,2015
Like@tbrightbill,igeta502error.Seemslikeitcan'tcreatethesocket.https://gist.github.com/anonymous/40284b9c84bea2df6fca
anujacharya1 August13,2015
Iwasabletomaketheuwsgistartusinguwsgi--http:8080--home/home/user/Env/firstsite--chdir/home/user/firstsite-wfirstsite.wsgi
Iwasnotabletostartusinguwsgiconfigurationfile,thereisnoportmentionintheuwsgiconfigfile.
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
28/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Whereistheuseofsetgidwww-data?
HowtomentionservernameinnginxifIhaveIPaddress?
kimstacks August25,2015
Hithere,
Ihavefollowedyoursetup.
TheissueIcontinuetohaveisthatonlythefirstsite.sock(inmycase,it'scalleddjangoonpy2.sock)isshowingup.The
secondsite.sockisNOT.
Thesearemyfollowingfiles:
/etc/nginx/sites-enabled/djangoonpy2.conf
server {
listen 80;
server_name djangoonpy2.app;
location = favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /src/Apps/djangoonpy2;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/run/uwsgi/djangoonpy2.sock;
}
}
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
29/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
/etc/nginx/sites-enabled/djangoonpy3.conf
server {
listen 80;
server_name djangoonpy3.app;
location = favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /src/Apps/djangoonpy3;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/run/uwsgi/djangoonpy3.sock;
}
}
/etc/init/uwsgi.conf
description "uWSGI application server in Emperor mode"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
pre-start script
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
30/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
mkdir -p /run/uwsgi
chown vagrant:www-data /run/uwsgi
end script
exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
/etc/uwsgi/sites/djangoonpy2.ini
[uwsgi]
project = djangoonpy2
username = vagrant
projectbase = /src/Apps
userbase = /home/%(username)
chdir = %(projectbase)/%(project)
home = %(userbase)/.virtualenvs/%(project)
module = %(project).wsgi:application
master = true
processes = 5
uid = %(username)
socket = /run/uwsgi/%(project).sock
chown-socket = %(username):www-data
chmod-socket = 664
vacuum = true
/etc/uwsgi/sites/djangoonpy3.ini
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
31/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
[uwsgi]
project = djangoonpy3
username = vagrant
projectbase = /src/Apps
userbase = /home/%(username)
chdir = %(projectbase)/%(project)
home = %(userbase)/.virtualenvs/%(project)
module = %(project).wsgi:application
master = true
processes = 5
uid = %(username)
socket = /run/uwsgi/%(project).sock
chown-socket = %(username):www-data
chmod-socket = 664
vacuum = true
Ihavealsodone:
Ihavealsochmod
WhydidIuse
/src/Appsas755
/run/uwsgi?
Becauseforsomereasonusing
/home/usernamejustdoesn'twork.
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
32/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
kimstacks August25,2015
@jellingwood
UPDATE
whichworks
whichfailedbecauseIgeta
Isurmisedthishastodowiththefactthattheglobaluwsgiisforpython2.
djangoonpy3.inifrom /etc/uwsgi/sitesandthenproceededtocreateanothervirtualenv,anotherproject,
etcnamed s
econddjangoonpy2
SoIremoved
thistimeitworked.
Myquestionis,howdoIrunmultipledjangoappsusinguwsgiandnginxonubuntu14.04whereoneofthemisonpython3and
therestareonpython2?
jellingwood August25,2015
@kimstacks:Youwillprobablyhavetohavemultipleemperorprocessesinthiscase.Usually,uWSGIisbuiltagainsta
particularversionofPython.However,itisapparentlypossibleto"stack"emperorssothatamasteremperorprocesscancall
individualPythonversion-specificemperorprocesses,whichcanthenspawnyourDjangoprojects.Iseethatyou'vealready
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
33/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
foundthisStackOverflowthreadonthesubject.
Ijusttriedthisforthefirsttimepersonallyandwasabletogetittowork.Theprocessisstillverynewtome,butI'lltryto
explain.
Startoffbygoingthroughthetutorialasusual.ForyourPython3site,you'llwanttocreatethevirtualenvironmentlikethis:
Ifyourunthroughtheguide,youwillhaveuWSGIbuiltagainstPython2installed,andwillbeabletoserveyourPython2
sites.TogetthePython3versionworking,you'llhavetofirstinstallthedevelopmentfilesthrough
apt:
MakeanewvirtualenvironmentforthePython3versionofuWSGI(youcouldjustinstallthisinyourPython3virtual
environment,butthisallowsforamoreexplicitseparationsothatit'sobviousthatitcouldrunanynumberofPython3sites):
Withinthisnewvirtualenvironment,installuWSGI.ThiswillbebuiltagainstPython3:
Deactivatethevirtualenvironmentwhenyouarefinished:
$ deactivate
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
34/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
ThenextchangewillbeintheuWSGIstructure.Sincethesystem'suWSGIisbuiltagainstPython2,youcankeepthePython
2sitesinthe
/etc/uwsgi/sitesdirectoryasnormal.MakeanewdirectorythatwillholdalloftheuWSGIconfigsforyour
Python3sites:
MovetheuWSGIconfigurationsforthePython3site(s)intothisnewdirectory:
WethenneedtoaddanadditionaluWSGIconfigurationfiletothe
/etc/uwsgi/sitesdirectory.
This
.inifilewillspawnanotheruWSGIemperorprocess,thistimeusingthePython3versionofuWSGIthatweinstalledin
thevirtualenvironment.ThisemperorprocesswillreadtheuWSGIconfigurationfileswithinthe
/etc/uwsgi/sites_python3directory:
/etc/uwsgi/sites/spawn_python3.ini
[uwsgi]
project = python3uwsgi
base = /home/user
privileged-binary-patch-arg = %(base)/Env/%(project)/bin/uwsgi --emperor /etc/uwsgi/sites_python3
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
35/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Now,whenyoustartthePython2versionofuWSGI(usingtheupstartfilefromthisguide),itwill,inturn,spawnanadditional
Python3emperortohandleyourPython3sites.
Ifiguredthisoutonceandvalidateditasecondtime,butit'sstillacompletelynewprocessforme,sotaketheaboveasa
startingpoint.Hopefullythathelpsthough!
kimstacks August28,2015
@jellingwood
Yourcodeworksbeautifully.
Recommendyouwritethisasaseparatearticleforubuntu14.04andcentos7.
Whatimpressesmethemostisthat:
youfoundthesameStackOverflowthreadifound.Yetyouwereabletocomeupwithasolutionthatiscompletelydifferent
fromanyoftheanswersthereorfromthedocumentationtheycited.
Q1)Howdidyoureverseengineerfromtheiranswertotheoneyouwrotehere?
Letmetrytounderstandyoursolution.
Youbasicallyusethesystemuwsgiinemperormodetorunallthe.inifilesinside/etc/uwsgi/siteswhichusuallycontainallthe
inifilesassociatedwithdjangoappsrunninginpython2.
Thisincludesthespawn_python3.ini
spawnpython3.iniineffectcallstheuwsgiinsidethepython3uwsgivirtualenvtoruninemperormodeaswellbutonly
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
36/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
affectingtheiniinside/etc/uwsgi/sitespython3
Q2)AmIcorrect?WheredidIunderstandwrongly?
SupposeIhavemultiplepython2djangoapps.Justthatsomeneedtobeonpython2.7andsomeneedtobeonpython2.8.
Q3)WillthismeanthatIneedtohaveaseparatevirtualenvforpython28uwsgi?
jellingwood August28,2015
@kimstacks:Thanksforthekindwords.
Asforyourquestions:
Q1)IbasicallylookedattheuWSGIdocumentationtotrytoseeifIcouldfigureouthowtoimplementthenestedEmperorcalls
thattheStackOverflowansweralludedto.Idon'tthinkIwouldhaverealizedthatwaspossibleonmyown.TheuWSGI
documentationitselfcontainedmostofthepiecesneeded(itdiscussedstartingdifferentbinariesasvassals.AuWSGIprocess
runninginemperormodehappenstofallintothiscategory).IwasluckyinthatmyfirstattemptatcallingtheseparatePython
3uWSGIprocesswassuccessful.I'mnotsurehowwellIwouldhavebeenabletotroubleshoototherwise.
Q2)Yourunderstandingofthesolutionisexactlycorrect.Basically,thePython2versionofuWSGItreatsthe
spawn_python3.inifileasjustanotherprocesstomanage.WebasicallyuseittochainloadthePython3filesbykicking
offthePython3specificuWSGIversion.ThePython3versionseemstorunjustasifitwerestartedonitsown,which
definitelyhelpsinminimizingthecomplexityofthesolution.
Q3)I'mnotsureifyou'dneedaseparateuWSGIinstancefor2.7vs2.8.I'ddefinitelytrytoseeifitjustworksas-isfirst.Letme
knowifyoufigurethatout.
Anyways,I'mgladthesolutionIpostedworkedforyou.IfyouenduphavingmaintainmanydifferentversionsofuWSGI,the
chainloadingmaybecomelessappealing.Inthatcase,youmightwanttothinkaboutmigratingtousingasingleuWSGI
binaryw/pluginsper-version,asdescribedhere.
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
37/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
kimstacks September1,2015
@jellingwood
Ireadthedocumentationandalsosawthepartaboutvassals.
Totallydidn'tunderstandasinglebitatall.Stillcannotfindtheexactpartinthedocsthatgaveyouthea-hamomentonthis.
Ihaveyettotrydifferentversionsofpython2.
Notreallyneededatthemoment,butIaskedincaseforfutureIdoneedsuchasituation.
Seriously,dowritethisupasaseparatearticle.Ithinkthereisaneedforthis.Yourwriteupisfarmorereadablethanthe
officialuwsgidocumentation.
rijojohn85 August27,2015
Hi,
Thanksfortutorial.Ifollowedallthesteps,butwhenirun
Igotthefollowingerror:
Failed to start uwsgi.service: Unit uwsgi.service failed to load: No such file or directory.
IamrunningUbuntu15.04.Isthattheproblem?
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
38/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
myuswgi.conffileis:
myinifileis:
[uwsgi]
project = mysterybox
base = /home/rijo
chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application
master = true
processes = 5
socket = %(base)/%(project)/%(project).sock
chmod-socket = 664
vacuum = true
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
39/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Thanks:)
jellingwood August27,2015
@rijojohn85:Yes,runningthisguideonUbuntu15.04wouldbetheproblem.Ubuntu6.10throughUbuntu14.10allusedthe
"Upstart"initdaemon.Inthisguide,the
uwsgi.conffileisanUpstartinitscript.Ubuntuchangedinitdaemonsto"systemd"
startingwith15.04.Thescripttypesarenotcompatiblewithoneanother.
Soinordertogetthisguidetowork,youwilleitherhavetostartoverusingUbuntu14.04,orwillhavetowriteyourown
systemdservicefile.ThereisasystemdservicefileincludedintheCentOS7versionofthistutorial,butitmayhavetobe
modifiedtoruncorrectlyonanUbuntusystem.
Hosni October20,2015
Itseemsthatit'salsothecasefordebian8.1
sergeypisarevsk September20,2015
sudoserviceuwsgistart-->start:Jobfailedtostart(((
kedr September23,2015
Isthisbecauseuwsgiwasinstalledwithpipandnotapt-get?Ifyoulookinyour/etc/init.ddirectory,therewillprobablynotbe
auwsgifileintherecorrect?
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
40/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
kedr September23,2015
Whereisthesockfilesupposedtocomefrom?Isitautomaticallygenerated?
krishnaburaka October14,2015
Ifollowedthetutorial,andforthefirstsiteitworkedoncebutnowiamgettingforthefirstsite"Couldnotconnecttotherequested
serverhost."
Howcanifigureoutwheretheerroroccured?Pleasehelpstucksinceaday!!
a1exus October19,2015
I'mtryingtofollowthistutorial,yetsomethingisamiss:
41/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
Requirement already satisfied (use --upgrade to upgrade): argparse in /usr/lib/python2.7 (from stevedore->vir
Installing collected packages: virtualenv, virtualenvwrapper, stevedore, virtualenv-clone, six, pbr
Running setup.py install for virtualenv-clone
Installing virtualenv-clone script to /usr/local/bin
Found existing installation: six 1.5.2
Not uninstalling six at /usr/lib/python2.7/dist-packages, owned by OS
Successfully installed virtualenv virtualenvwrapper stevedore virtualenv-clone six pbr
Cleaning up...
root@alexus:~# echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.bashrc
root@alexus:~# echo "export WORKON_HOME=~/Env" >> ~/.bashrc
root@alexus:~# echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc
root@alexus:~# source ~/.bashrc
/usr/bin/python3: Error while finding spec for 'virtualenvwrapper.hook_loader' (<class 'ImportError'>: No mod
virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 and that PATH is
set properly.
root@alexus:~#
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
42/43
12/7/2015
How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 | DigitalOcean
ThisworkislicensedunderaCreative
CommonsAttribution-NonCommercialShareAlike4.0InternationalLicense.
Copyright2015DigitalOceanInc.
Community
Tutorials
Terms,Privacy,&Copyright
Questions
Security
Projects
Tags
ReportaBug
RSS
GetPaidtoWrite
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04
43/43