Home Backend Development PHP Tutorial nginx+gunicorn+django

nginx+gunicorn+django

Aug 08, 2016 am 09:30 AM
app django gunicorn nbsp

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

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])
Copy after login
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
Copy after login

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;
        }
Copy after login
六、监控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
Copy after login

       

    

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to perform real-name authentication on Jingdong Mall APP How to perform real-name authentication on Jingdong Mall APP Mar 19, 2024 pm 02:31 PM

How to get real-name authentication on Jingdong Mall APP? Jingdong Mall is an online shopping platform that many friends often use. Before shopping, it is best for everyone to conduct real-name authentication so that they can enjoy complete services and get a better shopping experience. The following is the real-name authentication method for JD.com, I hope it will be helpful to netizens. 1. Install and open JD.com, and then log in to your personal account; 2. Then click [My] at the bottom of the page to enter the personal center page; 3. Then click the small [Settings] icon in the upper right corner to go to the setting function interface; 4. Select [Account and Security] to go to the account settings page; 5. Finally, click the [Real-name Authentication] option to fill in the real-name information; 6. The installation system requires you to fill in your real personal information and complete the real-name authentication

Django vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Steps and precautions for registering a Hong Kong Apple ID (enjoy the unique advantages of the Hong Kong Apple Store) Steps and precautions for registering a Hong Kong Apple ID (enjoy the unique advantages of the Hong Kong Apple Store) Sep 02, 2024 pm 03:47 PM

Apple's products and services have always been loved by users around the world. Registering a Hong Kong Apple ID will bring more convenience and privileges to users. Let’s take a look at the steps to register a Hong Kong Apple ID and what you need to pay attention to. How to register a Hong Kong Apple ID When using Apple devices, many applications and functions require using Apple ID to log in. If you want to download applications from Hong Kong or enjoy the preferential content of the Hong Kong AppStore, it is very necessary to register a Hong Kong Apple ID. This article will detail the steps on how to register a Hong Kong Apple ID and what you need to pay attention to. Steps: Select language and region: Find the "Settings" option on your Apple device and enter

Django Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to cancel the data package on China Unicom app How to cancel the data package on China Unicom How to cancel the data package on China Unicom app How to cancel the data package on China Unicom Mar 18, 2024 pm 10:10 PM

The China Unicom app can easily meet everyone's needs. It has various functions to solve your needs. If you want to handle various services, you can easily do it here. If you don't need it, you can unsubscribe in time here. It is effective. To avoid subsequent losses, many people sometimes feel that the data is not enough when using mobile phones, so they buy additional data packages. However, they don’t want it next month and want to unsubscribe immediately. Here, the editor explains We provide a method to unsubscribe, so that friends who need it can come and use it! In the China Unicom app, find the &quot;My&quot; option in the lower right corner and click on it. In the My interface, slide the My Services column and click the &quot;I have ordered&quot; option

How to upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

How to issue invoices with multipoint app How to issue invoices with multipoint app Mar 14, 2024 am 10:00 AM

As a shopping voucher, invoices are crucial to our daily lives and work. So when we usually use Duodian app for shopping, how can we easily issue invoices in Duodian app? Below, the editor of this website will bring you a detailed step-by-step guide for opening invoices on multi-point apps. Users who want to know more must not miss it. Come and follow the text to learn more! In the [Invoice Center], click [Multi-Point Supermarket/Free Shopping], select the order that needs to be invoiced on the completed order page, click Next to fill in the [Invoice Information], [Recipient Information], and click Submit after confirming that they are correct. After a few minutes, enter the receiving mailbox, open the email, click on the electronic invoice download address, and finally download and print the electronic invoice.

Blackmagic\'s pro-level video app lands on Android, but your phone probably can\'t run it Blackmagic\'s pro-level video app lands on Android, but your phone probably can\'t run it Jun 25, 2024 am 07:06 AM

Blackmagic Design has finally brought its well-praised Blackmagic Camera app to Android. The professional video camera app is free to download, and it offers complete manual controls. These controls aim to make it easier for you to take pro-level cin

See all articles