Nginx – How to run multiple websites from one Django project on nginx and uwsgi

djangonginxuwsgi

How to run two web sites or subdomains of a site from a single Django code base.

Each Django app in the project can then power a website on a different domain, but all the apps can still share a single database with a single administrative interface.

I'm Deploying with uWSGI-Nginx-Django

Thanks.

Best Answer

You have to deploy Django apps separately on uwsgi. An official site suggest to use emperor mode. First you have to write Upstart script at /etc/init/uwsgi.conf like this,

# Emperor uWSGI script

description "uWSGI Emperor"
start on runlevel [2345]
stop on runlevel [06]

# uwsgi location
#env UWSGI=/usr/bin/uwsgi
env UWSGI=/usr/local/bin/uwsgi

env LOGTO=<your log folder>

exec $UWSGI --master --die-on-term --emperor /etc/uwsgi/apps-enabled/ --pythonpath /usr/local/lib/python2.7/dist-packages --uid www-data --gid www-data --logto $LOGTO --enable-threads

In /etc/uwsgi/apps-enabled/, it'll contain your uwsgi configuration for each Django application. e.g. /etc/uwsgi/apps-enabled/app1.ini

Here's the sample configuration that I use.

[uwsgi]
; define variables to use in this script
; process name for easy identification in top
project = <project name>
base_dir = /<your base directory>/
chdir = %(base_dir)

pythonpath = /usr/local/lib/python2.7/dist-packages

http = 0.0.0.0:8000

uid = www-data
gid = www-data

procname = %(project)

; Enable master mode
; uWSGI’s built-in prefork+threading multi-worker management mode, activated by flicking the master switch on. For ; all practical serving deployments it’s not really a good idea not to use master mode.
master = true
master = 1

; run master process as root
master-as-root = true

; This value needs to be tuned
workers = 4

; Create pid file for easier process management
pidfile=/run/uwsgi/%(project).pid

# Specify your Django app here
module = mysite.wsgi:application
#or
#wsgi-file = %(base_dir)/<your wsgi file>.py

log-reopen = true
logto = /<your log directory>

chmod-socket = 666

vacuum = True
enable-threads = True

# Enable stats. View using `uwsgitop localhost:4000`
stats = :4000

; unix socket (referenced in nginx configuration)
socket = /run/uwsgi/%(project).sock

To run two web sites or subdomains of a site from a single Django code base, you need to set your domain at server_name directive for each Django application For example /etc/nginx/sites-enabled/yourweb1.conf that's bind to DjangoApp1

server_name app1.yourweb.com

/etc/nginx/sites-enabled/yourweb2.conf that's bind to DjangoApp2

server_name app2.yourweb.com

More information about deploying Django application with nginx