Solution refined solution step by step and the actual development of common problems Summary: Based on the core details of Nginx deploy Django project in the Ubuntu

There are about Django and Nginx deployment of many online articles, most of them are chaotic, and some can not read too simple, some are too long-winded do not know what is the core of the steps, I feel those who write down their ideas. There are many details not specifically marked, how to get leads is a failure error. After painstaking exploration of one days time, to be able to step on the pit are stepped on, summed up a detailed tutorial clearer, I hope this article can help you!

 

Analysis of core concepts:

WSGI is the Web Server Gateway Interface acronym. Layer is at an angle of view, WSGI layer is lower than the location of CGI. But the difference is that WSGI CGI has a strong scalability and can run in a multithreaded environment or process, because WSGI just a standard does not define how to achieve. In fact WSGI is not CGI, because it is located between the web application and web servers, and web servers can be CGI. It can be understood as a Python built-in test web server.

uWSGI is a Web server that implements the WSGI protocol, uwsgi, http and other protocols. Nginx role in HttpUwsgiModule uWSGI is exchanged with the server. WSGI is a Web Server Gateway Interface. For example, the HTTP protocol is converted into WSGI protocol, so Python can be used directly.

Second, the project environment
OS: Ubuntu 16.04

Programming languages: Python 3.5.2

Web frameworks: Django 2.0.3

Web server: uWSGI 2.0.17

Web server: Nginx 1.10.3

Here not detailed the specific installation, Ubuntu use apt-get install particularly convenient.

sudo apt-get install python3
sudo apt-get install python3-pip
sudo apt-get install nginx



Nginx enter 127.0.0.1 successfully installed in the browser, appears "Welcome to nginx!" Represents a successful installation.

Three, uWSGI installation configuration
installation

sudo pip3 install uwsgi


Test
create test.py file

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b'Hello World']


Run the file by uWSGI

uwsgi --http :8000 --wsgi-file test.py



Enter 127.0.0.1:8000 in the browser, appears "Hello World" represents a successful installation.

Communication between four, Django uWSGI and
install Django

sudo pip3 install Django==2.0.3



Create a Django project

django-admin startproject myweb


I Django project location: / home / setup / myweb

uwsgi --http :8000 --chdir /home/setup/myweb --wsgi-file myweb/wsgi.py --master --processes 4 --threads 2 --stats 127.0.0.1:8001


Common options
http: protocol type and port number

processes: the number of open processes

workers: the number of processes open, equivalent to the processes

chdir: Specifies the run directory

wsgi-file: Loading wsgi-file

stats: at the specified address on state service

threads: running thread. Because of the GIL, I think this is really futile.

master: allow the presence of the main process

daemonize: the process runs in the background and logs hit the specified log file or udp server (daemonize uWSGI). In fact, the most commonly used, or to log output to a local file.

pidfile: specify the location of the pid file, record pid number of the primary process.

vacuum: When the server exits automatically clean up the environment, delete the unix socket file and pid file

Xiao Bian recommend a school population of 315 346 913 python learning , whether you are big or small white cow, is want to change careers or want to join can come together to learn to understand progress together! There are tools within the group, a lot of dry goods and technical information to share!

Fifth, the communication between Nginx, uWSGI, Django
Next, we want to combine all three

1. Configure Django and uWSGI
first create a profile uwsgi.ini uWSGI in the root directory of your Django project

cd myweb
touch uwsgi.ini 



At this Django project directory file structure is as follows:

MyWeb /
├── manage.py
├── MyWeb
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── the __init __. CPython-35.pyc
│ │ └── settings.cpython-35.pyc
│ ├ settings.py - the
│ ├── urls.py
│ └── wsgi.py
└── uwsgi.ini

when we create myweb project by Django, in a subdirectory myweb has helped us generate a wsgi.py file. So, we just need to create uwsgi.ini configuration file.

uwsgi supports multiple types of configuration files, such as xml, ini and so on. Here, the use of ini type of configuration.

Next, open the configuration file you just created good uwsgi.ini add the following configuration:

[uwsgi]

socket = :8888
chdir           = /home/setup/myweb
module          = myweb.wsgi
master          = true
processes       = 4
vacuum          = true



This configuration, in fact, equivalent wsgi by way of command, followed by a bunch of parameters to the documentation.

socket: port number specified for project implementation.

chdir: directory specified item.

module: module = hello.wsgi so to be understood. For uwsgi.ini document, and it has a sibling directory myweb directory, there is a wsgi.py file in this directory.

Next, read uwsgi.ini file to start the project by uwsgi command

uwsgi --ini uwsgi.ini



operation result:

