Consul常用命令以及配置

Reference

CSDN:深入学习consul

segmentfault


1. dev模式启动

1
2
#直接启动localhost:8500可以看到集群信息
$ consul agent -dev

2. 配置集群启动

  • 首先创建config-dir, 编辑配置文件config.json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    "datacenter":"DC_Jay",
    "data_dir":"/Users/jay/opt/consul/data/",
    "log_level":"INFO",
    "node_name":"node1",
    "server":true,
    "ui":true,
    "bind_addr":"172.17.18.149",
    "bootstrap":true
    # "ui_dir":"/Users/user/consul/ui", 这个选项与ui参数二选一, 可以配置自己的html文件
    }
  • 编辑service配置文件
    web.json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    {
    "service": {
    "name": "web",
    "tags": [
    "rails"
    ],
    "port": 80
    }
    }

sql_service.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"service": {
"name": "sql_server",
"tags": [
"master"
],
"address": "127.0.0.1",
"port": 6379,
"checks": [
{
"http": "http://localhost:6379",
"interval": "10s"
}
]
}
}

  • 然后使用配置文件启动

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $ consul agent -config-file config.json

    # 或者同时启动所有配置的服务
    $ consul agent -config-dir conf/

    $ consul catalog services
    consul
    sql_server
    test
    test-controller
    web
  • 架构图

    图片来源于他人作品!

Diagram


3. 常用命令

这些命令既可以在server上运行, 也可以在client上面运行

  • consul members : Lists the members of a Consul cluster

    1
    2
    3
    $ consul members
    Node Address Status Type Build Protocol DC Segment
    node1 172.17.18.149:8301 alive server 1.0.1 2 dc_jay <all>
  • consul reload : 重新加载所有配置

    1
    2
    $ consul reload
    Configuration reload triggered
  • consul catalog :

    1
    2
    3
    4
    5
    6
    7
    8
    # 1. List all registered services in a datacenter
    $ consul catalog services

    # 2. List all nodes in the given datacenter
    $ consul catalog nodes

    # 3. List all known datacenters
    $ consul catalog datacenters

4. DNS API & HTTP API

这些命令既可以在server上运行, 也可以在client上面运行

与上面CLI对应, consul还提供了对应的http接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 1. consul catalog datacenters
$ curl localhost:8500/v1/catalog/datacenters
["dc_jay"]

# 2. consul catalog nodes
$ curl localhost:8500/v1/catalog/nodes | jq
[
{
"ID": "2b51df31-f63c-649e-0b43-a0f9bccda8d1",
"Node": "node1",
"Address": "172.17.18.149",
"Datacenter": "dc_jay",
"TaggedAddresses": {
"lan": "172.17.18.149",
"wan": "172.17.18.149"
},
"Meta": {
"consul-network-segment": ""
},
"CreateIndex": 5,
"ModifyIndex": 6
}
]

# 3. consul catalog services
$ curl localhost:8500/v1/catalog/services |jq
{
"consul": []
}

# 4.
$ curl localhost:8500/v1/catalog/service/service_name | jq


5. 服务注册与发现

consul提供两种服务注册方式:

  • 服务启动后自己调用consul提供的register http api, 自己注册
  • 在配置文件中定义服务的方式进行注册(这里介绍这种)
    1. 创建一个服务注册配置文件
      1
      2