注:本文使用docker for windows模拟构建zookeeper集群,在linux系统下,可使用同样的docker命令构建
1. 创建一个文件,名为:stack.yml,内容为:
version: '3.1'
services:
zoo1:
image: zookeeper
restart: always
hostname: zoo1
ports:
- 2181:2181
environment:
ZOO_MY_ID: 1
ZOO_SERVERS: server.1=0.0.0.0:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888
zoo2:
image: zookeeper
restart: always
hostname: zoo2
ports:
- 2182:2181
environment:
ZOO_MY_ID: 2
ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=0.0.0.0:2888:3888 server.3=zoo3:2888:3888
zoo3:
image: zookeeper
restart: always
hostname: zoo3
ports:
- 2183:2181
environment:
ZOO_MY_ID: 3
ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=0.0.0.0:2888:3888
执行命令构建:docker stack deploy -c stack.yml zookeeper
或者:docker-compose -f stack.yml up
创建完成后,发现发生错误,java.net.ConnectException: Connection refused
其实这三个容器已经创建好了,但是就是没有启动,我们输入命令单个逐个启动,就可以了
docker start zookeeper_zoo1_1
docker start zookeeper_zoo2_1
docker start zookeeper_zoo3_1
2. 在三个节点上,依次执行命令zkServer.sh status(可以看到MODE,谁是leader,谁是follower)
3. 集群测试
-
进入master,创建一个根节点
输入命令进入master:docker exec -it zookeeper_zoo3_1 zkCli.sh
创建一个根节点目录:create /project zookeeper_project
输入命令:get /project
在主机上创建成功
-
进入follower节点,查看相应目录
输入命令,进入zookeeper_zoo1_1:docker exec -it zookeeper_zoo1_1 zkCli.sh
输入命令:get /project
输入命令,进入zookeeper_zoo2_1:docker exec -it zookeeper_zoo2_1 zkCli.sh
输入命令:get /project
都成功了,说明集群也成功了
4. Zookeeper高可用测试-从节点接管主节点为新的主节点
-
进入zookeeper_zoo3_1,查看状态为leader
命令:docker exec –it zookeeper_zoo3_1 bash
zkServer.sh status
-
剩下的zoo1和zoo2都是follower节点
输入命令,关闭zoo3
Docker stop zookeeper_zoo3_1
关闭主节点后,我们再查看子节点的状态
发现zoo2变成了主节点,zoo1还是从节点
-
我们再打开zoo3节点,再查看三个节点的状态
Docker start zookeeper_zoo3_1
我们发现zoo3和zoo1为从节点,zoo2变成了主节点,从此可以看出,zookeeper集群已经成功!