setup@labideas-data:~/myweb$ uwsgi --ini uwsgi.ini
[uWSGI] getting INI configuration from uwsgi.ini
*** Starting uWSGI 2.0.17 (64bit) on [Tue Mar 20 11:11:30 2018] ***
compiled with version: 5.4.0 20160609 on 19 March 2018 09:13:12
os: Linux-4.4.0-105-generic #128-Ubuntu SMP Thu Dec 14 12:42:11 UTC 2017
nodename: labideas-data
machine: x86_64
clock source: unix
detected number of CPU cores: 4
current working directory: /home/setup/hello
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
chdir() to /home/setup/hello
your processes number limit is 64049
your memory page size is 4096 bytes
detected max file descriptor number: 65535
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address :8888 fd 3
Python version: 3.5.2 (default, Nov 23 2017, 16:37:01)  [GCC 5.4.0 20160609]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x1f73aa0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 364520 bytes (355 KB) for 4 cores
*** Operational MODE: preforking ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1f73aa0 pid: 7097 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 7097)
spawned uWSGI worker 1 (pid: 7099, cores: 1)
spawned uWSGI worker 2 (pid: 7100, cores: 1)
spawned uWSGI worker 3 (pid: 7101, cores: 1)
spawned uWSGI worker 4 (pid: 7102, cores: 1)



Note View startup information uwsgi, if there is wrong, we must check the parameters of the configuration file is set incorrectly.

2. Configure Nginx
Nginx default configuration files in / etc under / nginx directory

setup@labideas-data:/etc/nginx$ ll
total 64
drwxr-xr-x  6 root root 4096 Mar 20 09:37 ./
drwxr-xr-x 95 root root 4096 Mar 19 19:56 ../
drwxr-xr-x  2 root root 4096 Mar 19 20:13 conf.d/
-rw-r--r--  1 root root 1077 Feb 12  2017 fastcgi.conf
-rw-r--r--  1 root root 1007 Feb 12  2017 fastcgi_params
-rw-r--r--  1 root root 2837 Feb 12  2017 koi-utf
-rw-r--r--  1 root root 2223 Feb 12  2017 koi-win
-rw-r--r--  1 root root 3957 Feb 12  2017 mime.types
-rw-r--r--  1 root root 1919 Mar 20 09:33 nginx.conf
-rw-r--r--  1 root root  180 Feb 12  2017 proxy_params
-rw-r--r--  1 root root  636 Feb 12  2017 scgi_params
drwxr-xr-x  2 root root 4096 Mar 20 10:00 sites-available/
drwxr-xr-x  2 root root 4096 Mar 19 14:59 sites-enabled/
drwxr-xr-x  2 root root 4096 Mar 19 14:59 snippets/
-rw-r--r--  1 root root  664 Feb 12  2017 uwsgi_params
-rw-r--r--  1 root root 3071 Feb 12  2017 win-utf


Need to go to the next / etc / nginx / sites-available directory default configuration file (some Linux distributions configuration file is in /etc/nginx/nginx.conf, there are some other places where we prevail Ubuntu 16.04 ).

The original configuration files are backed up, and open the nginx configuration file

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak
sudo vi /etc/nginx/sites-available/default



The default port number 80 into another port number, such as 8080. Because the default port number 80 can easily be used by other applications, and we configure our own Django projects also need to use the default port.

# Django 2.0 项目部署
server {

    listen          80; 
    server_name     data.labideas.cn 
    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:8888;
        uwsgi_read_timeout 2;
    }   

    location /static {

        expires 30d;
        autoindex on; 
        add_header Cache-Control private;
        alias /home/setup/myweb/static/;
    }   
}


listen: nginx proxy is specified uwsgi external port number.

