当前位置: 首页 > 文档资料 > Docker 简明教程 >

8.1.2 二阶:单主机集群容器模式

优质
小牛编辑
128浏览
2023-12-01

单主机集群容器模式

单节点(主机)的zookeeper容器搭建,原理也是比较简单的,我们利用之前创建的zookeeper镜像分别创建三个容器:

Zk1

sudo docker run -d -p 21811:2181 --name=container1 \
-v  /home/zk/container1:/var/zookeeper/data \
-v  /home/zk/zoo.cfg:/var/zookeeper/conf/zoo.cfg \
-v  /home/zk/container_exec.sh:/var/zookeeper/data/container_exec.sh \
zookeeper /var/zookeeper/data/container_exec.sh

Zk2

sudo docker run -d -p 21812:2181 --name=container3 \
-v  /home/zk/container1:/var/zookeeper/data \
-v  /home/zk/zoo.cfg:/var/zookeeper/conf/zoo.cfg \
-v  /home/zk/container_exec.sh:/var/zookeeper/data/container_exec.sh \
zookeeper /var/zookeeper/data/container_exec.sh

Zk3

sudo docker run -d -p 21813:2181 --name=container3 \
-v  /home/zk/container1:/var/zookeeper/data \
-v  /home/zk/zoo.cfg:/var/zookeeper/conf/zoo.cfg \
-v  /home/zk/container_exec.sh:/var/zookeeper/data/container_exec.sh \
zookeeper /var/zookeeper/data/container_exec.sh

其中container_exec.sh负责在容器中配置zoo.cfg文件、获取myid文件内容以及启动容器操作,具体内容如下:

#获取容器ip地址,以及myid文件
CONTAINER_IP=`ip addr | grep eth0 |grep inet|cut -d/ -f1|awk '{print $2}'`
ZK_ID=`cat /var/zookeeper/data/myid`

#配置zoo.cfg文件
echo $CONTAINER_IP
echo myid=$ZK_ID
echo 'server.'$ZK_ID'='$CONTAINER_IP':2888:3888' >> /var/zookeeper/conf/zoo.cfg

#等待其他容器配置好
sleep 5

cat /var/zookeeper/conf/zoo.cfg

#前台运行
/var/zookeeper/bin/zkServer.sh start-foreground

待我们运行好了之后,我们可以看到端口映射:

# docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS                                         NAMES
b17517a0765e        zookeeper           "/var/zookeeper/data   8 seconds ago       Up 7 seconds        2888/tcp, 3888/tcp, 0.0.0.0:21813->2181/tcp   container3          
b04153b0197b        zookeeper           "/var/zookeeper/data   9 seconds ago       Up 7 seconds        2888/tcp, 3888/tcp, 0.0.0.0:21812->2181/tcp   container2          
17c260876404        zookeeper           "/var/zookeeper/data   9 seconds ago       Up 8 seconds        2888/tcp, 3888/tcp, 0.0.0.0:21811->2181/tcp   container1       

然后查看zookeper集群状态:

# telnet 0.0.0.0 21812
Trying 0.0.0.0...
Connected to 0.0.0.0.
Escape character is '^]'.
stat
Zookeeper version: 3.4.6-1569965, built on 02/20/2014 09:09 GMT
Clients:
 /172.17.42.1:57481[0](queued=0,recved=1,sent=0)

Latency min/avg/max: 0/0/0
Received: 1
Sent: 0
Connections: 1
Outstanding: 0
Zxid: 0x100000000
Mode: leader
Node count: 4
Connection closed by foreign host.

至此搭建成功