How to use Uwsgi and Nginx to build a Django project

Source: Internet
Author: User
Tags virtualenv
Preface:

Nginx and Uwsgi are a good choice for Django deployment, but they are not unique, they are irreplaceable and welcome other attempts.

Brief introduction of Background knowledge:

1, Wsgi is a kind of Web server gateway interface. It is a specification of a Web server, such as Nginx, that communicates with an application server, such as a UWSGI server.

2, Uwsgi it realizes the Wsgi, Uwsgi, HTTP and other protocols.

3, Nginx is a high-performance HTTP and reverse proxy server (we use nginx because of its ability to handle static file requests efficiently)

4. Django is an open-source Web application framework that uses MVC design patterns.

5, socket is used to achieve inter-process communication, in which we use to implement the communication between Nginx and Uwsgi

After a rough introduction of the parts we need to use, let's specify the steps to build (please look carefully to make it right at once)

The final work we are going to do is basically this:

Client (make Web request)--the server (which is using Nginx)--socket (automatically generated communication file)--uwsgi--django

Many of the following are derived from http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html# Configuring-uwsgi-to-run-with-a-ini-file

UWSGI installation and basic configuration:

We use the PIP Package Management tool to install UWSGI:

sudo pip install Uwsgi

If you don't have a pip yet, install it:

Used in Debian and Ubuntu systems:

sudo apt-get install Python-pip
used in Fedora and CentOS systems:
sudo yum install Python-pip
During pip installation of Uwsgi, if prompted to have dependencies not installed:

Debian and Ubuntu:

Apt-get Groupinstall "Development Tools"

Apt-get Install Python-devel

Fedora and CentOS:

Yum Groupinstall "Development Tools"

Yum Install-y python-devel

Basic test

Create a test file test.py:

DEF application (env, start_response):    start_response (' OK ', [(' Content-type ', ' text/html ')]    return [" Hello World "] # python2    #return [b ' Hello World '] # Python3

Run Uwsgi

Uwsgi--http:8000--wsgi-file test.py
The code means to use the HTTP protocol, port 8000, to load our test files. If everything works, visit:

Http://127.0.0.1:8000/ (Note that the colon is the English colon)

You will see the familiar and lovely Hello world. This also means that we get through the client--uwsgi--python Bridge.

Replace test.py with your Django project.

First of all make sure that our project is functioning properly, entering your project directory at the terminal, and then typing:

Python manage.py runserver 0.0.0.0:8000
If it works, stop it and then execute the following code to change the nidegongchenming to your project name:

Uwsgi--http:8000--module Nidegongchenming.wsgi
Module *.wsgi is the meaning of loading the Wsgi module, please rest assured that this module you already have.

So now we get through the client--uwsgi--django Bridge, congratulations.

If your Django project is called ABC, I suggest you copy all of its contents to/var/www/. Then your project's manage.py file is in the/var/www/abc/, which avoids some of the problems that can be caused by file permissions that do not provide services.

Okay, we can stop the service, let's go.

Installation and basic configuration of Nginx:

Installing Nginx

Ubuntu and Debian:

sudo apt-get install Nginxsudo/etc/init.d/nginx start
Fedora and CentOS
sudo yum install Nginxsudo service Nginx start
in Fedora, service Nginx start is redirected to Systemctl start Nginx.service.

If everything is OK (the default 80 port is not occupied), then access 127.0.0.1 in the browser and you will see "Welcome to Nginx on XXX"

So now our bridge has become: client-server (Nginx)

If the port is occupied by Apache or anything else, it doesn't matter if the Nginx service does not start successfully, we will show you how to configure Nginx to listen to other ports.

Configure Nginx

First of all we need a copy of the Uwsgi_params file, this file will generally be in your Nginx directory, such as my in the/etc/nginx/, of course, if not found, you can go to https://github.com/nginx/nginx/blob/ Master/conf/uwsgi_params,copy one copy, or duplicate the content below

Uwsgi_param  query_string       $query _string;uwsgi_param  request_method     $request _method;uwsgi_param  content_type       $content _type;uwsgi_param  content_length     $content _length;uwsgi_param  Request_uri        $request _uri;uwsgi_param  path_info          $document _uri;uwsgi_param  document_root      $document _root;uwsgi_param  Server_protocol    $server _protocol;uwsgi_param  HTTPS              $https if_not_empty;uwsgi_param  remote_ ADDR        $remote _addr;uwsgi_param  remote_port        $remote _port;uwsgi_param  server_port        $ Server_port;uwsgi_param  server_name        $server _name;

The file name is uwsgi_params and has no suffix. Put it in your Django project, and manage.py the same directory. Let's configure nginx and tell it to refer to the Uwsgi_params file.

Enter your Django project directory and create a file mysite_nginx.conf, which is typed in:

# mysite_nginx.conf# The upstream component Nginx needs to connect Toupstream Django {# server unix:///path/to/your/my Site/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a Web port socket (we'll use this first)}# configuration of the serverserver {# The Port your site'll be serve    D on listen 8000; # The domain name it would serve for server_name. example.com;    # Substitute your machine ' s IP address or FQDN charset utf-8;   # max upload size client_max_body_size 75M;  # adjust to taste # Django media location/media {alias/path/to/your/mysite/media; # your Django project ' s media files-amend as required} location/static {Alias/path/to/your/mysite/stati C # Your Django project ' s static files-amend as required} # Finally, send all Non-media requests to the Django serv    Er.        Location/{Uwsgi_pass Django; Include/path/to/your/mysite/uwsgi_params; # The Uwsgi_params file you INstalled}} 
The contents of this file I keep the comments in the English document, more detailed, may have some unexpected help to you.

server{} in the server_name can receive IP address, such as: server_name 219.242.174.48, test the words with your local bar, set up after easy to use other machine in the same network segment test.

This configuration file tells Nginx to create media and static file services from the file system, and also to handle requests from the Django application. For large deployments, having one server handle static/media files, and another that handles Django applications, is a good performance. But right now, we're doing fine.

Then execute the following command to let Nginx know that there is a configuration file:

sudo ln-s mysite_nginx.conf/etc/nginx/sites-enabled/

Deploying static Files

Before running Nginx, all Django static files must be collected into a static folder, first written in settings.py:

Static_root = Os.path.join (Base_dir, "static/")

And then run

Python manage.py collectstatic

Basic Nginx Test

Restart Nginx Service

Ubuntu,debian:

Sudo/etc/init.d/nginx restart
Fedora,centos:
sudo service nginx restart or systemctl restart Nginx.service

To test whether we can provide access to media files, find a picture such as "abc.png" and put it in your Django project's media directory, such as/var/www/project/project/media. Then access the http://127.0.0.1:8000/media/abc.png, if there is a problem, you need to stop nginx (the above command restart changed to stop), and then start. So we can get some information to find out where the problem is.

Nginx's communication with Uwsgi and test.py

Uwsgi--socket:8001--wsgi-file test.py
The front nginx has been set at 8001 ports to communicate with UWSGI, while the outside services are arranged on 8000 ports, access: Http://127.0.0.1:8000/

If we can see hell world, it means that the bridge we get through becomes:

Client (browser)--Server (Nginx)--socket--uwsgi--python

At the same time you can also visit http://127.0.0.1:8001/, to see the reaction of Uwsgi, temporarily not spoiler ...

By now we're all using TCP port sockets, which can be easier to start with, but actually using UNIX sockets is better and has a smaller overhead.

Edit the Nginx configuration file we just mysite_nginx.conf, make the following changes:

Server Unix:///path/to/your/mysite/mysite.sock; # for a file socket# server 127.0.0.1:8001; # for a Web port socket (we'll use this first)
Restart Nginx,

To stop just the UWSGI service, enter the following command to turn it back on:

Uwsgi--socket mysite.sock--wsgi-file test.py
The Mysite.sock file will be created automatically, used as a communication, you can when it is a temporary file. Of course not like this file name, you can also change. Visit the 8000 port again with your browser to see the results.

If the service does not work properly, check the error log of Nginx at/var/log/nginx/error.log. If the error log looks like this:

Connect () to Unix:///path/to/your/mysite/mysite.sock failed (13:permissiondenied)
It may be necessary to change the permissions of the socket so that nginx can use it.

Try it:

Uwsgi--socket mysite.sock--wsgi-file test.py--chmod-socket=666 # (very permissive)
Or:
Uwsgi--socket mysite.sock--wsgi-file test.py--chmod-socket=664 # (more sensible)
You may also need to add the current user to the Nginx user group, and vice versa, and add Nginx to the user group of your current user. This way nginx should have access to the socket file.

It's time to get excited.

Now we can try to run our Django app with Uwsgi and Nginx.

Run in the project directory:

Uwsgi--socket mysite.sock--module mysite.wsgi--chmod-socket=664
Notice that Mysite.wsgi is going to change to your project name.

You should now be able to see your project in the browser.

Configuring Uwsgi with INI file

Create a file named ' Mysite_uwsgi.ini '

# Mysite_uwsgi.ini file[uwsgi]# django-related settings# The base directory (full path) chdir           =/path/to/your/project # Django ' s wsgi filemodule          = project.wsgi# the virtualenv (full path) # home            =/path/to/virtualenv# process-relate D settings# mastermaster          = true# Maximum number of worker processesprocesses       = 10# The socket (use the full path t o be safesocket          =/path/to/your/project/mysite.sock# ... with appropriate permissions-may be needed# chmod-socket
  = 664# Clear Environment on exitvacuum          = True
If you use the virtualenv,home position, you can't comment it out.

To run USWGI later, you can use:

Uwsgi--ini Mysite_uwsgi.ini
Further we can also allow Uwsgi to run in God mode, set boot auto-start as well as limit the maximum access to the configuration such as project file size.

To dinner.

These content I may write in the next blog, want to know first classmate please move: http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html# Configuring-uwsgi-to-run-with-a-ini-file
This document is quite comprehensive, and it is important that there is no spelling error in this case.







Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The above describes how to use Uwsgi and Nginx to build Django project, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    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.