转载请注明出处:http://blog.csdn.net/l1028386804/article/details/52632011
三台CentOS虚拟机
vip:192.168.0.145
sip:192.168.0.146 192.168.0.147
192.168.0.145 做为LVS Server(LVS服务器),其中,再添加一块虚拟网卡ip地址为192.168.106.130,两个ip地址为两个不同网络段的地址,其中192.168.106.130为对外的网络,也就是能和真实PC机通信的ip,192.168.0.145作为另外两台sip虚拟机的网关;
注意:192.168.0.145为bridged连接方式,网关为192.168.0.1(和真实PC一致),192.168.106.130为NAT连接方式;
ip信息如下:
[root@liuyazhuang145 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
UUID=4f9aa259-ab85-4f26-9b54-adbd5b9d3af3
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=none
IPADDR=192.168.0.145
NETMASK=255.255.255.0
BROADCAST=192.168.0.255
GATEWAY=192.168.0.1
DNS1=114.114.114.114
DNS2=8.8.8.8
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0"
PREFIX=24
HWADDR=00:50:56:3A:D4:B5
LAST_CONNECT=1471798199
[root@liuyazhuang145 ~]#
192.168.0.146和192.168.0.147将网关设置为192.168.0.145,具体ip信息如下:
192.168.0.146 ip信息:
[root@liuyazhuang146 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
UUID=4f9aa259-ab85-4f26-9b54-adbd5b9d3af3
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=none
IPADDR=192.168.0.146
NETMASK=255.255.255.0
BROADCAST=192.168.0.255
GATEWAY=192.168.0.145
DNS1=114.114.114.114
DNS2=8.8.8.8
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0"
PREFIX=24
HWADDR=00:50:56:2B:B0:B8
LAST_CONNECT=1471798199
[root@liuyazhuang146 ~]#
192.168.0.147 ip信息
[root@liuyazhuang147 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
UUID=4f9aa259-ab85-4f26-9b54-adbd5b9d3af3
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=none
IPADDR=192.168.0.147
NETMASK=255.255.255.0
BROADCAST=192.168.0.255
GATEWAY=192.168.0.145
DNS1=114.114.114.114
DNS2=8.8.8.8
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0"
PREFIX=24
HWADDR=00:50:56:26:00:3D
LAST_CONNECT=1471798199
[root@liuyazhuang147 ~]#
首先要在vip(192.168.0.145)虚拟机上安装ipvsadm,在命令行输入如下命令即可安装:
yum -y install ipvsadm*
要想将PC机访问vip 192.168.106.130时以负载均衡的形式转发到sip(192.168.0.146和192.168.0.147)上,就要通过ipvsadm命令来设置转发规则,所以我们在vip虚拟机上创建脚本文件:lvs.sh,具体如下:
#!/bin/bash
#lvs.sh
ipvsadm -C
ipvsadm -At 192.168.106.130:80 -s rr
ipvsadm -at 192.168.106.130:80 -r 192.168.0.146:80 -m
ipvsadm -at 192.168.106.130:80 -r 192.168.0.147:80 -m
ipvsadm -L -n
要想lvs.sh脚本文件可以正常执行,则需要设置相应的权限,如下输入命令,执行成为可执行文件
chmod a+x lvs.sh
在命令行输入如下命令启动脚本
./lvs.sh
命令行输出如下命令:
[root@liuyazhuang145 ~]# ./lvs.sh
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 192.168.106.130:80 rr
-> 192.168.0.146:80 Masq 1 0 0
-> 192.168.0.147:80 Masq 1 0 0
[root@liuyazhuang145 ~]#
说明脚本执行成功
CentOS默认为非路由模式,要想将其修改为路由模式需要修改/proc/sys/net/ipv4/ip-forward文件,文件中默认的值为0,即非路由模式,这里,我们需要将其修改为1,即路由模式,具体如何修改请参见博文《CentOS之——"/proc/sys/net/ipv4/ip_forward" E667: Fsync failed解决方式》
我们在sip虚拟机上安装Nginx来部署静态网页,通过真实PC访问vip,由vip均衡的转发到sip,访问sip的静态网页来实现负载均衡,具体如何安装Nginx请参见博文《Nginx+Tomcat+Memcached负载均衡集群服务搭建》
环境部署好了,我们在PC浏览器上输入链接http://192.168.106.130效果如下:
至此,LVS Net负载均衡环境搭建完毕