keepalived+nginx实现负载均衡

1、安装keepalived(源码编译安装)

wget https://www.keepalived.org/software/keepalived-2.3.0.tar.gz

tar -zxf keepalived-2.3.0.tar.gz

cd keepalived-2.3.0 &&  mkdir /data01/keepalived && ./configure --prefix=/data01/keepalived && make -j4 &&  make install

2、安装nginx(使用docker安装演示)

由于docker的默认镜像仓库已经关闭了,安装docker配置和编译可以看这个安装docker在线和离线方式 - dididi崩了 - 博客园 (cnblogs.com)

docker pull nginx:latest

docker run -itd --name nginx01 nginx:latest (172.17.0.5)

docker run -itd --name nginx02 nginx:latest (172.17.0.6)

进入容器的nginx静态目录页面,新加一个静态文件test.html

cat > test.html << EOF
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx01.</em></p>
</body>
</html>
EOF

3、配置keepalived

cd /data01/keepalived/etc/keepalived/

vi keepalived.conf

! Configuration File for keepalived

global_defs {
router_id huoshanyun
}

vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1

authentication {
auth_type PASS
auth_pass 1111
}

virtual_ipaddress {
192.168.0.3
}
}

virtual_server 192.168.0.3 80 {
delay_loop 6
lb_algo rr
lb_kind NAT

persistence_timeout 3

protocol TCP

real_server 172.17.0.5 80 {
weight 1
TCP_CHECK {
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}

real_server 172.17.0.6 80 {
weight 1
TCP_CHECK {
connect_timeout 3
nb_get_retry 3
delay_before_retry 3
}
}
}

启动keepalived服务,开始验证

 curl  192.168.0.3:80/test.html|grep nginx0

同时可以随机宕机节点

posted @ 2024-07-22 21:08  dididi崩了  阅读(7)  评论(0编辑  收藏  举报