How to build a Django project using uWSGI and nginx

Source: Internet
Author: User
Tags django server virtualenv
: This article describes how to use uWSGI and nginx to build a Django project. For more information about PHP tutorials, see. Preface:

Nginx and uWSGI are good options for deploying Django, but they are not unique. they can be replaced. please try other methods.

Brief introduction to background knowledge:

1. WSGI is a Web Server Gateway Interface. It is a specification for communication between Web servers (such as nginx) and application servers (such as uWSGI servers.

2. uWSGI implements WSGI, uwsgi, http, and other protocols.

3. Nginx is a high-performance HTTP and reverse proxy server (we use Nginx because it can efficiently process static file requests)

4. Django is an open-source Web application framework that adopts the MVC design model.

5. socket is used to implement inter-process communication. here we use it to implement communication between nginx and uWSGI.

After a rough introduction of the components we need to use, we will describe the construction steps (please take a look carefully and try to do it right once)

The final work we want to accomplish is basically like this:

Client (web request) -- Server (nginx used here) -- socket (automatically generated communication file) -- uwsgi -- Django

Many of the following content comes 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 pip package management tool to install uWSGI:

sudo pip install uwsgi

If you do not have pip, install it:

In Debian and Ubuntu systems:

sudo apt-get install python-pip
In Fedora and CentOS systems:
sudo yum install python-pip
During pip uwsgi installation, if the following error occurs:

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('200 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 and port 8000 to load our test file. If everything is normal, access:

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

You will see the familiar and cute Hello World. This means that we have connected the client-uWSGI-Python.

Replace test. py with your Django project

First, make sure that our project can run normally, enter your project directory on the terminal, and then enter:

python manage.py runserver 0.0.0.0:8000
If it works properly, stop it and run the following code to change nidegongchenming to your project name:

uwsgi --http :8000 --module nidegongchenming.wsgi
Module *. wsgi indicates loading the wsgi module. please rest assured that you already have this module.

Now let's get through the client-uWSGI-Django bridge. congratulations.

If your Django project is abc, I suggest you copy all its contents to/var/www. Then, the manage. py file of your project is in/var/www/abc/, which can avoid some problems that cannot provide services due to file permissions.

Now we can stop the service. let's continue.

Nginx installation and basic configuration:

Install 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 normal (the default port 80 is not occupied), visit 127.0.0.1 in the browser and you will see "Welcome to nginx on XXX"

Now our bridge becomes: client-server (nginx)

It doesn't matter if the port is occupied by Apache or anything else and the nginx service cannot be started successfully. next we will introduce how to configure nginx to listen to other ports.

Configure nginx

First, we need a uwsgi_params file, which is usually in your nginx Directory, for example, in/etc/nginx/. of course, if it is not found, you can also

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 with no suffix. Put it in your Django project, in the same directory as manage. py. Configure nginx and tell it to reference the uwsgi_params file.

Go to 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/mysite/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 will be served on    listen      8000;    # the domain name it will 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/static; # your Django project's static files - amend as required    }    # Finally, send all non-media requests to the Django server.    location / {        uwsgi_pass  django;        include     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed    }}
I keep comments in the English document for the content in this file, which is more detailed and may be of some unexpected help to you.

Server_name in server {} can be connected to an IP address, for example, server_name 219.242.174.48. use your local IP address for testing. after completing the test, you can use other machines in the same network segment for testing.

This configuration file tells nginx to create media and static file services from the file system, and also process requests in Django applications. For large-scale deployment, it is good to let one server process static/media files and the other process Django applications. But now, we can do this.

Then run the following command to let nginx know that there is such a configuration file:

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

Deploy static files

Before running nginx, you must collect all Django static files into a static folder. First, write the following in settings. py:

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

Then run

python manage.py collectstatic

Basic nginx testing

Restart the 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 the service for accessing media files, find an image such as "abc.png" and put it in the media directory of your Django project, for example,/var/www/project/media. Then access http: // 127.0.0.1: 8000/media/abc.png. if there is a problem, stop nginx (change restart to stop in the preceding command) and then start nginx. In this way, we can get some prompts to find out where the problem is.

Communication between nginx, uWSGI, and test. py

uwsgi --socket :8001 --wsgi-file test.py
Nginx has been set to communicate with uWSGI at Port 8001, and external services are deployed at port 8000. access: http: // 127.0.0.1: 8000/

If we can see the Hell World, it means that the bridge we connect is:

Client (browser) -- Server (nginx) -- socket -- uWSGI -- python

You can also access http: // 127.0.0.1: 8001/to check the uWSGI response ......

Now we are all using TCP port socket, which will be easier at the beginning, but in fact it will be better to use Unix sockets with a lower overhead.

Edit The nginx configuration file mysite_nginx.conf and 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,

Stop the uWSGI service and run the following command to restart it:

uwsgi --socket mysite.sock --wsgi-file test.py
The mysite. sock file is automatically created for communication. you can use it as a temporary file. You can change the file name if you do not like it. Use your browser to access port 8000 again and check the result.

If the service fails to run properly, check the nginx error log at/var/log/nginx/error. log. If the error log is like this:

connect() to unix:///path/to/your/mysite/mysite.sock failed (13: Permissiondenied)
You may need to change the socket permission so that nginx can use it.

Try:

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, or vice versa. In this way, nginx should have the permission to access the socket file.

The exciting time is coming.

Now we can try to use uwsgi and nginx to run our Django application.

Run in the project directory:

uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=664
Note that mysite. wsgi should be changed to your project name.

Now you should be able to see your project in the browser.

Use the INI file to configure uWSGI

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-related settings# mastermaster          = true# maximum number of worker processesprocesses       = 10# the socket (use the full path to be safesocket          = /path/to/your/project/mysite.sock# ... with appropriate permissions - may be needed# chmod-socket    = 664# clear environment on exitvacuum          = true
If virtualenv is used, the home location cannot be commented out.

You can run uswgi later:

uwsgi --ini mysite_uwsgi.ini
We can also enable uWSGI to run in the "God" mode, set automatic start upon startup, limit maximum access, and configure the project file size.

Have dinner

These content I may write in the next blog, want to first understand the students 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 comprehensive and important that there are no spelling mistakes.







Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

The above describes how to use uWSGI and nginx to build the Django project, including some content, and hope to be helpful to friends who are interested in the PHP Tutorial.

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.