Total Pageviews

Thursday 21 April 2016

Gunicorn + Django 部署小记

服务器拿到手后第一件事就是更新apt-get,要换源什么的自己搜一大堆。之前因为系统不小心选成了Ubuntu 10.04了,遇到一大堆问题,后来换到12.04一切顺利。

apt-get update

pip

pip还是建议更换源,速度是飞一般的感觉。具体方法可以看看我之前介绍的那篇文章《Pythoner的福利,豆瓣的PyPI源
sudo apt-get install python-pip

Django

Django不用说肯定是用pip装,我一般是用的最新版,这样就可以了。
sudo pip install django

Nginx

首先给默认的Nginx配置备个份,这是好习惯。目录位于/etc/nginx/sites-available/default
cp /etc/nginx/sites-available/default default.bak
然后Vim编辑
vim /etc/nginx/sites-available/default
server {
        listen   80;

        server_name www.isaced.com;
        access_log  /var/log/nginx/isaced.log;

        location / {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /static/ {
                root /data/isaced; #Django项目所在目录
        }
以上是最简单的Nginx配置,目的是为能跑起来就行,更多其他详细配置还请参照其他文章。

Gunicorn

Gunicorn是一个朋友(CloverStd)推荐的,一个开源Python WSGI UNIX的HTTP服务器,Github仓库地址在这,传说速度快(配置快、运行快)、简单,默认是同步工作,支持Gevent、Eventlet异步,支持Tornado,官方有很详细的文档可以参阅。
需要在你的Django项目的settings.py中的INSTALLED_APPS加入:gunicorn
gunicorn --worker-class=gevent isaced.wsgi:application
  • --worker-class
    指定工作方式,这里我用的gevent
    如果提示You need gevent installed to use this worker则表示你还没有安装gevent。
  • isaced.wsgi:application
    这里是指你的项目名,在Django创建项目的时候会自动生成对应名字文件夹中的wsgi.py,这里就是指的它。
###nohup
nohup是一个Linux命令,用来不挂断地运行某条命令。这里我们用它来执行gunicorn,来保持gunicorn进程不会被挂断。
nohup gunicorn --worker-class=gevent NSLoger.wsgi:application -b 127.0.0.1:8000&
--worker-class来指定工作方式为gevent,-b指定地址和端口号。
注意:在尾部加上&(and)字符表示后台运行
执行这条命令后可以用ps命令查看进程,就能看到gunicorn了~

Start

好了,以上就是整个服务器的配置了。然后我们重启下Nginx,刷新页面就能看到你的Django App了。
sudo service nginx restart
部署日记就到这里了.
另外再推荐一篇文章:
----------------------------------

Setting up Django with Nginx, Gunicorn, virtualenv, supervisor and PostgreSQL


Django is an efficient, versatile and dynamically evolving web application development framework. When Django initially gained popularity, the recommended setup for running Django applications was based around Apache with mod_wsgi. The art of running Django advanced and these days the recommended configuration is more efficient and resilient, but also more complex and includes such tools as: Nginx, Gunicorn, virtualenv, supervisord and PostgreSQL.
In this text I will explain how to combine all of these components into a Django server running on Linux.

Prerequisites

I assume you have a server available on which you have root privileges. I am using a server running Debian 7, so everything here should also work on an Ubuntu server or other Debian-based distribution. If you’re using an RPM-based distro (such as CentOS), you will need to replace the aptitude commands by their yum counterparts and if you’re using FreeBSD you can install the components from ports.
If you don’t have a server to play with, I would recommend the inexpensive VPS servers offered by Digital Ocean. If you click through this link when signing up, you’ll pay a bit of my server bill :)
I’m also assuming you configured your DNS to point a domain at the server’s IP. In this text, I pretend your domain is example.com

Update your system

Let’s get started by making sure our system is up to date.
$ sudo aptitude update
$ sudo aptitude upgrade

PostgreSQL

To install PostgreSQL on a Debian-based system run this command:
$ sudo aptitude install postgresql postgresql-contrib
Create a database user and a new database for the app. Grab a perfect password from GRC.
$ sudo su - postgres
postgres@django:~$ createuser --interactive -P
Enter name of role to add: hello_django
Enter password for new role: 
Enter it again: 
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
postgres@django:~$

postgres@django:~$ createdb --owner hello_django hello
postgres@django:~$ logout
$

Application user

Even though Django has a pretty good security track record, web applications can become compromised. If the application has limited access to resources on your server, potential damage can also be limited. Your web applications should run as system users with limited privileges.
Create a user for your app, named hello and assigned to a system group called webapps.
$ sudo groupadd --system webapps
$ sudo useradd --system --gid webapps --shell /bin/bash --home /webapps/hello_django hello

Install virtualenv and create an environment for you app

Virtualenv is a tool which allows you to create separate Python environments on your system. This allows you to run applications with different sets of requirements concurrently (e.g. one based on Django 1.5, another based on 1.6). virtualenv is easy to install on Debian:
$ sudo aptitude install python-virtualenv

Create and activate an environment for your application

I like to keep all my web apps in the /webapps/ directory. If you prefer /var/www//srv/ or something else, use that instead. Create a directory to store your application in /webapps/hello_django/ and change the owner of that directory to your application user hello
$ sudo mkdir -p /webapps/hello_django/
$ sudo chown hello /webapps/hello_django/
As the application user create a virtual Python environment in the application directory:
$ sudo su - hello
hello@django:~$ cd /webapps/hello_django/
hello@django:~$ virtualenv .

New python executable in hello_django/bin/python
Installing distribute..............done.
Installing pip.....................done.

hello@django:~$ source bin/activate
(hello_django)hello@django:~$ 
Your environment is now activated and you can proceed to install Django inside it.
(hello_django)hello@django:~$ pip install django

Downloading/unpacking django
(...)
Installing collected packages: django
(...)
Successfully installed django
Cleaning up...
Your environment with Django should be ready to use. Go ahead and create an empty Django project.
(hello_django)hello@django:~$ django-admin.py startproject hello
You can test it by running the development server:
(hello_django)hello@django:~$ cd hello
(hello_django)hello@django:~$ python manage.py runserver example.com:8000
Validating models...

0 errors found
June 09, 2013 - 06:12:00
Django version 1.5.1, using settings 'hello.settings'
Development server is running at http://example.com:8000/
Quit the server with CONTROL-C.
You should now be able to access your development server from http://example.com:8000

Allowing other users write access to the application directory

Your application will run as the user hello, who owns the entire application directory. If you want regular user to be able to change application files, you can set the group owner of the directory to users and give the group write permissions.
$ sudo chown -R hello:users /webapps/hello_django
$ sudo chmod -R g+w /webapps/hello_django
You can check what groups you’re a member of by issuing the groups command or id.
$ id
uid=1000(michal) gid=1000(michal) groups=1000(michal),27(sudo),100(users)
If you’re not a member of users, you can add yourself to the group with this command:
$ sudo usermod -a -G users `whoami`
Group memberships are assigned during login, so you may need to log out and back in again for the system to recognize your new group.

Configure PostgreSQL to work with Django

In order to use Django with PostgreSQL you will need to install the psycopg2 database adapter in your virtual environment. This step requires the compilation of a native extension (written in C). The compilation will fail if it cannot find header files and static libraries required for linking C programs with libpq (library for communication with Postgres) and building Python modules (python-dev package). We have to install these two packages first, then we can install psycopg2using PIP.
Install dependencies:
$ sudo aptitude install libpq-dev python-dev
Install psycopg2 database adapter:
(hello_django)hello@django:~$ pip install psycopg2
You can now configure the databases section in your settings.py:


1
2
3
4
5
6
7
8
9
10
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'hello',
        'USER': 'hello_django',
        'PASSWORD': '1Ak5RTQt7mtw0OREsfPhJYzXIak41gnrm5NWYEosCeIduJck10awIzoys1wvbL8',
        'HOST': 'localhost',
        'PORT': '',                      # Set to empty string for default.
    }
}

