天天看点

【Web集群】Nginx 负载均衡实战

硬件设备

三台虚拟机
Roel HOSTNAME IP 说明
Proxy host Node 1 192.168.74.153 Nginx代理主机
Web Server 1 Node 2 192.168.74.162 Web服务器1
Web Server 2 Node 3 192.168.74.163 Web服务器2

软件设备

软件准备      系统:CentOS7.x x86_64

软件:nginx-1.16.0-1.el7.ngx.x86_64.rpm

配置

1、配置虚拟主机(两台web服务器配置)

[[email protected] ~]# vim /etc/nginx/conf.d/vhost.conf

server {
        listen       80;
        server_name  bbs.yunjisuan.com;

        location / {
            root  /usr/share/nginx/html/bbs;
            index  index.html index.htm;
        }
}

    server {
        listen       80;
        server_name  blog.yunjisuan.com;

        location / {
            root   /usr/share/nginx/html/blog;
            index  index.html index.htm;
        }
}
           

2、准备web测试界面(两台web服务器配置)

[[email protected] ~]# mkdir -p /usr/share/nginx/html/{blog,bbs}/logs
[[email protected] ~]# echo "`hostname -I `blog test page" > /usr/share/nginx/html/blog/index.html
[[email protected] ~]# echo "`hostname -I `bbs test page" > /usr/share/nginx/html/bbs/index.html
           

3、启动Nginx服务(两台web服务器配置)

[[email protected] ~]# systemctl start nginx.service 
[[email protected] ~]# systemctl enable nginx.service 
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
           

4、配置负载均衡(代理主机配置)

[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf

    upstream bbs_pool {
        server 192.168.74.162;
        server 192.168.74.163;
        }
 
    upstream blog_pool {
        server 192.168.74.162;
        server 192.168.74.163;
        }

    server {
        listen 80;
        server_name bbs.yunjisuan.com;
        
        location / {
            proxy_pass http://bbs_pool;
        }
    }
        
    server {
        listen 80;
        server_name blog.yunjisuan.com;
        
        location / {
            proxy_pass http://blog_pool;
        }
    }
           

5、重启Nginx服务

[[email protected] ~]# systemctl start nginx
           

6、修改测试主机本地hosts文件

[[email protected] ~]# vim /etc/hosts
192.168.74.153 bbs.yunjisuan.com blog.yunjisuan.com
           

6、测试

[[email protected] ~]# for i in `seq 6`; do curl http://blog.yunjisuan.com; done
192.168.74.162 bbs test page
192.168.74.163 bbs test page
192.168.74.162 bbs test page
192.168.74.163 bbs test page
192.168.74.162 bbs test page
192.168.74.163 bbs test page