docker-compose部署zookeeper集群

参考https://zgljl2012.com/shi-yong-docker-compose-jin-xing-zookeeper-ji-qun-da-jian/

快速建立集群

  1. 在某目录下建立docker-compose.yml,假设路径为:~/Documents/dockerProject/zk_cluster/docker-compose.yml
version: '3.1'

services:
  zoo1:
    image: zookeeper
    restart: always
    hostname: zoo1
    networks:
      - zoo-net
    ports:
      - 2181:2181
    volumes:
      - zoo1-data:/data
      - zoo1-log:/datalog
    environment:
      ZOO_MY_ID: 1
      ZOO_SERVERS: server.1=0.0.0.0:2888:3888;2181 server.2=zoo2:2888:3888;2181 server.3=zoo3:2888:3888;2181
      ZOO_4LW_COMMANDS_WHITELIST: "*"

  zoo2:
    image: zookeeper
    restart: always
    hostname: zoo2
    networks:
      - zoo-net
    ports:
      - 2182:2181
    environment:
      ZOO_MY_ID: 2
      ZOO_SERVERS: server.1=zoo1:2888:3888;2181 server.2=0.0.0.0:2888:3888;2181 server.3=zoo3:2888:3888;2181
      ZOO_4LW_COMMANDS_WHITELIST: "*"

  zoo3:
    image: zookeeper
    restart: always
    hostname: zoo3
    networks:
      - zoo-net
    ports:
      - 2183:2181
    environment:
      ZOO_MY_ID: 3
      ZOO_SERVERS: server.1=zoo1:2888:3888;2181 server.2=zoo2:2888:3888;2181 server.3=0.0.0.0:2888:3888;2181
      ZOO_4LW_COMMANDS_WHITELIST: "*"

volumes:
  zoo1-data:
    external: false
  zoo1-log:
    external: false  

networks:
  zoo-net:

然后运行

docker-compose up

可看到正常启动:



之后开启一个容器去访问之:

docker run -it --rm \
    --link zoo1:zk1 \
    --link zoo2:zk2 \
    --link zoo3:zk3 \
    --net zk_cluster_zoo-net \
    zookeeper zkCli.sh -server zk1:2181,zk2:2181,zk3:2181

注意此处zk_cluster_zoo-net的格式为{project_name}_{network_name},project_name默认为文件夹名,network_name默认为docker-compose.yml中指定的名字。docker-compose启动集群时会为其分配专门的网络,可在docker network ls中查看。

docker-compose文件解释

  • networks: 指定了网络名,最终的网络名可能为"{project_name}/{network_name}"
  • ports: {p1}:{p2} 指定将宿主机上的p1端口映射到容器的p2端口,映射关系可在docker-compose ps中查看
  • volumes: zookeeper docker hub页面提到

    This image is configured with volumes at /data and /datalog to hold the Zookeeper in-memory database snapshots and the transaction log of updates to the database, respectively.

    • 大致就是zookeeper会需要创建卷来存储/data和/datalog(实际上貌似每个容器会创造三个卷)
    • - zoo1-data:/data结合下方的zoo1-data:(换行) external: false的意思就是,将/data挂载在zoo1-data上,同时external: false将指定不一定要使用现成的卷(不存在则创建名为{project_name}_zoo1-data的卷,此处为zk_cluster_zoo1-data)(external: true意思是必须使用现成的卷)
  • environment: 这里的三个变量都可在zookeeper docker hub页面查找中查阅

意外

Opening socket connection to server Will not attempt to authenticate using SASL (unknown error)
如果出现connection refused错误,可以尝试让防火墙开启端口,或sudo ufw disable关闭防火墙,并重启

你可能感兴趣的:(docker-compose部署zookeeper集群)