And finally build the initial database for Django:
(hello_django)hello@django:~$ python manage.py syncdb

Gunicorn

In production we won’t be using Django’s single-threaded development server, but a dedicated application server called gunicorn.
Install gunicorn in your application’s virtual environment:
(hello_django)hello@django:~$ pip install gunicorn
Downloading/unpacking gunicorn
  Downloading gunicorn-0.17.4.tar.gz (372Kb): 372Kb downloaded
  Running setup.py egg_info for package gunicorn

Installing collected packages: gunicorn
  Running setup.py install for gunicorn

    Installing gunicorn_paster script to /webapps/hello_django/bin
    Installing gunicorn script to /webapps/hello_django/bin
    Installing gunicorn_django script to /webapps/hello_django/bin
Successfully installed gunicorn
Cleaning up...
Now that you have gunicorn, you can test whether it can serve your Django application by running the following command:
(hello_django)hello@django:~$ gunicorn hello.wsgi:application --bind example.com:8001
You should now be able to access the Gunicorn server from http://example.com:8001 . I intentionally changed port 8000 to 8001 to force your browser to establish a new connection.
Gunicorn is installed and ready to serve your app. Let’s set some configuration options to make it more useful. I like to set a number of parameters, so let’s put them all into a small BASH script, which I save as bin/gunicorn_start
#!/bin/bash
NAME="hello_app" # Name of the application
DJANGODIR=/webapps/hello_django/hello # Django project directory
SOCKFILE=/webapps/hello_django/run/gunicorn.sock # we will communicte using this unix socket
USER=hello # the user to run as
GROUP=webapps # the group to run as
NUM_WORKERS=3 # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=hello.settings # which settings file should Django use
DJANGO_WSGI_MODULE=hello.wsgi # WSGI module name
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source ../bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR
# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--user=$USER --group=$GROUP \
--bind=unix:$SOCKFILE \
--log-level=debug \
--log-file=-
Set the executable bit on the gunicorn_start script:
$ sudo chmod u+x bin/gunicorn_start
You can test your gunicorn_start script by running it as the user hello.
$ sudo su - hello
hello@django:~$ bin/gunicorn_start
Starting hello_app as hello
2013-06-09 14:21:45 [10724] [INFO] Starting gunicorn 18.0
2013-06-09 14:21:45 [10724] [DEBUG] Arbiter booted
2013-06-09 14:21:45 [10724] [INFO] Listening at: unix:/webapps/hello_django/run/gunicorn.sock (10724)
2013-06-09 14:21:45 [10724] [INFO] Using worker: sync
2013-06-09 14:21:45 [10735] [INFO] Booting worker with pid: 10735
2013-06-09 14:21:45 [10736] [INFO] Booting worker with pid: 10736
2013-06-09 14:21:45 [10737] [INFO] Booting worker with pid: 10737

