配置web服务器
一,基本逻辑
nginx官网
http://nginx.org/en/
nginx有关uwsgi模块介绍
http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html
nginx、WSGI、uwsgi、uWSGI、django这几个关系梳理一下。
wsgi 全称web server gateway interface,wsgi不是服务器,也不是python模块,只是一种协议,描述web server如何和web application通信的规则。
运行在wsgi上的web框架有bottle,flask,django
uwsgi 和wsgi一样是通信协议,是uWSGI服务器的单独协议,用于定义传输信息的类型
uWSGI 是一个web服务器,实现了WSGI协议,uwsgi协议。a
nginx web服务器,更加安全,更好的处理处理静态资源,缓存功能,负载均衡,因此nginx的强劲性能,配合uWSGI服务器会更加安全,性能有保障。
django 高级的python web框架,用于快速开发,解决web开发的大部分麻烦,程序员可以更专注业务逻辑,无须重新造轮子
逻辑图

web服务器
传统的c/s架构,请求的过程是 客户端 > 服务器 服务器 > 客户端 服务器就是:1.接收请求 2.处理请求 3.返回响应
web框架层
HTTP的动态数据交给web框架,例如django遵循MTV模式处理请求。 HTTp协议使用url定位资源,urls.py将路由请求交给views视图处理,然后返回一个结果,完成一次请求。 web框架使用者只需要处理业务的逻辑即可。
如果将一次通信转化为“对话”的过程
Nginx:hello wsgi,我刚收到一个请求,你准备下然后让django来处理吧
WSGI:好的nginx,我马上设置环境变量,然后把请求交给django
Django:谢谢WSGI,我处理完请求马上给你响应结果
WSGI:好的,我在等着
Django:搞定啦,麻烦wsgi吧响应结果传递给nginx
WSGI:太棒了,nginx,响应结果请收好,已经按照要求传递给你了
nginx:好滴。我把响应交给用户。合作愉快
二,Django+uwsgi 安装配置
在前面的章节中我们使用 python manage.py runserver 来运行服务器。这只适用测试环境中使用。
正式发布的服务,需要一个可以稳定而持续的服务器。
1,基础开发环境配置
提前安装好python3环境
https://www.cnblogs.com/glh-ty/p/9948881.html
virtualenv
https://www.cnblogs.com/glh-ty/p/9948943.html
安装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,即运行一个py文件
#启动一个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程序,即django项目等
在启动命令后面加上参数 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,添加如下配置:
touch /etc/uwsgi_nginx.ini [uwsgi] #使用nginx连接时服务器时使用 socket=0.0.0.0:8989 #不用nginx直接当做web服务器使用 #http=0.0.0.0:9000 #项目目录绝对路径 chdir=/root/Envs/django15/mysite15 #wsgi文件路径,在项目底下 wsgi-file=mysite15/wsgi.py #指定解释器目录 home=/root/Envs/django15 processes=4 threads=2 master=True pidfile=uwsgi.pid
然后指定配置文件启动命令
uwsgi --ini /etc/uwsgi_nginx.ini
三,Django+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 / { 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; } } }
加上负载均衡池的配置
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #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; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; # #负载均衡池:好多台服务器上跑着同一个项目,nginx可以在这里做负载均衡,把请求分发到不同的服务器上去 upstream crm { server 0.0.0.0:8989 weight=10; # server 0.0.0.0:9000 weight=8; } server { listen 80; server_name www.djangocrm.com; #charset koi8-r; #access_log logs/host.access.log main; location / { include /opt/nginx1-12/conf/uwsgi_params; # nginx配置下conf里面的uwsgi_params uwsgi_pass crm; } # error_page 404 /404.html; # 404页面 # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } location /static { # 静态文件的配置 alias /opt/all_crm_static; } } server { listen 80; server_name www.myjd.com; location /{ root /opt/static; index index.html index.htm; } error_page 404 /404.html; } }
然后启动项目
先启动nginx,要是启动了需要重载一下
/opt/nginx1-12/sbin/nginx 启动 /opt/nginx1-12/sbin/nginx -s reload 热重载 uwsgi --socket :8080 --module my_site.wsgi
django静态文件的配置
不配置静态文件,直接去访问,会发现admin以及自己写的静态文件丢失,页面没有样式。需要配置
首先,django项目的settings.py的配置
TATIC_ROOT=' /opt/all_crm_static' # 指定这个路径就会 把所有的静态文件收集到linux下的该目录下
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等部署的时候更方便
收集完毕之后,一定要在nginx.conf中配置好静态文件
location /static { # 静态文件的配置
alias /opt/all_crm_static;
}
}
配置好之后记得重载nginx.conf:
/opt/nginx1-12/sbin/nginx -s reload 热重载
三,supervisor
supervisor 是基于 python 的任务管理工具,用来自动运行各种后台任务,当然你也能直接利用 nohup 命令使任务自动后台运行,但如果要重启任务,每次都自己手动 kill 掉任务进程,这样很繁琐,而且一旦程序错误导致进程退出的话,系统也无法自动重载任务。
配置基于virtualenv的supervisor
由于supervisor在python3下无法使用,因此只能用python2去下载!
#注意此时已经退出虚拟环境了!!!!!
yum install python-setuptools
easy_install supervisor
通过命令生成supervisor的配支文件
echo_supervisord_conf > /etc/supervisord.conf
然后再/etc/supervisord.conf末尾添加上如下代码!
[program:crm] # 该任务名称 也叫项目名称 command=/root/Envs/django_venv/bin/uwsgi --ini /etc/uwsgi.ini # 命令就是我们手动启动项目时的命令,只是变为了绝对路径 ,让supervisor帮你管理项目的开启,停止等
supervisor的配置详细:
[supervisord] http_port=/var/tmp/supervisor.sock ; (default is to run a UNIX domain socket server) ;http_port=127.0.0.1:9001 ; (alternately, ip_address:port specifies AF_INET) ;sockchmod=0700 ; AF_UNIX socketmode (AF_INET ignore, default 0700) ;sockchown=nobody.nogroup ; AF_UNIX socket uid.gid owner (AF_INET ignores) ;umask=022 ; (process file creation umask;default 022) logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB) logfile_backups=10 ; (num of main logfile rotation backups;default 10) loglevel=info ; (logging level;default info; others: debug,warn) pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) nodaemon=false ; (start in foreground if true;default false) minfds=1024 ; (min. avail startup file descriptors;default 1024) minprocs=200 ; (min. avail process descriptors;default 200) ;nocleanup=true ; (don't clean up tempfiles at start;default false) ;http_username=user ; (default is no username (open system)) ;http_password=123 ; (default is no password (open system)) ;childlogdir=/tmp ; ('AUTO' child log dir, default $TEMP) ;user=chrism ; (default is current user, required if root) ;directory=/tmp ; (default is not to cd during start) ;environment=KEY=value ; (key value pairs to add to environment) [supervisorctl] serverurl=unix:///var/tmp/supervisor.sock ; use a unix:// URL for a unix socket ;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket ;username=chris ; should be same as http_username if set ;password=123 ; should be same as http_password if set ;prompt=mysupervisor ; cmd line prompt (default "supervisor") ; The below sample program section shows all possible program subsection values, ; create one or more 'real' program: sections to be able to control them under ; supervisor. ;[program:theprogramname] ;command=/bin/cat ; the program (relative uses PATH, can take args) ;priority=999 ; the relative start priority (default 999) ;autostart=true ; start at supervisord start (default: true) ;autorestart=true ; retstart at unexpected quit (default: true) ;startsecs=10 ; number of secs prog must stay running (def. 10) ;startretries=3 ; max # of serial start failures (default 3) ;exitcodes=0,2 ; 'expected' exit codes for process (default 0,2) ;stopsignal=QUIT ; signal used to kill process (default TERM) ;stopwaitsecs=10 ; max num secs to wait before SIGKILL (default 10) ;user=chrism ; setuid to this UNIX account to run the program ;log_stdout=true ; if true, log program stdout (default true) ;log_stderr=true ; if true, log program stderr (def false) ;logfile=/var/log/cat.log ; child log path, use NONE for none; default AUTO ;logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB) ;logfile_backups=10 ; # of logfile backups (default 10) [program:oldboy] command=/usr/local/bin/uwsgi /data/oldboy/oldboy.ini ;命令 priority=999 ; 优先级(越小越优先) autostart=true ; supervisord启动时,该程序也启动 autorestart=true ; 异常退出时,自动启动 startsecs=10 ; 启动后持续10s后未发生异常,才表示启动成功 startretries=3 ; 异常后,自动重启次数 exitcodes=0,2 ; exit异常抛出的是0、2时才认为是异常 stopsignal=QUIT ; 杀进程的信号 stopwaitsecs=10 ; 向进程发出stopsignal后等待OS向supervisord返回SIGCHILD 的时间。若超时则supervisord将使用SIGKILL杀进程 user=chrism ; 设置启动该程序的用户 log_stdout=true ; 如果为True,则记录程序日志 log_stderr=false ; 如果为True,则记录程序错误日志 logfile=/var/log/cat.log ; 程序日志路径 logfile_maxbytes=1MB ; 日志文件最大大小 logfile_backups=10 ; 日志文件最大数量 配置详细
启动supervosr,管理uwsgi
supervisord -c /etc/supervisord.conf #指定配置文件启动supervisor supervisorctl 进入交互模式 通过start crm # crm就是那个配置文件的项目名称 stop crm 管理项目

一、添加好配置文件后 二、更新新的配置到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都不会自动重启。

浙公网安备 33010602011771号