server_name: most of the information online is a web site set up (for example, www.baidu.com, if you specify a localhost or 127.0.0.1 can only be accessed locally.

So in the end it is how nginx uwsgi associate it? It now appears that probably the most important is the two-line configuration.

include uwsgi_params;
uwsgi_pass 127.0.0.1:8888;


include must be specified as uwsgi_params. It refers to the uwsgi_pass local IP and port number, and to the myweb_uwsgi.ini profile IP and port number to be consistent.

Now restart nginx

sudo /etc/init.d/nginx restart



The browser then access to 127.0.0.1

Invalid HTTP_HOST header: 'data.labideas.cn'. You may need to add 'data.labideas.cn' to ALLOWED_HOSTS.
[pid: 7924|app: 0|req: 1/1] 114.249.204.30 () {40 vars in 658 bytes} [Tue Mar 20 06:16:28 2018] GET / => generated 54903 bytes in 41 msecs (HTTP/1.1 400) 1 headers in 53 bytes (1 switches on core 0)



In the background you can see uWSGI information output. By pointing to IP and port number, the request should be the first to nginx, if you perform some requests on the page, you will see that these requests will eventually go uwsgi to deal with.

Finally, we will uWSGI configured to boot from Kai

Open the sudo vi /etc/rc.local

uwsgi --ini /home/setup/myweb/uwsgi.ini &


Add to file

Note Before you want to add to the exit 0, & indicates that the service is performed in the background.

Sixth, the problems encountered
during the configuration process, there will always encounter a variety of problems, and here I will be the most commonly used set out a few issues, I hope you can help. 1. Django startup error

setup@labideas-data:~/myweb$ python3 manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

March 20, 2018 - 06:28:52
Django version 2.0.3, using settings 'myweb.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.



Create a new project, use Django's own test server is started, the above error. This is because some of your project and default data is not migrated to the database.

Solution:

Migrate data into the database

python3 manage.py migrate


2. uwsgi start error
when starting uwsgi in startup information if you have the following error message:

!!! no internal routing support, rebuild with pcre support !!!


There is a dependence problem

Solution:

Uninstall uwsgi, pay attention to uninstall this time, pip will remain in the system cache

pip uninstall uwsgi


Install pcre dependent libraries

centos installation

sudo yum install pcre pcre-devel pcre-static


ubuntu installation

sudo apt-get install libpcre3 libpcre3-dev



Reinstall uwsgi, do not go pip cache

pip install uwsgi -I --no-cache-dir


Uwsgi start again, has no !!! no internal routing support, rebuild with an error of the pcre support !!!.

3. Port error
sometimes been to overwrite the start and uWSGI Django error may appear as follows

Error: That port is already in use



This is the port number is already in use, is servr already running, it is also possible to run in the background or you can be stopped Django However, the process of resources and port numbers are not released.

Solution:

The process to find kill off

sudo ps aux | grep uwsgi
sudo kill -9 PID


Or the simplest solution is to directly kill

sudo fuser -k 8000/tcp


Such port 8000 and related processes would have died

4. The public port security set shield
some cases, obviously feeling everything configured, also check a lot of times. Local not the slightest problem, but an on-line date of the dog, always report "server not responding" and other errors, or localhost access, but is not using the domain name or external network access, gas which in turn want to hit the computer ... It is how it goes?

Project in a formal environment on the line, it must be in the public Internet, sometimes we will choose the cloud server, here to Ali cloud server, for example, we need to open its corresponding port number.

Smart students may already be aware of why the figure above does not uwsgi.ini port number 8888 file it?

This is because the security group rules Ali port is the external cloud shield, we socket port number used for communication between Nginx and uWSGI of 8888 is included in the network environment, it unaffected.

5. formally launched mode
because we in actual development, it is necessary to use DEBUG mode, but at the time we need to close formally launched DEBUG mode.

Open Django project settings.py configuration file in

The DEBUG = True amended as DEBUG = False

will ALLOWED_HOSTS = [] modified as ALLOWED_HOSTS = [ 'data.labideas.cn'], or ALLOWED_HOSTS = [ '*']
is not recommended to use the wildcard *, you can add specific domain name!

6. Admin management interface style sheets lost
long ago, Admin test is whether the success criteria Django installation. But in a formal environment, often encounter the problem of missing stylesheet. Why is this so?

This is because Nginx formal environment, can not find a static document Django project.

Solution:

① create a static directory Django project, to place some static files

② Open the configuration file settings.py Django project

Add a row

STATIC_ROOT = '/home/setup/myweb/static/'


The STATIC_ROOT point to store static directory static files

③ copied from the resource bundle Django static files required to static directory STATIC_ROOT pointed to, which includes the necessary admin interface style sheet (style), picture (image) and script (js) and so on.

python3 manage.py collectstatic



Note that, if not the first step ①, then directly run this command would cause an error.

④ modify the configuration file Nginx

location /static {

    expires 30d;
    autoindex on; 
    add_header Cache-Control private;
    alias /home/setup/html/data/static/;
}



The alias also point static directory to store static files, needs and Django project settings.py profile STATIC_ROOT point to a directory consistent.

⑤ uWSGI and restart Nginx

# 杀掉 uwsgi.ini 进程
ps aux | grep uwsgi | grep -v grep | awk '{print $2}' | xargs kill -9
uwsgi --ini /home/setup/html/data/uwsgi.ini &

sudo /etc/init.d/nginx restart



Well, so far this tutorial has ended. Chose Django2.0 version and Python3 deployment, because from the beginning Django2.0 only support more than Python3.4 version is not backward compatible. And the next plunge into this pit students more and more, can be considered for this purpose to do something small contribution to Python and Django community.
There are confused I do not know how to learn a school friend Editor's Choice Python learning qun 315 -346- 913 can be understood with progress in learning to learn together!

Guess you like

Origin blog.csdn.net/weixin_44995023/article/details/92419527