^C (CONTROL-C to kill Gunicorn)

2013-06-09 14:21:48 [10736] [INFO] Worker exiting (pid: 10736)
2013-06-09 14:21:48 [10735] [INFO] Worker exiting (pid: 10735)
2013-06-09 14:21:48 [10724] [INFO] Handling signal: int
2013-06-09 14:21:48 [10737] [INFO] Worker exiting (pid: 10737)
2013-06-09 14:21:48 [10724] [INFO] Shutting down: Master
$ exit
Note the parameters set in gunicorn_start. You’ll need to set the paths and filenames to match your setup.
As a rule-of-thumb set the --workers (NUM_WORKERS) according to the following formula: 2 * CPUs + 1. The idea being, that at any given time half of your workers will be busy doing I/O. For a single CPU machine it would give you 3.
The --name (NAME) argument specifies how your application will identify itself in programs such as top or ps. It defaults to gunicorn, which might make it harder to distinguish from other apps if you have multiple Gunicorn-powered applications running on the same server.
In order for the --name argument to have an effect you need to install a Python module called setproctitle. To build this native extension pip needs to have access to C header files for Python. You can add them to your system with the python-dev package and then install setproctitle.
$ sudo aptitude install python-dev
(hello_django)hello@django:~$ pip install setproctitle
Now when you list processes, you should see which gunicorn belongs to which application.
$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
(...)
hello    11588  0.7  0.2  58400 11568 ?        S    14:52   0:00 gunicorn: master [hello_app]
hello    11602  0.5  0.3  66584 16040 ?        S    14:52   0:00 gunicorn: worker [hello_app]
hello    11603  0.5  0.3  66592 16044 ?        S    14:52   0:00 gunicorn: worker [hello_app]
hello    11604  0.5  0.3  66604 16052 ?        S    14:52   0:00 gunicorn: worker [hello_app]

