Nginx + Django + uWSGI detailed analysis server deployment

Based on: Ali cloud CentOS 7.4.1708 , Python 3.6.1 , Django 2.0.2 , uWSGI 2.0.15 , Nginx 1.12.2

First, a brief introduction
know how prior to deployment, we must first figure out why? Why use Django + uWSGI + Nginx? So the more we need to know what is?
To clarify a few concepts, pay attention to case distinctions.

  1. WSGI - full name Python Web Server Gateway Interface, namely Pythonserver gateway interface
    for Pythonlanguage definition of Webservers and Webapplications or Websimple and universal application framework between an interface
    WSGIis just a communication protocol more detailed information, please see Wikipedia. WSGI.
    Popular point I did not want to write Python programs spend a lot of time to process the TCPconnection, HTTPrequest and response, and so on,
    so he took them all into a unified interface (ie WSGI). then by specialized Web server (uWSGI等)and Web application framework ( Djangoto achieve, etc.) .
    not only reduces the development threshold but also saves time.
  2. uWSGI - uWSGIis a realization of the WSGIagreement of the Web server, uWSGIprocessing the HTTPresponse analysis or the like, and turn into WSGIthe agreement, so we write Webapplications or Web application framework can process the information passed to it uwsgi -.
    uwsgiis to achieve WSGIagreement own internal server protocol, which defines the type of information transmission,
    for implementing a WSGIdata communication protocol of the server of the other network servers.

After understanding the basic concepts, you know why Django+uWSGI. Djangois Pythonthe Webapplication framework, he helped us do a lot of basic work, so developers can concentrate on writing business code while uWSGIachieving a WSGIprotocol Webserver, only the combination of both together, Pythonthe application can play a role.
theoretically, with this set, you can be deployed to the server to use. and we would also like to add Nginxa reason, of course, because Nginxyou can do some uWSGIfailed to do, or to things better.
Nginxis a design for HTTP server performance, compared to Apachehaving possession of less memory, high stability advantages can be used as 反向代理,a load balancer and HTTPcache, so using Nginxone of the biggest reason is the performance issue. If only a small site, there will be a lot of traffic, of course, uWSGImeet the requirements, but in case you need high concurrency Nginx, and and Nginxcompared to Apachea great high concurrency advantages.
in addition, Nginxcan bring better security and you can 直接处理静态内容, without going through uWSGI, so uWSGIconcentrate on dealing with dynamic content, which improves performance even more. Nginxcontent can be accessed Nginx, epoll, about Nginx.
summarize the respective mandates and works: Nginxreceives a client Request, if the request is returned directly to static content static content, dynamic content if the request is, to put forward the request to uWSGI, uWSGIconnected Djangoto ourPythonProcedures for processing.

Know Django, uWSGI, NginxWhat are they, and why should know Django+uWSGI+Nginxlater, it can be a deployment server.

