Django + Nginx + uWSGI部署

Django + Nginx + uWSGI部署

1. Nginx/uWSGI/Django项目工作流程

项目基于 Django + Nginx + uWSGI 进行部署
项目代码路径: pro/prodec

1.1 用户通过浏览器访问发出http请求到服务器;
1.2 Nginx负责接受外部Http请求并进行解包:
若请求是静态文件则根据设置好的静态文件路径返回对应内容;
若请求是动态内容则将请求交给uWSGI服务器,uWSGI服务器收到请求后,根据wsgi协议解析并回调Django应用;
1.3 Django应用则根据请求进行数据库增删查改和模版渲染等工作,然后再逆方向返回Nginx;
1.4 Nginx将响应交付用户浏览器。

2. 环境搭建

2.1 安装Python

安装Python3.6.6
更改pip源(默认的 pip 源的速度太慢,可以更换为国内的镜像源)
安装依赖包pip install -r requirements.txt

2.2 安装uwsgi
# 安装
pip install uwsgi
# 新建test.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"] # python3
    #return ["Hello World"] # python2
# 启动
uwsgi --http :8000 --wsgi-file test.py
# 验证
http://localhost:8000
显示Hello World,证明安装成功

2.3 安装 Nginx

命令:yum -y install nginx
使用/usr/sbin/nginx 指令来启动nginx,nginx默认端口80,启动后通过访问服务器ip+端口查看出现Welcome to nginx表示启动成功

使用Nginx的最大好处之一是实现对后端uwsgi的负载均衡,这样可以提升并发量,此外Nginx对静态请求的处理能力要强过uwsgi,因此如果静态请求较多,那么可以将这部分内容用Nginx处理。

2.4 配置文件修改
uwsgi配置

在项目目录/data/dec_platform下新建uwsgi启动文件exclude_uwsgi.ini 如下:

[uwsgi]
# Django-related settings

# http = :8090
socket = 127.0.0.1:8090

# the base directory (full path)
chdir=/data/dec_platform

# Django s wsgi file
module=cloudDeC.wsgi:application

# process-related settings
# master
master          = true

# maximum number of worker processes
processes       = 4

vacuum          = true

pidfile=/tmp/uwsgi/uwsgi.pid
# 在后台运行, 信息保存的日志文件
daemonize=/tmp/uwsgi/uwsgi.log

在uwsgi配置文件中,配置http = :8090,通过命令uwsgi --http :8090 /data/dec_platform/exclude_uwsgi.ini启动uwsgi,访问ip + 端口8090,页面正常显示,证明uwsgi配置和项目运行ok;
停止uwsgi,修改配置为socket = 127.0.0.1:8090,使之与Nginx通信,通过命令
uwsgi -i /data/dec_platform/exclude_uwsgi.ini启动uwsgi

注意:
uwsgi配置文件尾行不能留空行,否则会出现问题,导致uwsgi启动失败

Nginx配置

通过命令vim /etc/nginx/nginx.conf 进入Nginx配置文件进行修改:

    #gzip  on;
    upstream django {     #自己加入的部分
        server 127.0.0.1:8090;    #端口8090必须和uwsgi配置文件中的socket端口一样
   }

    server {
        listen      8088 default_server;

        root        /pro/prodec;    #项目路径

        # Load configuration files for the default server block.

        location / {

            include uwsgi_params;

            uwsgi_pass django;

            alias /pro/prodec/frontend/dist/;
            index index.html;
    }
        location /static/ {    #加入静态文件路径,包括css文件,image文件和js文件

                autoindex on;

                alias /pro/prodec/frontend/dist/static/;

        }

修改配置文件,配置文件中自己添加部分的端口8090必须和uwsgi配置文件中的socket端口保持一致,这样就可以直接将所有访问Nginx 8088端口的url转给uwsgi处理

注意:
还需要修改Nginx配置文件第一行的用户权限,默认为nobody,修改指定权限用户,否则在Nginx读取本地目录时可能会出现403错误,权限问题

扫描二维码关注公众号,回复: 5774958 查看本文章
***最后***配置完成,重启Nginx和uwsgi,打开浏览器访问ip+Nginx监听端口,项目运行正常!

猜你喜欢

转载自blog.csdn.net/hng1992/article/details/86704358