1.准备好两台服务器,每台服务器都安装nginx和keepalived
Nginx的安装
1. 下载nginx
官网:http://nginx.org/
2. 上传并解压nginx
tar -zxvf nginx-1.8.1.tar.gz -C /usr/local/src
3. 编译nginx
#进入到nginx源码目录
cd /usr/local/src/nginx-1.8.1
#检查安装环境,并指定将来要安装的路径
./configure --prefix=/usr/local/nginx
#缺包报错 ./configure: error: C compiler cc is not found
#使用YUM安装缺少的包
yum -y install gcc pcre-devel openssl openssl-devel
#编译安装
make && make install
安装完后测试是否正常:
/usr/local/nginx/sbin/nginx
查看端口是否有ngnix进程监听
netstat -ntlp | grep 80
keepalived安装
1.下载keepalived官网:http://keepalived.org
2.将keepalived解压到/usr/local/src目录下
tar -zxvf keepalived-1.2.19.tar.gz -C /usr/local/src
3.进入到/usr/local/src/keepalived-1.2.19目录
cd /usr/local/src/keepalived-1.2.19
4.开始configure
./configure --prefix=/usr/local/keepalived
5.#编译并安装
make && make install
6. 将keepalived添加到系统服务中
拷贝执行文件
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
将init.d文件拷贝到etc下,加入开机启动项
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/keepalived
将keepalived文件拷贝到etc下
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
创建keepalived文件夹
mkdir -p /etc/keepalived
将keepalived配置文件拷贝到etc下
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf
添加可执行权限
chmod +x /etc/init.d/keepalived
##以上所有命令一次性执行:
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/keepalived
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
mkdir -p /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf
chmod +x /etc/init.d/keepalived
chkconfig --add keepalived
chkconfig keepalived on
添加keepalived到开机启动
chkconfig --add keepalived
chkconfig keepalived on
2.nginx配置负载均衡
找到nginx.conf配置文件编辑,在http这个节下面配置一个叫upstream的,后面的名字可以随意取,但是要和location下的proxy_pass http://后的保持一致
http { upstream tomcats { server 192.168.122.168:8080 weight=2;#weight表示多少个 server 192.168.122.169:8080 weight=1; }location ~ .*\.(jsp|do|action) { proxy_pass http://tomcats; #tomcats是后面的tomcat服务器组的逻辑组号 }} |
3.利用keepalived实现高可靠(HA)
1.keepalived虚拟IP,
修改配置文件: /etc/keepalived/keepalived.conf
#MASTER节点
global_defs { |
#BACKUP节点
global_defs { |
#分别启动两台机器上的keepalived
service keepalived start
测试:
杀掉master上的keepalived进程,你会发现,在slave机器上的eth0网卡多了一个ip地址
查看ip地址的命令: ip addr
实质是在抢占192.168.122.168/24配置的ip
4. 配置keepalived心跳检查
原理:
Keepalived并不跟nginx耦合,它俩完全不是一家人
但是keepalived提供一个机制:让用户自定义一个shell脚本去检测用户自己的程序,返回状态给keepalived就可以了
#MASTER节点
global_defs { |
#添加切换通知脚本
vi /usr/local/keepalived/sbin/notify.sh
#添加执行权限
chmod +x /usr/local/keepalived/sbin/notify.sh
#BACKUP节点
#在第二台机器上添加notify.sh脚本
#分别在两台机器上启动keepalived
service keepalived start
chkconfig keepalived on
最后访问虚拟ip的资源路径,如:192.168.122.60:8080/helloworld