Nginx+uWSGI运作流程
- wsgi是一种实现python解析的通用接口标准/协议,是一种通用的接口标准或者接口协议,实现了python web程序与服务器之间交互的通用性。
- uwsgi是uWSGI项目自有的协议。uWSGI是一种python web server或称为Server/Gateway,实现了uwsgi和WSGI两种协议的Web服务器,负责响应python 的web请求。
- apache、nginx等都没有解析动态语言的功能,而是分派给其他模块来做。Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换。
运作流程
- 客户端(如浏览器)向服务器发送请求
- nginx作为直接对外的服务接口,会解析接收到的来自客户端的HTTP请求
- 如果是静态文件请求就根据nginx配置的静态文件目录,返回请求的资源;如果是动态的请求,nginx就通过配置文件,将请求传递给uWSGI
- uWSGI 将接收到的包进行处理,并转发给wsgi
- wsgi根据请求调用django工程的某个文件或函数,处理完后django将返回值交给wsgi,
wsgi将返回值进行打包,转发给uWSGI - uWSGI接收后转发给nginx,nginx最终将返回值返回给客户端。
Nginx是一个反向代理服务器
- 正向代理,例如FQ用的代理服务器就是正向代理,浏览器主动请求代理服务器,代理服 务器转发请求到对应的目标服务器
- 反向代理,部署在Web服务器上,代理所有外部网络对内部网络的访问。浏览器访问服务器,必须经过这个代理,是被动的。
- 正向代理的主动方是客户端,反向代理的主动方是Web服务器。
Nginx安装与配置
ubuntu16.04下安装
sudo apt install nginx
配置文件
# the upstream component nginx needs to connect to
upstream django {
# server unix:///path/to/your/mysite/mysite.sock; # for a file socket
server 127.0.0.1:8000; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name 127.0.0.1; # substitute your machine's IP address or FQDN
charset utf-8;
access_log /home/spzhu/py_projects/GMOOC/access_log;
error_log /home/spzhu/py_projects/GMOOC/error_log;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias /home/spzhu/py_projects/GMOOC/gmooc/media; # 指向django的media目录
}
location /static {
alias /home/spzhu/py_projects/GMOOC/gmooc/static; # 指向django的static目录
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include uwsgi_params; # the uwsgi_params file you installed
}
}
设置符号链接将配置文件链接到/etc/nginx/site-enabled/uc_nginx.conf
ln -s /home/spzhu/py_projects/GMOOC/uc_nginx.conf /etc/nginx/site-enabled/uc_nginx.conf
重新加载nginx配置,或停止,重启nginx服务
sudo nginx -s reload
sudo service nginx stop
sudo service nginx restart
静态文件如果存在文件所有权的问题,需要更改nginx配置文件nginx.conf为root用户启动:user root;
uWSGI配置文件
# mysite_uwsgi.ini file
[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /home/spzhu/py_projects/GMOOC/gmooc
# Django's wsgi file
module = gmooc.wsgi
# the virtualenv (full path)
virtualenv = /home/spzhu/programs/anaconda3/envs/djangoenv
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = 127.0.0.1:8000
# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true
daemonize = %(chdir)/uwsgi/uwsgi.log
# logto = /tmp/mylog.log
# 保存uwsgi的状态
stats=%(chdir)/uwsgi/uwsgi.status
# 进程id,用于重启,停止uwsgi
pidfile=%(chdir)/uwsgi/uwsgi.pid
以配置文件启动:uwsgi –ini uwsgi/uwsgi.ini
关闭uwsgi:uwsgi –stop uwsgi/uwsgi.pid
参考:
https://www.cnblogs.com/Xjng/p/aa4dd23918359c6414d54e4b972e9081.html
https://blog.csdn.net/c465869935/article/details/53242126