Second, the project deployment

  1. In server deployment Python 3.6andDjango 2.0.2

  2. Ali cloud server connection in Mac terminal input $ SSH [email protected],
    rootthe user name xxx.cnis the domain name or IP address of the server

  3. Install Nginx

    # yum install epel-release
    # yum install python-devel nginx
    
  4. Use pip install uwsgi >>> pip3 install uwsgi --upgrade

  5. UWSGI and Nginx configuration files and configuration directly on the project root directory

    Because the configuration file is required only once during the deployment, directly in the server configuration would be more appropriate. Of course, you can also create a new folder corresponding configuration file in the local project file and write configuration. But note the path in the configuration file are server end of the path.

    uWSGI profile uwsgi.ini. For more information, please see uWSGI Configuration.

    [uwsgi]
    #使用HTTP访问的端口号, 使用这个端口号是直接访问了uWSGI, 绕过了Nginx
    http = :8010
    #与外界连接的端口号, Nginx通过这个端口转发给uWSGI
    socket = 127.0.0.1:8001
    #是否使用主线程
    master = true
    # 项目在服务器中的目录(绝对路径)
    chdir = /project_dir/
    # Django's wsgi 文件目录
    wsgi-file = project_name/wsgi.py
    # 最大进程数
    processes = 4
    #每个进程的线程数
    threads = 2
    #状态监听端口
    stats = 127.0.0.1:9191
    # 退出时自动清理环境配置
    vacuum = true
    #目录下文件改动时自动重启
    touch-reload = /project_dir
    #Python文件改动时自动重启
    #py-auto-reload = 1
    #后台运行并把日志存到.log文件
    daemonize = /project_dir/uWSGI.log
    
  6. NginxIt requires two configuration files. uwsgi_paramsFiles and project_name.conffile

    1, uwsgi_params file directly in Nginxthe gitwarehouse can be downloaded.
    2, project_name.conf modify configuration files by copying nginx.conf and first looks nginx.conf file location:

    # nginx -t
    

    It will print out something like:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    

    3, the new project_name.conffile, copy nginx.confall the files to the information project_name.conf. And replace the serverpart.

    server {
    #把nginx.conf这一部分内容替换掉
    ...
    }
    

    After the file is replaced by:

    # For more information on configuration, see:
    #   * Official English Documentation: http://nginx.org/en/docs/
    #   * Official Russian Documentation: http://nginx.org/ru/docs/
    
    user  nginx;
    worker_processes  auto;
    error_log /var/log/nginx/error.log;
    pid /run/nginx.pid;
    
    # Load dynamic modules. See /usr/share/nginx/README.dynamic.
    include /usr/share/nginx/modules/*.conf;
    
    events {
        worker_connections  1024;
    }
    
    http {
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
        ¦   ¦   ¦   ¦   ¦ '$status $body_bytes_sent "$http_referer" '
        ¦   ¦   ¦   ¦   ¦ '"$http_user_agent" "$http_x_forwarded_for"';
    
        access_log  /var/log/nginx/access.log  main;
    
        sendfile            on;
        tcp_nopush          on;
        tcp_nodelay         on;
        keepalive_timeout   65;
        types_hash_max_size 2048;
    
        include             /etc/nginx/mime.types;
        default_type        application/octet-stream;
    
        # Load modular configuration files from the /etc/nginx/conf.d directory.
        # See http://nginx.org/en/docs/ngx_core_module.html#include
        # for more information.
        include /etc/nginx/conf.d/*.conf;
    
    
        #下面的部分是替换之后的配置
        # the upstream component nginx needs to connect to
        upstream django {
            # 连接到Django的端口号, 和uwsgi.ini文件中端口一致. 127.0.0.1说明只允许本地转发
            server 127.0.0.1:8001; # for a web port socket (we'll use this first)
        }
    
        # configuration of the server
        server {
            # 端口号, 客户端通过这个端口连接到Nginx
            listen      80;
            # 服务器地址
            server_name pefami.cn; # substitute your machine's IP address or FQDN
            # 编码
            charset     utf-8;
    
            #日志文件在服务器中的路径
            access_log      /project_dir/nginx_access.log;
            error_log       /project_dir/nginx_error.log;
    
            # 上传文件最大体积限制
            client_max_body_size 75M;   # adjust to taste
    
            # Django media文件路径
            location /media  {
                alias /project_dir/media;  # your Django project's media files - amend as                         required
            }
            # Django 静态文件路径
            location /static {
                alias /project_dir/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     /project_dir/uwsgi_params; # the uwsgi_params file you installed
            }
        }
    
    }
    
  7. After configured the configuration file, the entire project uploaded to the server the next as long as the server is running. uWSGIAnd Nginxon it there is a need to pay attention to this:
    open the corresponding port in Ali cloud server, such as used in the configuration of the upper 8001and 80port otherwise. the client can not connect to the server.

  8. start upuWSGI

     # uwsgi --ini uwsgi.ini
    

    Also does not require configuration files directly start uWSGI, then you need to configure uwsgi.ini file as follows:

    # uwsgi --http :8001 --chdir /project_dir/project_name --home=/path/to/env --module project_name.wsgi
    

    Wherein --homethe specified virtualenvpath can be removed if not.

  9. Start Nginx

    # nginx -c /project_dir/static/project_name.conf
    
  10. After the startup is complete you can check the status of network ports

       # netstat -nltp
    

    Normally next time a similar print the following information is displayed uwsgi and nginx are in service of.

       Active Internet connections (only servers)
       Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
       tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      18977/./src/redis-s 
       tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      4752/nginx: master  
       tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1117/sshd           
       tcp        0      0 127.0.0.1:32000         0.0.0.0:*               LISTEN      969/java            
       tcp        0      0 127.0.0.1:8001          0.0.0.0:*               LISTEN      8989/uwsgi          
       tcp        0      0 127.0.0.1:9191          0.0.0.0:*               LISTEN      8989/uwsgi          
       tcp        0      0 0.0.0.0:8010            0.0.0.0:*               LISTEN      8989/uwsgi          
       tcp6       0      0 :::3306                 :::*                    LISTEN      1145/mysqld 
    
  11. Here, the whole process of the deployment is complete.

  12. In addition, after the modified files, Nginx need to restart:

       # nginx -s reload
    

Author: KenZhangCn
link: https://www.jianshu.com/p/a13307242ca3
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin blog.csdn.net/qq_41433183/article/details/90733244