天天看点

用 docker-compose 搭建 Etcd 集群

Etcd 高可以的分布式 key-value 系统,是 CoreOS 团队发起的一个开源项目(Go语言实现的),简单直接的应用就是配置中心

etcd 和 ZooKeeper/Consul 非常相似,都提供了类似的功能,以及 REST API 的访问操作,具有以下特点:

简单:安装和使用简单,提供了 REST API 进行操作交互
安全:支持 HTTPS SSL 证书
快速:支持并发 10 k/s 的读写操作
可靠:采用 raft 算法,实现分布式系统数据的可用性和一致性
           

拉取镜像:

docker pull quay.io/coreos/etcd
           

​​​​​​​​​​​​​​​​​​​​​​​​​​

用 docker-compose 搭建 Etcd 集群

编写 etcd.yml 文件:

version: '2'
networks:
  byfn:

services:
  etcd1:
    image: quay.io/coreos/etcd
    container_name: etcd1
    command: etcd -name etcd1 -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379 -listen-peer-urls http://0.0.0.0:2380 -initial-cluster-token etcd-cluster -initial-cluster "etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380" -initial-cluster-state new
    ports:
      - 2379
      - 2380
    networks:
      - byfn
 
  etcd2:
    image: quay.io/coreos/etcd
    container_name: etcd2
    command: etcd -name etcd2 -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379 -listen-peer-urls http://0.0.0.0:2380 -initial-cluster-token etcd-cluster -initial-cluster "etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380" -initial-cluster-state new
    ports:
      - 2379
      - 2380
    networks:
      - byfn
  
  etcd3:
    image: quay.io/coreos/etcd
    container_name: etcd3
    command: etcd -name etcd3 -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379 -listen-peer-urls http://0.0.0.0:2380 -initial-cluster-token etcd-cluster -initial-cluster "etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380" -initial-cluster-state new
    ports:
      - 2379
      - 2380
    networks:
      - byfn
           

参数介绍:

  • data-dir 指定节点的数据存储目录,这些数据包括节点ID,集群ID,集群初始化配置,Snapshot文件,若未指定—wal-dir,还会存储WAL文件;
  • wal-dir 指定节点的was文件的存储目录,若指定了该参数,wal文件会和其他数据文件分开存储。
  • name 节点名称
  • initial-advertise-peer-urls 告知集群其他节点url.
  • listen-peer-urls 监听URL,用于与其他节点通讯
  • advertise-client-urls 告知客户端url, 也就是服务的url
  • initial-cluster-token 集群的ID
  • initial-cluster 集群中所有节点
  • initial-cluster-state 监听客户端状态
  • listen-client-urls 监听客户端地址
  • initial-cluster-state new 初始化集群 为新节点

启动服务:

docker-compose -f etcd.yml up
           
用 docker-compose 搭建 Etcd 集群

验证 3 节点返回的数据:

用 docker-compose 搭建 Etcd 集群

测试节点 1 新增数据,节点 2 获取:

curl -L http://127.0.0.1:32771/v2/keys/etcd -XPUT -d value="Hello etcd1"
curl -L http://127.0.0.1:32773/v2/keys/etc
curl -L http://127.0.0.1:32769/v2/keys/etc
           
用 docker-compose 搭建 Etcd 集群

文档地址:https://etcd.io/docs/v3.3.12/

demo示例:https://etcd.io/docs/v3.3.12/demo/

go客户端示例:https://dreambo8563.github.io/2018/09/14/Etcd-%E5%88%86%E5%B8%83%E5%BC%8F%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83/