consul入门
Date: 2019/05/17 Categories: 工作 Tags: consul micro service
启动和停止
ssh node1
make bootstrap
ssh node2
make server
make MASTER=node1 join
ssh node1
make kill
make MASTER=node2 join
ui
如果使用了-ui
选项来启动server或client,
那么可以用web浏览器打开http://127.0.0.1:8500
来查看consul集群的状态.
常用命令
consul members
打印目前集群中的节点, 这个结果是eventually consistent的,要获得strong consistent view, 可以用curl localhost:8500/v1/catalog/nodes
.
添加服务
consul的服务使用json格式描述, 存放在config目录下,
比如我们要添加一个elasticsearch服务, 我们进入consul/config
, 执行
echo '{"service": {"name": "es", "tags": ["test"], "port": 9200}}' > es.json
然后执行killall -s SIGHUP consul
, 就可以看到consul service了.
查询服务和节点
dig @127.0.0.1 -p 8600 test.es.service.consul dig @127.0.0.1 -p 8600 node1.node.consul
如果要获得端口号, 可以用
dig @127.0.0.1 -p 8600 test.es.service.consul SRV
服务和check
在/consul/config
下加一个服务json
{
"service": {
"name": "es",
"tags": ["test"],
"port": 9200
},
"check": [{
"id":"es_check",
"name": "ElasticSearch Status",
"service_id": "es",
"http": "http://localhost:9200",
"interval": "10s"
}]
}
一个使用命令check的例子
{
"service": {
"name": "gremlin",
"tags": ["test"],
"port": 8182
},
"check": [{
"id":"gremlin_check",
"name": "Gremlin Status",
"service_id": "gremlin",
"shell": "/bin/sh",
"args": [
"interval": "10s"
}]
}
Multi-datacenter
每个data center之间独立, 需要先bootstrap一台机器, 成为本地集群后可以join
-wan
到另一个datacenter的cluster
connect
这个功能主要用在公有云里, 因为在同一个机房里有很多机器, 你希望自己的服务之间可以相互通信, 但不要暴露一个well known端口. consul自动为你设置一个代理, 将远端的服务端口或流量映射到本地的loopback端口, 那么所有服务实际上都在监听loopback, 之间的通信由consul sidebar proxy解决. 在私有机房这个功能似乎不是特别重要.
不使用docker部署client
某些时候机器因为内核原因无法使用docker也是可以部署consul client的, 幸好consul是用go写的.
下载consul可执行文件后执行
mkdir -p config data
consul agent -config-file config.json -config-dir=config
config.json文件:
{
"datacenter": "dc1",
"data_dir": "data",
"server": false,
"log_level": "INFO",
"retry_join": [
"9.24.17.66"
]
}
DNS缓存
consul的dns查询是不缓存的,TTL为1, 所以直接设置consul为dns服务性能很差. 我们可以用dnsmasq这样的dns cache挡在前面.
/etc/dnsmasq.conf
相关部分如下, 我们的consul监听udp端口5353,
而原先的dns配置放在/etc/resolv.conf.bak里.
resolv-file=/etc/resolv.conf.bak
server=/consul/127.0.0.1#5353
新的/etc/resolv.conf内容为
nameserver 127.0.0.1