nginx负载均衡配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.****.net/chengyi_L/article/details/82221490

原理:nginx通过它本身的反向代理功能将用户的请求转发到我们预先定义的集群(upstream),集群通过预先定义的规则将请求转发到下属服务器

1.找到nginx.conf  在http块中定义名为mygroup的upstream
2.在server块中配置反向代理到我们定义的upstream

3.重启nginx,负载均衡配置完成(就是这么简单!)

 

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;

    upstream myGroup{
        server 192.168.0.1:80;
        server 192.168.0.2:80;
    }

    server {
        listen 80;
        server_name *.your.domain;
        location / {
                proxy_pass http://myGroup;
                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
    }

    #gzip  on;

    #include /etc/nginx/conf.d/*.conf;
}

4.其他

upstream配置可以定义负载均衡策略。如果不填则默认随机轮询

另外还有加权轮询,下图这两个个后端服务器被访问的比率是8:5

 upstream myGroup{
        server 192.168.0.1:80  weight=8;
        server 192.168.0.2:80  weight=5;
    }

和ip_hash(根据ip的hash规则选择机器)能保证单个ip每次都访问同样的机器

 upstream myGroup{
        ip_hash;
        server 192.168.0.1:80;
        server 192.168.0.2:80;
    }

 

上一篇:一次服务器环境搭建的记录(nginx+php+subversion)


下一篇:windows服务器重启后 apache自动启动