Configure load balance using Nginx 1.8 on CentOS 6.7

本教程使用Vultr的VPS搭建,准备三台VPS,一主两从

master - 45.32.90.100
slave1  - 45.32.92.47
slave2  - 45.32.89.205

1、安装Nginx

三台全装,并启动Nginx

/usr/local/nginx/sbin/nginx

2、修改master配置文件

在http段增加:

    upstream backend {
        server 45.32.92.47;
        server 45.32.89.205;
        }

在server的location段中加入:

            proxy_pass http://backend;

3、完整nginx.conf如下:

#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;

    upstream backend {
        server 45.32.92.47 weight=2;
        server 45.32.89.205;
        }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;

            proxy_pass http://backend;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

4、重启master上的nginx

/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload

5、验证

在slave1中修改网页文件

echo "slave1" > /usr/local/nginx/html/index.html

在slave2中修改网页文件

echo "slave2" > /usr/local/nginx/html/index.html

在浏览器中输入master的ip,刷新查看,可以看到交替出现slave1和slave2

此外,还可以设置权重

    upstream backend {
        server 45.32.92.47 weight=2;
        server 45.32.89.205 weight=1;
        }