CentOS上配置Nginx+uWSGI+负载均衡详解

负载均衡在服务端开发中算是一个比较重要的特性。因为Nginx除了作为常规的Web服务器外,还会被大规模的用于反向代理后端,Nginx的异步框架可以处理很大的并发请求,把这些并发请求hold住之后就可以分发给后台服务端(backend servers, 后面简称backend)来做复杂的计算、处理和响应,并且在业务量增加的时候可以方便地扩容后台服务器。

说白了就是,随着业务和用户规模的增长,仅仅一台服务器无法肩负起高并发的响应,所以需要两台以上的服务器共同分担压力,而分担压力的媒介就是万能的Nginx。  

CentOS上配置Nginx+uWSGI+负载均衡详解

首先,利用wsgi在不同的端口上起两个Django服务,比如8000和8001(不用启动nginx服务)

然后修改nginx网站配置,将原uwsgi_pass注释,改成变量绑定

server {
    listen       8000;
    server_name  localhost;

    access_log      /root/myweb_access.log;
    error_log       /root/myweb_error.log;


    client_max_body_size 75M;

    location / {
        include uwsgi_params;
        uwsgi_pass mytest;
        #uwsgi_pass 127.0.0.1:8001;
        uwsgi_param UWSGI_SCRIPT video_back.wsgi;
        uwsgi_param UWSGI_CHDIR  /root/video_back;
    }


    location /static {
        alias /root/video_back/static;
    }

    location /upload {
        alias /root/video_back/upload;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
server {
    listen       80;
    server_name  localhost;

    access_log      /root/video_vue_access.log;
    error_log       /root/video_vue_error.log;
    
    client_max_body_size 75M;


    location / {
        #include uwsgi_params;
        # uwsgi_pass 127.0.0.1:8000;
        #uwsgi_pass mytest;
        root /root/video_vue;
        index index.html;
        try_files $uri $uri/ /index.html;

    }

    location /static {
        alias /root/video_vue/static;
    }

    error_log    /root/video_vue/error.log    error;

}

然后修改主配置文件 vim /etc/nginx/nginx.conf,在http配置内添加负载均衡配置

user  root;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    upstream mytest {
    server 39.106.172.65:8000 weight=3;  #负载均衡服务器群
    server 39.97.117.229:8001 weight=7;
        }
}

然后重启服务即可: