Home  >  Article  >  Backend Development  >  nginx+gunicorn+django

nginx+gunicorn+django

WBOY
WBOYOriginal
2016-08-08 09:30:071527browse

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">官方地址:http://gunicorn.org/</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">                  http://docs.gunicorn.org/en/19.2/</span>

Reference address: http://www.cnblogs.com/ArtsCrafts/p/gunicorn.html

                                                                                       

WSGI What are the servers:

For example, Flask, webpy, Django, and CherryPy all come with WSGI Server. Of course, the performance is not good. The built-in web server is more for testing. When publishing online, use a high-performance wsgi server or combine it with nginx to do uwsgi.


2. Install gunicorn

~$ sudo pip install gunicorn

If you want Gunicorn to support asynchronous workers, you need to install three python packages

~$ sudo pip install greenlet

~$ sudo pip install eventlet

~$ sudo pip install gevent

Note: If the greenlet installation fails, you need to install Python headers

~$ sudo apt-get install python-dev

We can check the version of gunicorn

~$ gunicorn - -Versionn Gunicorn (Version 19.1.1)


II, the Gunicorn command uses

After successful installation of Gunicorn, you can use the following three instructions to start the Gunicorn to run WSGI Application or WSGI Frameworks.

1. gunicorn

The most basic command of Gunicorn server, which is directly used to run the most basic wsgi application.

Usage: gunicorn [OPTIONS] APP_MODULE

OPTIONS Optional parameters Configuration options for running gunicorn, which will be discussed later.

APP_MODULE specifies the wsgi application file, writing format $(MODULE_NAME):$(VARIABLE_NAME). Among them, module_name is used to specify the wsgi application file to be run, but it is a complete embellishment name.

             

For example, there is a python package gunicorn_app in the current directory myapp directory, and there is a wsgi application file test.py under the gunicorn_app package.

Then module_name can be written directly as gunicorn_app.test.

                                                                                                                                                                                                                                                The variable_name represent the name of the object (which is a WSGI callable, which can be a function) to be called in the module_name file.

According to the above example, the current directory is /home/workspace/myapp, there is a package gunicorn_app in myapp, and the test.py code is as follows:

def app(environ, start_response):
    """Simplest possible application object"""
    data = 'Hello, World!\n'
    status = '200 OK'
    response_headers = [
        ('Content-type','text/plain'),
        ('Content-Length', str(len(data)))
    ]
    start_response(status, response_headers)
    return iter([data])
We are going to run the app in test.py


gunicorn gunicorn_app.test: app

2. gunicorn_django

The guniorn_django command is used to deploy Django app to Gunicorn Server.

It is actually very simple. The principle is the same as gunicorn, except that gunicorn_django has been specially processed to make it more suitable for Django.

Basic usage: gunicorn_django [OPTIONS] [SETTINGS_PATH]

OPTIONS has been mentioned before.

SETTINGS_PATH The directory where the settings.py file in django app is located. If not written, it will be searched in the current directory by default.


                                                                           but this usage is applicable to django before 1.4. For Django 1.4 and later versions, it is strongly recommended to use the gunicorn command. N u 3. Gunicorn_Paster

This command is interested to study the official documentation.

3. Gunicorn configuration

Gunicorn reads configuration information from three different places.

The first place: read from the configuration information defined by the framework, currently only valid for the Paster framework.

The second place: defined in the command line, the configuration information defined in the command line will overwrite the value of the same parameter name defined in the framework.

The third place: Create a configuration file and write the configuration information into the file (it is a python source file, so you are just like writing python code).

View all command configuration information through gunicorn -h

You can also view more detailed information through the official documentation: http://docs.gunicorn.org/en/19.2/

As based on the myapp example above

gunicorn --workers=4 --bind=127.0.0.1:8000 myapp.gunicorn_app.test:app

The above command starts 4 workers and binds to 127.0.0.1:8000

Or you can use the configuration file as follows It is a config.py configuration file source code:

import multiprocessing

bind = "127.0.0.1:8001"
workers = multiprocessing.cpu_count() * 2 + 1

gunicorn --config=config.py myapp.gunicorn_app.test:app

4. Introduction to the gunicorn framework

     Gunicorn是基于pre-fork模型的。也就意味着有一个中心管理进程(master process)用来管理worker进程集合。Master从不知道任何关于客户端的信息。所有请求

和响应处理都是由worker进程来处理的。

     Master(管理者)

     主程序是一个简单的循环,监听各种信号以及相应的响应进程。master管理着正在运行的worker集合。

     Worker类型

     1. Sync Workers

         最基本的也是默认的worker type。

         一个同步的worker class,同一时间只能控制一个request请求。

     2. Async Workers

        异步workers的使用是基于Greenlets(通过Eventlet和Gevent)。所以使用此worker type之前一定要安装好python对应的包。

        Greenlets是python多线程协作的一个实现。

     3. Tornado Workers  

         这是一个Tornado worker class。

     

五、Gunicorn部署

       使用Gunicorn必须基于一个代理服务器。

       1. Nginx Configuration

           虽然有很多HTTP代理可以使用,但是我们还是强烈推荐Nginx。如果你选择了其他代理服务器,你需要确认,当你使用默认的Gunicorn workers时,它能够buffers slow clients。没有buffering Gunicorn将很容易受 denial of service attacks的影响。也可使用 slowloris 去核实你的代理服务器是否工作良好。

         如下是一个nginx配置文件实例(假设127.0.0.1:8888端口已经被gunicorn绑定监听):

server {
        #listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default ipv6only=on; ## listen for ipv6
        listen 80;
        client_max_body_size 4G;
        server_name www.android_stat.com

        keepalive_timeout 5;



        location / {
                try_files $uri @proxy_to_app;
        }

        location @proxy_to_app {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                proxy_pass http://127.0.0.1:8888;
        }
六、监控Gunicorn

       注意:要监控Gunicorn的时候,Gunicorn不能启动daemon模式,如果使用daemon模式会fork出一个进程,这样监控工具就没法监控这个进程。

       我在这只介绍supervisor

      1. Supervisor

          Supervisor可以用来监控进程,下面是一个简单的supervisor的配置文件:

[program:gunicorn]
command=/path/to/gunicorn main:application -c /path/to/gunicorn.conf.py
directory=/path/to/project
user=nobody
autostart=true
autorestart=true
redirect_stderr=true

       

    

以上就介绍了nginx+gunicorn+django,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn