Reprint Nginx+uwsgi+django

Source: Internet
Author: User

There are many ways in which Django can be deployed, and the way to adopt NGINX+UWSGI is one of the more common ones.

In this way, it is common practice to use Nginx as the server's front-end, which will receive all requests from the web and manage requests uniformly. Nginx handles all static requests themselves (this is Nginx's strength). Nginx then passes all non-static requests through Uwsgi to Django, which is processed by Django to complete a Web request.

As can be seen, the UWSGI function is similar to a bridge. Play a role as a bridge.

The strength of Linux is to do the server, so the entire deployment process below we choose to complete under Ubuntu.

First, install Nginx

Nginx is a lightweight Web server/reverse proxy server and e-mail (IMAP/POP3) proxy server that is released under a bsd-like protocol. It is characterized by the possession of less memory, concurrency is strong, in fact, nginx concurrency is actually in the same type of Web server performance better.

Nginx is also currently a very popular Web server. Using it to deploy Django, we also do a brief introduction here.

Nginx Official website: http://nginx.org/

Open Ubuntu Console (ctrl+alt+t) to use Ubuntu's warehouse installation.

[Email protected]:~$ sudo apt-get install nginx  #安装

Start Nginx:

[Email protected]:~$/etc/init.d/nginx start  #启动 [email protected]:~$/etc/init.d/nginx Stop  #关闭 [email protected]:~$/etc/init.d/nginx Restart  #重启

Modify the Nginx default port number, open the/etc/nginx/nginx.conf file, and modify the port number.

server {    listen       8088;    # Modify Port number    server_name  localhost;    #charset Koi8-r;     #access_log  logs/host.access.log  main;    Location/{        root   html;        Index  index.html index.htm;    }

Probably in the location of the file 36 line, the default 80 port number is changed to another port number, such as 8088. Because the default 80 port number is easily consumed by other applications.

Then, restart Nginx with the above command. Visit: http://127.0.0.1:8088/

  

If this occurs, the Nginx boot succeeds.

Second, installation Uwsgi

Install Uwsgi via PIP.

[Email protected]:/etc# python3-m pip Install Uwsgi

To test Uwsgi, create a test.py file:

DEF application (env, start_response):    start_response (' $ Ok ', [(' Content-type ', ' text/html ')]    return [b] Hello World "]

Run the file through Uwsgi.

[Email protected]:~/pydj$ uwsgi--http:8001--wsgi-file test.py

Next, configure Django to connect to the UWSGI. Here, assume that my Django project location is:/home/fnngj/pydj/myweb

[Email protected]:~/pydj$ uwsgi--http:8001--chdir/home/fnngj/pydj/myweb/--wsgi-file myweb/wsgi.py--master-- Processes 4--threads 2--stats 127.0.0.1:9191

Common options:

http : protocol type and port number

processes : number of open processes

workers : Number of open processes, equivalent to processes (the official website says spawn the specified numbers ofworkers/processes)

chdir : Specify Run directory (chdir to specified directory before apps loading)

wsgi-file : Loading wsgi-file (load. wsgi file)

stats : On the specified address, turn on the status service (enable the stats server on the specified)

Threads : Runs the thread. Because of the Gil's existence, I feel that this sincerity is useless. (Run each worker in prethreaded mode with the specified number of threads)

Master : Allow the main process to exist (enable master processes)

daemonize : Causes the process to run in the background and hits the log to the specified log file or UDP server (Daemonize uwsgi). In fact, the most common thing is to output the running record to a local file.

pidfile : Specifies the location of the PID file and records the PID number of the main process.

Vacuum : Automatically cleans up the environment when the server exits, removes UNIX socket files and PID files (try to remove all of the generated file/sockets)

Third, Nginx+uwsgi+django

Next, we need to combine the three. First, list the required documents for the project:

myweb/

├──manage.py

├──myweb/

│├──__init__.py

│├──settings.py

│├──urls.py

│└──wsgi.py

└──myweb_uwsgi.ini

When we created the MyWeb project through Django, the wsgi.py file that we generated under subdirectory MyWeb has been built for us. So, we just need to create the Myweb_uwsgi.ini configuration file again, of course, UWSGI supports many types of configuration files, such as Xml,ini. Here, the configuration of the INI type is used.

# Myweb_uwsgi.ini file[uwsgi]# django-related settingssocket =: 8000# The base directory (full path) chdir           =/home/fnng j/pydj/myweb# Django s Wsgi filemodule          = myweb.wsgi# process-related settings# mastermaster          = true# maximum Numbe R of worker processesprocesses       = 4# ... with appropriate permissions-may be needed# chmod-socket    = 664# clear en Vironment on exitvacuum          = True

This configuration, in fact, is equivalent to the WSGI command in the previous section, followed by a bunch of parameters, the way to file.

The socket specifies the port number of the project execution.

CHDIR Specifies the directory for the project.

Module MYWEB.WSGI, it can be understood, for the Myweb_uwsgi.ini file, with its peer has a myweb directory, this directory has a wsgi.py file.

For several other parameters, refer to the parameters in the previous section.

Next, switch to the MyWeb project directory and read the Myweb_uwsgi.ini file from the Uwsgi command to start the project.

[Email protected]:~$cd/home/fnngj/pydj/myweb/[Email protected]:~/pydj/myweb$Uwsgi--ini Myweb_uwsgi.ini [Uwsgi] Getting INI configuration from myweb_uwsgi.ini*** starting Uwsgi 2.0.12 (32bit) on [Sat 12 13:05:06 2016] * * * Compiled with version:4.8.4 on January 06:14:41os:linux-3.19.0-25-generic #26 ~14.04.1-ubuntu SMP Fri Jul 24 21:1 8:00am UTC 2015nodename:ubuntumachine:i686clock source:unixdetected number of CPUs cores:2current working directory:/hom e/fnngj/pydj/mywebdetected binary path:/USR/LOCAL/BIN/UWSGI!!! No internal routing support, rebuild and PCRE support!!! ChDir () to/home/fnngj/pydj/mywebyour processes number limit is 15962your memory page size is 4096 bytesdetected max file Descriptor Number:1024lock Engine:pthread Robust Mutexesthunder lock:disabled (can enable it with--thunder-lock) UW SGI socket 0 bound to TCP address:8000 fd 3Python version:3.4.3 (default, OCT, 20:37:06) [GCC 4.8.4]*** Python Threads support is disabled. can enable it with--enable-threads ***python main interpreter initialized at 0x8b52dc0your server socket listenBacklog is limited to connectionsyour mercy for graceful operations on workers are secondsmapped 319920 bytes (312 K B) for 4 cores*** operational mode:preforking ***wsgi app 0 (mountpoint= ") ready to 1 seconds on interpreter 0X8B52DC0 p  id:7158 (Default app) * * * UWSGI is running in multiple interpreter mode ***spawned UWSGI Master process (pid:7158) spawned  Uwsgi worker 1 (pid:7160, cores:1) spawned UWSGI worker 2 (pid:7161, cores:1) spawned UWSGI worker 3 (pid:7162, cores: 1) spawned UWSGI worker 4 (pid:7163, cores:1)

Note Check the startup information of the UWSGI, and if wrong, check that the configuration file parameters are set incorrectly.

The next thing to do is to modify the nginx.conf configuration file. Open the/etc/nginx/nginx.conf file and add the following.

... server {    listen         8099;     server_name    127.0.0.1     charset UTF-8;    Access_log      /var/log/nginx/myweb_access.log;    Error_log       /var/log/nginx/myweb_error.log;    Client_max_body_size 75M;    Location/{         include uwsgi_params;        Uwsgi_pass 127.0.0.1:8000;        Uwsgi_read_timeout 2;    }       location/static {        expires 30d;        AutoIndex on;         Add_header Cache-control Private;        alias/home/fnngj/pydj/myweb/static/;     } }......

Listen Specifies the port number of the Nginx proxy Uwsgi external.

  server_name Online Most of the information is set up a URL (example, www.example.com), I here if set to a URL is not accessible, so, specified to the native default IP.

I have a problem that I can't figure out at the time of configuration. How the Nginx UWSGI to produce the association. Now it seems that the most important is the two-line configuration.

Include Uwsgi_params;

Uwsgi_pass 127.0.0.1:8000;

The include must be specified as Uwsgi_params, while Uwsgi_pass refers to the port of the native IP and must always be in the Myweb_uwsgi.ini configuration file.

Now restart Nginx and look at the above command to restart Nginx. Then, visit: http://127.0.0.1:8099/

Through this IP and port number point, the request should be first to nginx. If you make some requests on the page, you will see that these requests will eventually go to Uwsgi to process.

  

=============

PS: This process should not be complicated, before spending two days not to fix, simply put on one side, this time it took two days to calculate the fix. Online search of the article is chaotic, some too simple to understand, and some too wordy do not know the core of a few steps is what, I hope this article can help you.

Reprint Nginx+uwsgi+django

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.