Starting and monitoring with Supervisor

Your gunicorn_start script should now be ready and working. We need to make sure that it starts automatically with the system and that it can automatically restart if for some reason it exits unexpectedly. These tasks can easily be handled by a service called supervisord. Installation is simple:
$ sudo aptitude install supervisor
When Supervisor is installed you can give it programs to start and watch by creating configuration files in the /etc/supervisor/conf.d directory. For our hello application we’ll create a file named /etc/supervisor/conf.d/hello.conf with this content:
[program:hello]
command = /webapps/hello_django/bin/gunicorn_start ; Command to start app
user = hello ; User to run as
stdout_logfile = /webapps/hello_django/logs/gunicorn_supervisor.log ; Where to write log messages
redirect_stderr = true ; Save stderr in the same log
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding
view rawhello.confhosted with ❤ by GitHub
You can set many other options, but this basic configuration should suffice.
Create the file to store your application’s log messages:
hello@django:~$ mkdir -p /webapps/hello_django/logs/
hello@django:~$ touch /webapps/hello_django/logs/gunicorn_supervisor.log 
After you save the configuration file for your program you can ask supervisor to reread configuration files and update (which will start your the newly registered app).
$ sudo supervisorctl reread
hello: available
$ sudo supervisorctl update
hello: added process group
You can also check the status of your app or start, stop or restart it using supervisor.
$ sudo supervisorctl status hello                       
hello                            RUNNING    pid 18020, uptime 0:00:50
$ sudo supervisorctl stop hello  
hello: stopped
$ sudo supervisorctl start hello                        
hello: started
$ sudo supervisorctl restart hello 
hello: stopped
hello: started
Your application should now be automatically started after a system reboot and automatically restarted if it ever crashed for some reason.

Nginx

Time to set up Nginx as a server for out application and its static files. Install and start Nginx:
$ sudo aptitude install nginx
$ sudo service nginx start
You can navigate to your server (http://example.com) with your browser and Nginx should greet you with the words “Welcome to nginx!”.

Create an Nginx virtual server configuration for Django

Each Nginx virtual server should be described by a file in the /etc/nginx/sites-availabledirectory. You select which sites you want to enable by making symbolic links to those in the /etc/nginx/sites-enabled directory.
Create a new nginx server configuration file for your Django application running on example.com in /etc/nginx/sites-available/hello. The file should contain something along the following lines. A more detailed example is available from the folks who make Gunicorn.
upstream hello_app_server {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).
server unix:/webapps/hello_django/run/gunicorn.sock fail_timeout=0;
}
server {
listen 80;
server_name example.com;
client_max_body_size 4G;
access_log /webapps/hello_django/logs/nginx-access.log;
error_log /webapps/hello_django/logs/nginx-error.log;
location /static/ {
alias /webapps/hello_django/static/;
}
location /media/ {
alias /webapps/hello_django/media/;
}
location / {
# an HTTP header important enough to have its own Wikipedia entry:
# http://en.wikipedia.org/wiki/X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if and only if you use HTTPS, this helps Rack
# set the proper protocol for doing redirects:
# proxy_set_header X-Forwarded-Proto https;
# pass the Host: header from the client right along so redirects
# can be set properly within the Rack application
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
# set "proxy_buffering off" *only* for Rainbows! when doing
# Comet/long-poll stuff. It's also safe to set if you're
# using only serving fast clients with Unicorn + nginx.
# Otherwise you _want_ nginx to buffer responses to slow
# clients, really.
# proxy_buffering off;
# Try to serve static files from nginx, no point in making an
# *application* server like Unicorn/Rainbows! serve static files.
if (!-f $request_filename) {
proxy_pass http://hello_app_server;
break;
}
}
# Error pages
error_page 500 502 503 504 /500.html;
location = /500.html {
root /webapps/hello_django/static/;
}
}
view rawhello.nginxconfhosted with ❤ by GitHub
Create a symbolic link in the sites-enabled folder:
$ sudo ln -s /etc/nginx/sites-available/hello /etc/nginx/sites-enabled/hello
Restart Nginx:
$ sudo service nginx restart 
If you navigate to your site, you should now see your Django welcome-page powered by Nginx and Gunicorn. Go ahead and develop to your heart’s content.
At this stage you may find that instead of the Django welcome-page, you encounter the default “Welcome to nginx!” page. This may be caused by the default configuration file, which is installed with Nginx and masks your new site’s configuration. If you don’t plan to use it, delete the symbolic link to this file from /etc/nginx/sites-enabled.
If you run into any problems with the above setup, please drop me a line.

