• Linux nginx+uWSGI+django+virtualenv+supervisor发布web服务器


    用Nginx+uwsgi原因

    首先nginx 是对外的服务接口,外部浏览器通过url访问nginx,
    
    2nginx 接收到浏览器发送过来的http请求,将包进行解析,分析url,如果是静态文件请求就直接访问用户给nginx配置的静态文件目录,直接返回用户请求的静态文件,
    
    如果不是静态文件,而是一个动态的请求,那么nginx就将请求转发给uwsgi,uwsgi 接收到请求之后将包进行处理,处理成wsgi可以接受的格式,并发给wsgi,wsgi 根据请求调用应用程序的某个文件,某个文件的某个函数,最后处理完将返回值再次交给wsgi,wsgi将返回值进行打包,打包成uwsgi能够接收的格式,uwsgi接收wsgi 发送的请求,并转发给nginx,nginx最终将返回值返回给浏览器。
    
    3要知道第一级的nginx并不是必须的,uwsgi完全可以完成整个的和浏览器交互的流程,但是要考虑到某些情况
    安全问题,程序不能直接被浏览器访问到,而是通过nginx,nginx只开放某个接口,uwsgi本身是内网接口,这样运维人员在nginx上加上安全性的限制,可以达到保护程序的作用。
    
    2负载均衡问题,一个uwsgi很可能不够用,即使开了多个work也是不行,毕竟一台机器的cpu和内存都是有限的,有了nginx做代理,一个nginx可以代理多台uwsgi完成uwsgi的负载均衡。
    
    3静态文件问题,用django或是uwsgi这种东西来负责静态文件的处理是很浪费的行为,而且他们本身对文件的处理也不如nginx好,所以整个静态文件的处理都直接由nginx完成,静态文件的访问完全不去经过uwsgi以及其后面的东西。
    
    为什么要用nginx,uwsgi
    View Code

    基础开发环境配置

    yum groupinstall "Development tools"
    yum install zlib-devel bzip2-devel pcre-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel

    python3 + virtualenv安装

    安装django1.11

    pip3 install django==1.11
    #创建django项目mysite
    django-admin startproject mysite
    #创建app01
    python3 manage.py startapp app01

    mysite/settings.py

    #settings.py设置
    ALLOWED_HOSTS = ['*']
    install app01

    mysite/urls.py

    from app01 import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^hello_django/', views.hello),
    ]

    app01/views.py

    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    def hello(request):
        print('request is :',request)
        return HttpResponse('django is ok ')

    安装uWSGI

    进入虚拟环境venv,安装uwsgi
    (venv) [root@slave 192.168.11.64 /opt]$pip3 install uwsgi
    检查uwsgi版本
    (venv) [root@slave 192.168.11.64 /opt]$uwsgi --version
    2.0.17.1
    #检查uwsgi python版本
    uwsgi --python-version

    运行简单的uWSGI

    #启动一个python
    uwsgi --http :8000 --wsgi-file test.py
    http :8000: 使用http协议,端口8000
    wsgi-file test.py: 加载指定的文件,test.py
    #test.py
    def application(env, start_response):
        start_response('200 OK', [('Content-Type','text/html')])
        return [b"Hello World"] # python3

    uWsgi热加载python程序

    在启动命令后面加上参数
    uwsgi --http :8088 --module mysite.wsgi --py-autoreload=1 
    #发布命令
    command= /home/venv/bin/uwsgi --uwsgi 0.0.0.0:8000 --chdir /opt/mysite --home=/home/venv --module mysite.wsgi
    #此时修改django代码,uWSGI会自动加载django程序,页面生效

    运行django程序

    #mysite/wsgi.py  确保找到这个文件
    uwsgi --http :8000 --module mysite.wsgi
    module mysite.wsgi: 加载指定的wsgi模块

    uwsgi配置文件

    uwsgi支持ini、xml等多种配置方式,本文以 ini 为例, 在/etc/目录下新建uwsgi_nginx.ini,添加如下配置:
    
    # mysite_uwsgi.ini file
    [uwsgi]
    
    # Django-related settings
    # the base directory (full path)
    chdir           = /opt/mysite
    # Django's wsgi file
    module          = mysite.wsgi
    # the virtualenv (full path)
    home            = /opt/venv
    # process-related settings
    # master
    master          = true
    # maximum number of worker processes
    processes       = 1
    # the socket (use the full path to be safe
    socket          = 0.0.0.0:8000
    # ... with appropriate permissions - may be needed
    # chmod-socket    = 664
    # clear environment on exit
    vacuum          = true
    
    uwsgi.ini

    指定配置文件启动命令

    uwsgi --ini  /etc/uwsgi_nginx.ini

    配置nginx结合uWSGI

    配置nginx.conf

    worker_processes  1;
    error_log  logs/error.log;
    pid        logs/nginx.pid;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        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  logs/access.log  main;
        sendfile        on;
        keepalive_timeout  65;
      #nginx反向代理uwsgi
        server {
            listen       80;
            server_name  192.168.11.64;
            location / {
          #nginx自带ngx_http_uwsgi_module模块,起到nginx和uwsgi交互作用
             #通过uwsgi_pass设置服务器地址和协议,讲动态请求转发给uwsgi处理
             include  /opt/nginx1-12/conf/uwsgi_params;
             uwsgi_pass 0.0.0.0:8000;
                root   html;
                index  index.html index.htm;
            }
          #nginx处理静态页面资源
          location /static{
            alias /opt/nginx1-12/static;   
             }
         #nginx处理媒体资源
         location /media{
            alias /opt/nginx1-12/media;  
             }
            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                root   html;
            }
        }
    }

    supervisor

    supervisor 是基于 python 的任务管理工具,用来自动运行各种后台任务,如果要重启任务,每次都自己手动 kill 掉任务进程,这样很繁琐,而且一旦程序错误导致进程退出的话,系统也无法自动重载任务。

    由于supervisor在python3下无法使用,因此只能用python2去下载!

    #注意此时已经退出虚拟环境了!
    yum install python-setuptools
    easy_install supervisor

    通过命令生成supervisor的配支文件

    echo_supervisord_conf > /etc/supervisord.conf

    然后再/etc/supervisord.conf末尾添加上如下代码

    supervisord.conf配置文件参数解释
    [program:xx]是被管理的进程配置参数,xx是进程的名称
    [program:xx]
    command=/opt/apache-tomcat-8.0.35/bin/catalina.sh run  ; 程序启动命令
    autostart=true       ; 在supervisord启动的时候也自动启动
    startsecs=10         ; 启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒
    autorestart=true     ; 程序退出后自动重启,可选值:[unexpected,true,false],默认为unexpected,表示进程意外杀死后才重启
    startretries=3       ; 启动失败自动重试次数,默认是3
    user=tomcat          ; 用哪个用户启动进程,默认是root
    priority=999         ; 进程启动优先级,默认999,值小的优先启动
    redirect_stderr=true ; 把stderr重定向到stdout,默认false
    stdout_logfile_maxbytes=20MB  ; stdout 日志文件大小,默认50MB
    stdout_logfile_backups = 20   ; stdout 日志文件备份数,默认是10
    ; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
    stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out
    stopasgroup=false     ;默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程
    killasgroup=false     ;默认为false,向进程组发送kill信号,包括子进程
    [program:my]
    #command=/opt/venv/bin/uwsgi --ini  /etc/uwsgi_nginx.ini  #这里是结合virtualenv的命令 和supervisor的精髓!!!!
    command= /home/venv/bin/uwsgi --uwsgi 0.0.0.0:8000 --chdir /opt/mysite --home=/home/venv --module mysite.wsgi
    #--home指的是虚拟环境目录  --module找到 mysite/wsgi.py   

    最后启动supervisor,完成uWSGI启动django,nginx反向代理

    supervisord -c /etc/supervisord.conf #启动supervisor
    supervisorctl -c /etxc/supervisord.conf restart my  #重启my项目
    supervisorctl -c 
    /etc/supervisord
    .conf [start|stop|restart] [program-name|all]

    重新加载supervisor

    一、添加好配置文件后
    
    二、更新新的配置到supervisord    
    
    supervisorctl update
    三、重新启动配置中的所有程序
    
    supervisorctl reload
    四、启动某个进程(program_name=你配置中写的程序名称)
    
    supervisorctl start program_name
    五、查看正在守候的进程
    
    supervisorctl
    六、停止某一进程 (program_name=你配置中写的程序名称)
    
    pervisorctl stop program_name
    七、重启某一进程 (program_name=你配置中写的程序名称)
    
    supervisorctl restart program_name
    八、停止全部进程
    
    supervisorctl stop all
    注意:显示用stop停止掉的进程,用reload或者update都不会自动重启。

    django的静态文件与nginx配置

    mysite/settings.py

    STATIC_ROOT='/opt/nginx1-12/static'
    STATIC_URL = '/static/'
    STATICFILES_DIRS=[
        os.path.join(BASE_DIR,"static"),
    ]

    参数STATIC_ROOT作用

    通过python3 manage.py collectstatic 收集所有你使用的静态文件保存到STATIC_ROOT!

    STATIC_ROOT 文件夹 是用来将所有STATICFILES_DIRS中所有文件夹中的文件,以及各app中static中的文件都复制过来
    # 把这些文件放到一起是为了用nginx等部署的时候更方便
  • 相关阅读:
    redis的主从复制,读写分离,主从切换
    webpack 教程资源收集
    webpack进阶之插件篇
    Mysql与Redis的同步实践
    通过Gearman实现MySQL到Redis的数据同步
    LVS+MYCAT读写分离+MYSQL同步部署手册(第三版)
    Keepalived+Redis高可用部署(第二版)
    Keepalived+Redis高可用部署
    LVS+Redis部署手册
    知识就是力量(笔记记录)
  • 原文地址:https://www.cnblogs.com/NachoLau/p/10457478.html
Copyright © 2020-2023  润新知