Final directory structure

If you followed this tutorial, you should have created a directory structure resembling this:
/webapps/hello_django/
├── bin                          <= Directory created by virtualenv
│   ├── activate                 <= Environment activation script
│   ├── django-admin.py
│   ├── gunicorn
│   ├── gunicorn_django
│   ├── gunicorn_start           <= Script to start application with Gunicorn
│   └── python
├── hello                        <= Django project directory, add this to PYTHONPATH
│   ├── manage.py
│   ├── project_application_1
│   ├── project_application_2
│   └── hello                    <= Project settings directory
│       ├── __init__.py
│       ├── settings.py          <= hello.settings - settings module Gunicorn will use
│       ├── urls.py
│       └── wsgi.py              <= hello.wsgi - WSGI module Gunicorn will use
├── include
│   └── python2.7 -> /usr/include/python2.7
├── lib
│   └── python2.7
├── lib64 -> /webapps/hello_django/lib
├── logs                         <= Application logs directory
│   ├── gunicorn_supervisor.log
│   ├── nginx-access.log
│   └── nginx-error.log
├── media                        <= User uploaded files folder
├── run
│   └── gunicorn.sock 
└── static                       <= Collect and serve static files from here

Uninstalling the Django application

If time comes to remove the application, follow these steps.
Remove the virtual server from Nginx sites-enabled folder:
$ sudo rm /etc/nginx/sites-enabled/hello_django
Restart Nginx:
$ sudo service nginx restart 
If you never plan to use this application again, you can remove its config file also from the sites-available directory
$ sudo rm /etc/nginx/sites-available/hello_django
Stop the application with Supervisor:
$ sudo supervisorctl stop hello
Remove the application from Supervisor’s control scripts directory:
$ sudo rm /etc/supervisor/conf.d/hello.conf
If you never plan to use this application again, you can now remove its entire directory from webapps:
$ sudo rm -r /webapps/hello_django

Running multiple applications

If you would like some help with setting up a Nginx server to run multiple Django applications, check out my next article.
FROM http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/
--------------------------


Serving multiple Django applications with Nginx and Gunicorn


Nginx makes a great server for your Gunicorn-powered Django applications. In this article I will demonstrate how you can run multiple Django applications on the same Nginx server, hosting sites on two different domains. Each application will be set up in its own Virtualenv and each will be owned by and run as a different user to limit consequences of a potential security breach.

Prerequisites

This artcle is a continuation of a previous article on setting up Django with Nginx and Gunicorn. You should start by following instructions in that article and prepare a server with the following components:
  • Nginx
  • PostgreSQL
  • Virtualenv
  • Supervisor
Our goal in this article will be to create two applications, one called Hello and one called Goodbye. The former will be served under the address http://hello.test and the latter http://goodbye.test

Create a virtual environment for each app

In order to keep your apps independent, each will run in its own virtual environment. Create an environment for each application using the virtualenv command. In each environment install Django, Gunicorn, the application itself and its other dependencies. Follow steps described in my previous article for each app.
Let’s say that for our hello and goodbye applications we would create environments in /webapps/hello_django and /webapps/goodbye_django respectively. We would get a directory structure containing the following entries:
/webapps/
├── hello_django                <= virtualenv for the application Hello
│   ├── bin
│   │   ├── activate
│   │   ├── gunicorn            <= Hello app's gunicorn
│   │   ├── gunicorn_start      <= Hello app's gunicorn start script
│   │   └── python
│   ├── hello                   <= Hello app's Django project directory
│   │   └── hello
│   │       ├── settings.py     <= hello.settings
│   │       └── wsgi.py         <= hello.wsgi
│   ├── logs                    <= Hello app's logs will be saved here
│   ├── media
│   ├── run                     <= Gunicorn's socket file will be placed here
│   └── static
└── goodbye_django              <= analogous virtualenv for the application Goodbye
    ├── bin
    │   ├── activate
    │   ├── gunicorn
    │   ├── gunicorn_start
    │   └── python
    ├── goodbye
    │   └── goodbye
    │       ├── settings.py
    │       └── wsgi.py
    ├── logs
    ├── media
    ├── run
    └── static

Create system accounts for the webapps

Even though Django has a pretty good security track record, web applications can become compromised. In order to make running multiple applications safer we’ll create a separate system user account for each application. The apps will run on our system with the privileges of those special users. Even if one application became compromised, an attacker would only be able to take over the part of your system available to the hacked application.
Create system users named hello and goodbye and assign them to a system group called webapps.
$ sudo groupadd --system webapps
$ sudo useradd --system --gid webapps --home /webapps/hello_django hello 
$ sudo useradd --system --gid webapps --home /webapps/goodbye_django goodbye 
Now change the owner of files in each application’s folder. I like to assign the group users as the owner, because that allows regular users of the server to access and modify parts of the application which are group-writable. This is optional.
$ sudo chown -R hello:users /webapps/hello_django
$ sudo chown -R goodbye:users /webapps/goodbye_django

Create Gunicorn start scripts

For each application create a simple shell script based on my gunicorn_start template. The scripts differ only in the values of variables which they set.
For the Hello app, set the following values in /webapps/hello_django/bin/gunicorn_start:


/webapps/hello_django/bin/gunicorn_start
1
2
3
4
5
6
7
8
9
10
(...)
NAME="hello_app"                                  # Name of the application
DJANGODIR=/webapps/hello_django/hello             # Django project directory
SOCKFILE=/webapps/hello_django/run/gunicorn.sock  # we will communicte using this unix socket
USER=hello                                        # the user to run as
GROUP=webapps                                     # the group to run as
NUM_WORKERS=3                                     # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=hello.settings             # which settings file should Django use
DJANGO_WSGI_MODULE=hello.wsgi                     # WSGI module name
(...)

And for the Goodbye app by analogy:


/webapps/goodbye_django/bin/gunicorn_start
1
2
3
4
5
6
7
8
9
10
(...)
NAME="goodbye_app"                                  # Name of the application
DJANGODIR=/webapps/goodbye_django/goodbye           # Django project directory
SOCKFILE=/webapps/goodbye_django/run/gunicorn.sock  # we will communicte using this unix socket
USER=goodbye                                        # the user to run as
GROUP=webapps                                       # the group to run as
NUM_WORKERS=3                                       # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=goodbye.settings             # which settings file should Django use
DJANGO_WSGI_MODULE=goodbye.wsgi                     # WSGI module name
(...)

Create Supervisor configuration files and start the apps

Next, create a Supervisor configuration for each application. Add a file for each app to the /etc/supervisor/conf.d directory.
One for Hello:


/etc/supervisor/conf.d/hello.conf
1
2
3
4
5
[program:hello]
command = /webapps/hello_django/bin/gunicorn_start                    ; Command to start app
user = hello                                                          ; User to run as
stdout_logfile = /webapps/hello_django/logs/gunicorn_supervisor.log   ; Where to write log messages
redirect_stderr = true                                                ; Save stderr in the same log

And one for Goodbye:


/etc/supervisor/conf.d/goodbye.conf
1
2
3
4
5
[program:goodbye]
command = /webapps/goodbye_django/bin/gunicorn_start                    ; Command to start app
user = goodbye                                                          ; User to run as
stdout_logfile = /webapps/goodbye_django/logs/gunicorn_supervisor.log   ; Where to write log messages
redirect_stderr = true                                                  ; Save stderr in the same log

Reread the configuration files and update Supervisor to start the apps:
$ sudo supervisorctl reread
$ sudo supervisorctl update
You can also start them manually, if you prefer:
$ sudo supervisorctl start hello
$ sudo supervisorctl start goodbye

Create Nginx virtual servers

Finally we can create virtual server configurations for each app based on this template. These will be stored in /etc/nginx/sites-available and then activated by links in /etc/nginx/sites-enabled.


/etc/nginx/sites-available/hello
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
upstream hello_app_server {
  server unix:/webapps/hello_django/run/gunicorn.sock fail_timeout=0;
}

server {
    listen   80;
    server_name hello.test;

    client_max_body_size 4G;

    access_log /webapps/hello_django/logs/nginx-access.log;
    error_log /webapps/hello_django/logs/nginx-error.log;

    location /static/ {
        alias   /webapps/hello_django/static/;
    }

    location /media/ {
        alias   /webapps/hello_django/media/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://hello_app_server;
            break;
        }
    }
}
/etc/nginx/sites-available/goodbye
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
upstream goodbye_app_server {
  server unix:/webapps/goodbye_django/run/gunicorn.sock fail_timeout=0;
}

server {
    listen   80;
    server_name goodbye.test;

    client_max_body_size 4G;

    access_log /webapps/goodbye_django/logs/nginx-access.log;
    error_log /webapps/goodbye_django/logs/nginx-error.log;

    location /static/ {
        alias   /webapps/goodbye_django/static/;
    }

    location /media/ {
        alias   /webapps/goodbye_django/media/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://goodbye_app_server;
            break;
        }
    }
}

Enable the virtual servers and restart Nginx:
$ sudo ln -s /etc/nginx/sites-available/hello /etc/nginx/sites-enabled/hello
$ sudo ln -s /etc/nginx/sites-available/goodbye /etc/nginx/sites-enabled/goodbye
$ sudo service nginx restart

Test the virtual servers

Now let’s point each domain to our server for testing purposes. Making actual changes to the Domain Name System is usually among the final steps when working in production, performed after all tests are completed. For testing you can simulate the DNS changes by adding an entry to the /etc/hosts file of a computer from which you will be connecting to your server (your laptop for example).
Say you want to serve Django applications under the domains hello.test and goodbye.testfrom a server with the IP address of 10.10.10.200. You can simulate the appropriate DNS entries locally on your PC by putting the following line into your /etc/hosts file. On Windows the file is conveniently hidden in %SystemRoot%\system32\drivers\etc\hosts.


/etc/hosts
1
2
(...)
10.10.10.200    hello.test goodbye.test

You can now navigate to each domain from your PC to test that each app on the server is working correctly:
Good luck!
FROM http://michal.karzynski.pl/blog/2013/10/29/serving-multiple-django-applications-with-nginx-gunicorn-supervisor/
--------

gunicorn

gunicorn 'Green Unicorn' is a WSGI HTTP Server for UNIX, fast clients and sleepy applications.

Gunicorn

Build Status Gunicorn 'Green Unicorn' is a Python WSGI HTTP Server for UNIX. It's a pre-fork worker model ported from Ruby's Unicorn project. The Gunicorn server is broadly compatible with various web frameworks, simply implemented, light on server resource usage, and fairly speedy.
Feel free to join us in #gunicorn on Freenode.

Documentation

The documentation is hosted at http://docs.gunicorn.org.

Installation

Gunicorn requires Python 2.x >= 2.6 or Python 3.x >= 3.2.
Install from PyPI:
$ pip install gunicorn

Usage

Basic usage:
$ gunicorn [OPTIONS] APP_MODULE
Where APP_MODULE is of the pattern $(MODULE_NAME):$(VARIABLE_NAME). The module name can be a full dotted path. The variable name refers to a WSGI callable that should be found in the specified module.
Example with test app:
$ cd examples
$ gunicorn --workers=2 test:app 
 
from https://github.com/benoitc/gunicorn