Consul 使用手冊(感受比較全了)

使用consul

介紹

Consul包含多個組件,可是做爲一個總體,爲你的基礎設施提供服務發現和服務配置的工具.他提供如下關鍵特性:css

服務發現 Consul的客戶端可用提供一個服務,好比 api 或者mysql ,另一些客戶端可用使用Consul去發現一個指定服務的提供者.經過DNS或者HTTP應用程序可用很容易的找到他所依賴的服務.
健康檢查 Consul客戶端可用提供任意數量的健康檢查,指定一個服務(好比:webserver是否返回了200 OK 狀態碼)或者使用本地節點(好比:內存使用是否大於90%). 這個信息可由operator用來監視集羣的健康.被服務發現組件用來避免將流量發送到不健康的主機.
Key/Value存儲 應用程序可用根據本身的須要使用Consul的層級的Key/Value存儲.好比動態配置,功能標記,協調,領袖選舉等等,簡單的HTTP API讓他更易於使用.
多數據中心 Consul支持開箱即用的多數據中心.這意味着用戶不須要擔憂須要創建額外的抽象層讓業務擴展到多個區域.
Consul面向DevOps和應用開發者友好.是他適合現代的彈性的基礎設施.
consul-clusterhtml

基礎架構

Consul是一個分佈式高可用的系統. 這節將包含一些基礎,咱們忽略掉一些細節這樣你能夠快速瞭解Consul是如何工做的.若是要了解更多細節,請參考深刻的架構描述.node

每一個提供服務給Consul的階段都運行了一個Consul agent . 發現服務或者設置和獲取 key/value存儲的數據不是必須運行agent.這個agent是負責對節點自身和節點上的服務進行健康檢查的.python

Agent與一個和多個Consul Server 進行交互.Consul Server 用於存放和複製數據.server自行選舉一個領袖.雖然Consul能夠運行在一臺server , 可是建議使用3到5臺來避免失敗狀況下數據的丟失.每一個數據中心建議配置一個server集羣.mysql

你基礎設施中須要發現其餘服務的組件能夠查詢任何一個Consul 的server或者 agent.Agent會自動轉發請求到server .linux

每一個數據中運行了一個Consul server集羣.當一個跨數據中心的服務發現和配置請求建立時.本地Consul Server轉發請求到遠程的數據中心並返回結果.nginx

更多介紹查看官網點擊前往git

安裝Consul

安裝Consul,找到適合你係統的包下載他.Consul打包爲一個’Zip’文件.前往下載github

下載後解開壓縮包.拷貝Consul到你的PATH路徑中,在Unix系統中~/bin/usr/local/bin是一般的安裝目錄.根據你是想爲單個用戶安裝仍是給整個系統安裝來選擇.在Windows系統中有能夠安裝到%PATH%的路徑中.web

驗證安裝

完成安裝後,經過打開一個新終端窗口檢查consul安裝是否成功.經過執行 consul你應該看到相似下面的輸出

[root@dhcp-10-201-102-248 ~]# consul usage: consul [--version] [--help] <command> [<args>] Available commands are: agent Runs a Consul agent configtest Validate config file event Fire a new event exec Executes a command on Consul nodes force-leave Forces a member of the cluster to enter the "left" state info Provides debugging information for operators join Tell Consul agent to join cluster keygen Generates a new encryption key keyring Manages gossip layer encryption keys kv Interact with the key-value store leave Gracefully leaves the Consul cluster and shuts down lock Execute a command holding a lock maint Controls node or service maintenance mode members Lists the members of a Consul cluster monitor Stream logs from a Consul agent operator Provides cluster-level tools for Consul operators reload Triggers the agent to reload configuration files rtt Estimates network round trip time between nodes snapshot Saves, restores and inspects snapshots of Consul server state version Prints the Consul version watch Watch for changes in Consul
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

若是你獲得一個consul not be found的錯誤,你的PATH可能沒有正確設置.請返回檢查你的consul的安裝路徑是否包含在PATH中.

運行Agent

完成Consul的安裝後,必須運行agent. agent能夠運行爲serverclient模式.每一個數據中心至少必須擁有一臺server . 建議在一個集羣中有3或者5個server.部署單一的server,在出現失敗時會不可避免的形成數據丟失.

其餘的agent運行爲client模式.一個client是一個很是輕量級的進程.用於註冊服務,運行健康檢查和轉發對server的查詢.agent必須在集羣中的每一個主機上運行.

查看啓動數據中心的細節請查看這裏.

啓動 Consul Server

consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -ui-dir ./consul_ui/ -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0
  • 1

運行cosnul agent以server模式,

  • -server : 定義agent運行在server模式
  • -bootstrap-expect :在一個datacenter中指望提供的server節點數目,當該值提供的時候,consul一直等到達到指定sever數目的時候纔會引導整個集羣,該標記不能和bootstrap共用
  • -bind:該地址用來在集羣內部的通信,集羣內的全部節點到地址都必須是可達的,默認是0.0.0.0
  • -node:節點在集羣中的名稱,在一個集羣中必須是惟一的,默認是該節點的主機名
  • -ui-dir: 提供存放web ui資源的路徑,該目錄必須是可讀的
  • -rejoin:使consul忽略先前的離開,在再次啓動後仍舊嘗試加入集羣中。
  • -config-dir:配置文件目錄,裏面全部以.json結尾的文件都會被加載
  • -client:consul服務偵聽地址,這個地址提供HTTP、DNS、RPC等服務,默認是127.0.0.1因此不對外提供服務,若是你要對外提供服務改爲0.0.0.0
[root@dhcp-10-201-102-198 consul]# consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -ui-dir ./consul_ui/ -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0 ==> WARNING: Expect Mode enabled, expecting 3 servers ==> Starting Consul agent... ==> Starting Consul agent RPC... ==> Consul agent running! Version: 'v0.7.4' Node ID: '422ec677-74ef-8f29-2f22-01effeed6334' Node name: 's1' Datacenter: 'dc1' Server: true (bootstrap: false) Client Addr: 0.0.0.0 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400) Cluster Addr: 10.201.102.198 (LAN: 8301, WAN: 8302) Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false Atlas: <disabled> ==> Log data will now stream in as it occurs: 2017/03/17 18:03:08 [INFO] raft: Restored from snapshot 139-352267-1489707086023 2017/03/17 18:03:08 [INFO] raft: Initial configuration (index=6982): [{Suffrage:Voter ID:10.201.102.199:8300 Address:10.201.102.199:8300} {Suffrage:Voter ID:10.201.102.200:8300 Address:10.201.102.200:8300} {Suffrage:Voter ID:10.201.102.198:8300 Address:10.201.102.198:8300}] 2017/03/17 18:03:08 [INFO] raft: Node at 10.201.102.198:8300 [Follower] entering Follower state (Leader: "") 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1 10.201.102.198 2017/03/17 18:03:08 [INFO] serf: Attempting re-join to previously known node: s2: 10.201.102.199:8301 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1) 2017/03/17 18:03:08 [INFO] consul: Raft data found, disabling bootstrap mode 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s2 10.201.102.199 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s3 10.201.102.200 2017/03/17 18:03:08 [INFO] serf: Re-joined to previously known node: s2: 10.201.102.199:8301 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1) 2017/03/17 18:03:08 [INFO] consul: Adding LAN server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1) 2017/03/17 18:03:08 [INFO] serf: EventMemberJoin: s1.dc1 10.201.102.198 2017/03/17 18:03:08 [INFO] consul: Adding WAN server s1.dc1 (Addr: tcp/10.201.102.198:8300) (DC: dc1) 2017/03/17 18:03:08 [WARN] serf: Failed to re-join any previously known node 2017/03/17 18:03:14 [INFO] agent: Synced service 'consul' 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul01' 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul02' 2017/03/17 18:03:14 [INFO] agent: Deregistered service 'consul03'
  • 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
  • 33
  • 34

查看集羣成員
新開一個終端窗口運行consul members, 你能夠看到Consul集羣的成員.

[root@dhcp-10-201-102-198 ~]# consul members Node Address Status Type Build Protocol DC s1 10.201.102.198:8301 alive server 0.7.4 2 dc1 s2 10.201.102.199:8301 alive server 0.7.4 2 dc1 s3 10.201.102.200:8301 alive server 0.7.4 2 dc1
  • 1
  • 2
  • 3
  • 4
  • 5

啓動 Consul Client

consul agent -data-dir /tmp/consul -node=c1 -bind=10.201.102.248 -config-dir=/etc/consul.d/ -join 10.201.102.198
  • 1

運行cosnul agent以client模式,-join 加入到已有的集羣中去。

[root@dhcp-10-201-102-248 ~]# consul agent -data-dir /tmp/consul -node=c1 -bind=10.201.102.248 -config-dir=/etc/consul.d/ -join 10.201.102.198 ==> Starting Consul agent... ==> Starting Consul agent RPC... ==> Joining cluster... Join completed. Synced with 1 initial agents ==> Consul agent running! Version: 'v0.7.4' Node ID: '564dc0c7-7f4f-7402-a301-cebe7f024294' Node name: 'c1' Datacenter: 'dc1' Server: false (bootstrap: false) Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400) Cluster Addr: 10.201.102.248 (LAN: 8301, WAN: 8302) Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false Atlas: <disabled> ==> Log data will now stream in as it occurs: 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: c1 10.201.102.248 2017/03/17 15:35:16 [INFO] agent: (LAN) joining: [10.201.102.198] 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s2 10.201.102.199 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s3 10.201.102.200 2017/03/17 15:35:16 [INFO] serf: EventMemberJoin: s1 10.201.102.198 2017/03/17 15:35:16 [INFO] agent: (LAN) joined: 1 Err: <nil> 2017/03/17 15:35:16 [INFO] consul: adding server s2 (Addr: tcp/10.201.102.199:8300) (DC: dc1) 2017/03/17 15:35:16 [INFO] consul: adding server s3 (Addr: tcp/10.201.102.200:8300) (DC: dc1) 2017/03/17 15:35:16 [INFO] consul: adding server s1 (Addr: tcp/10.201.102.198:8300) (DC: dc1) 2017/03/17 15:35:16 [INFO] agent: Synced node info
  • 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

查看集羣成員
新開一個終端窗口運行consul members, 你能夠看到Consul集羣的成員.

[root@dhcp-10-201-102-248 ~]# consul members Node Address Status Type Build Protocol DC c1 10.201.102.248:8301 alive client 0.7.4 2 dc1 s1 10.201.102.198:8301 alive server 0.7.4 2 dc1 s2 10.201.102.199:8301 alive server 0.7.4 2 dc1 s3 10.201.102.200:8301 alive server 0.7.4 2 dc1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

加入集羣

[root@dhcp-10-201-102-248 ~]# consul join 10.201.102.198 Node Address Status Type Build Protocol DC c1 10.201.102.248:8301 alive client 0.7.4 2 dc1 s1 10.201.102.198:8301 alive server 0.7.4 2 dc1 s2 10.201.102.199:8301 alive server 0.7.4 2 dc1 s3 10.201.102.200:8301 alive server 0.7.4 2 dc1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

中止Agent

你可使用Ctrl-C 優雅的關閉Agent. 中斷Agent以後你能夠看到他離開了集羣並關閉.

在退出中,Consul提醒其餘集羣成員,這個節點離開了.若是你強行殺掉進程.集羣的其餘成員應該能檢測到這個節點失效了.當一個成員離開,他的服務和檢測也會從目錄中移除.當一個成員失效了,他的健康情況被簡單的標記爲危險,可是不會從目錄中移除.Consul會自動嘗試對失效的節點進行重連.容許他從某些網絡條件下恢復過來.離開的節點則不會再繼續聯繫.

此外,若是一個agent做爲一個服務器,一個優雅的離開是很重要的,能夠避免引發潛在的可用性故障影響達成一致性協議.

查看這裏瞭解添加和移除server.

更新服務

服務定義能夠經過配置文件併發送SIGHUP給agent來進行更新.這樣你可讓你在不關閉服務或者保持服務請求可用的狀況下進行更新.

consul reload
  • 1

另外 HTTP API能夠用來動態的添加,移除和修改服務.

註冊服務
搭建好conusl集羣后,用戶或者程序就能到consul中去查詢或者註冊服務。能夠經過提供服務定義文件或者調用HTTP API來註冊一個服務.

首先,爲Consul配置建立一個目錄.Consul會載入配置文件夾裏的全部配置文件.在Unix系統中一般相似 /etc/consul.d (.d 後綴意思是這個路徑包含了一組配置文件).

mkdir /etc/consul.d
  • 1

而後,咱們將編寫服務定義配置文件.假設咱們有一個名叫web的服務運行在 80端口.另外,咱們將給他設置一個標籤.這樣咱們可使用他做爲額外的查詢方式:

echo '{"service": {"name": "web", "tags": ["rails"], "port": 80}}' >/etc/consul.d/web.json
  • 1

如今重啓agent , 設置配置目錄:

$ consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0 ... [INFO] agent: Synced service 'web' ...
  • 1
  • 2
  • 3
  • 4
  • -data-dir:提供一個目錄用來存放agent的狀態,全部的agent容許都須要該目錄,該目錄必須是穩定的,系統重啓後都繼續存在
    你可能注意到了輸出了 「synced」 了 web這個服務.意思是這個agent從配置文件中載入了服務定義,而且成功註冊到服務目錄.

若是你想註冊多個服務,你應該在Consul配置目錄建立多個服務定義文件.

HTTP API註冊服務,curl命令或者postman 以PUT方式請求consul HTTP API更多細節點擊查看

curl -X PUT -d '{"Datacenter": "dc1", "Node": "c2", "Address": "10.155.0.106", "Service": {"Service": "MAC", "tags": ["lianglian", "Mac"], "Port": 22}}' http://127.0.0.1:8500/v1/catalog/register
  • 1

查詢服務

一旦agent啓動而且服務同步了.咱們能夠經過DNS或者HTTP的API來查詢服務.

DNS API
讓咱們首先使用DNS API來查詢.在DNS API中,服務的DNS名字是 NAME.service.consul. 雖然是可配置的,但默認的全部DNS名字會都在consul命名空間下.這個子域告訴Consul,咱們在查詢服務,NAME則是服務的名稱.

對於咱們上面註冊的Web服務.它的域名是 web.service.consul :

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 web.service.consul ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39468 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;web.service.consul. IN A ;; ANSWER SECTION: web.service.consul. 0 IN A 10.201.102.198 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Tue Mar 28 16:10:24 2017 ;; MSG SIZE rcvd: 52 [root@dhcp-10-201-102-198 ~]#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

如你所見,一個A記錄返回了一個可用的服務所在的節點的IP地址.A記錄只能設置爲IP地址. 有也可用使用 DNS API 來接收包含 地址和端口的 SRV記錄:

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 web.service.consul SRV ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 web.service.consul SRV ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13331 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;web.service.consul. IN SRV ;; ANSWER SECTION: web.service.consul. 0 IN SRV 1 1 80 s1.node.dc1.consul. ;; ADDITIONAL SECTION: s1.node.dc1.consul. 0 IN A 10.201.102.198 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Tue Mar 28 16:10:56 2017 ;; MSG SIZE rcvd: 84 [root@dhcp-10-201-102-198 ~]#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

SRV記錄告訴咱們 web 這個服務運行於節點dhcp-10-201-102-198 的80端口. DNS額外返回了節點的A記錄.

最後,咱們也能夠用 DNS API 經過標籤來過濾服務.基於標籤的服務查詢格式爲TAG.NAME.service.consul. 在下面的例子中,咱們請求Consul返回有 rails標籤的 web服務.咱們成功獲取了咱們註冊爲這個標籤的服務:

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 rails.web.service.consul SRV ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 rails.web.service.consul SRV ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37307 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;rails.web.service.consul. IN SRV ;; ANSWER SECTION: rails.web.service.consul. 0 IN SRV 1 1 80 s1.node.dc1.consul. ;; ADDITIONAL SECTION: s1.node.dc1.consul. 0 IN A 10.201.102.198 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Tue Mar 28 16:11:45 2017 ;; MSG SIZE rcvd: 90 [root@dhcp-10-201-102-198 ~]#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

HTTP API
除了DNS API以外,HTTP API也能夠用來進行服務查詢:

[root@dhcp-10-201-102-198 ~]# curl -s 127.0.0.1:8500/v1/catalog/service/web | python -m json.tool [ { "Address": "10.201.102.198", "CreateIndex": 492843, "ID": "422ec677-74ef-8f29-2f22-01effeed6334", "ModifyIndex": 492843, "Node": "s1", "NodeMeta": {}, "ServiceAddress": "", "ServiceEnableTagOverride": false, "ServiceID": "web", "ServiceName": "web", "ServicePort": 80, "ServiceTags": [ "rails" ], "TaggedAddresses": { "lan": "10.201.102.198", "wan": "10.201.102.198" } } ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

目錄API給出全部節點提供的服務.稍後咱們會像一般的那樣帶上健康檢查進行查詢.就像DNS內部處理的那樣.這是隻查看健康的實例的查詢方法:

[root@dhcp-10-201-102-198 ~]# curl -s 127.0.0.1:8500/v1/catalog/service/web?passing | python -m json.tool [ { "Address": "10.201.102.198", "CreateIndex": 492843, "ID": "422ec677-74ef-8f29-2f22-01effeed6334", "ModifyIndex": 492843, "Node": "s1", "NodeMeta": {}, "ServiceAddress": "", "ServiceEnableTagOverride": false, "ServiceID": "web", "ServiceName": "web", "ServicePort": 80, "ServiceTags": [ "rails" ], "TaggedAddresses": { "lan": "10.201.102.198", "wan": "10.201.102.198" } } ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

WEB管理界面

Consul同時提供了一個漂亮的功能齊全的WEB界面,開箱即用.界面能夠用來查看全部的節點,能夠查看健康檢查和他們的當前狀態.能夠讀取和設置K/V 存儲的數據.UI自動支持多數據中心.點擊前往下載

UI_Download

下載完後上傳至服務器,建議全部server角色都使用WebUI,。

consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=s1 -bind=10.201.102.198 -ui-dir ./consul_ui/ -rejoin -config-dir=/etc/consul.d/ -client 0.0.0.0
  • 1
  • -ui-dir: 提供存放web ui資源的路徑,指向該目錄必須是可讀的
  • -client:consul服務偵聽地址,這個地址提供HTTP、DNS、RPC等服務,默認是127.0.0.1因此不對外提供服務,若是你要對外提供服務改爲0.0.0.0
    可經過http://10.201.102.198:8500訪問WEB管理界面。

UI_Download

健康檢查

咱們如今看到Consul運行時如此簡單.添加節點和服務,查詢節點和服務.在這一節.咱們將繼續添加健康檢查到節點和服務.健康檢查是服務發現的關鍵組件.預防使用到不健康的服務.

這一步創建在前一節的Consul集羣建立之上.目前你應該有一個包含多個節點的Consul集羣.

自定義檢查
和服務註冊相似,一個檢查能夠經過檢查定義或HTTP API請求來註冊.

咱們將使用和檢查定義來註冊檢查.和服務相似,由於這是創建檢查最經常使用的方式.

在第二個節點的配置目錄創建定義文件:

/etc/consul.d/web.json
  • 1
{"service": { "name": "Faceid", "tags": ["extract", "verify", "compare", "idcard"], "address": "10.201.102.198", "port": 9000, "check": { "name": "ping", "script": "curl -s localhost:9000", "interval": "3s" } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

or

/etc/consul.d/web.json
  • 1
{"service": { "name": "Faceid", "tags": ["extract", "verify", "compare", "idcard"], "address": "10.201.102.199", "port": 9000, "check": { "id": "api", "name": "HTTP API on port 9000", "http": "http://localhost:9000", "interval": "10s", "timeout": "1s" } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

more

檢查健康狀態

咱們能適應HTTP API來檢查他們.首先咱們檢查有哪些失敗的檢查.使用這個命令(注意:這個命令能夠運行在任何節點)

[root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/health/state/critical | python -m json.tool [ { "CheckID": "service:Faceid", "CreateIndex": 493398, "ModifyIndex": 493846, "Name": "Service 'Faceid' check", "Node": "s1", "Notes": "", "Output": "", "ServiceID": "Faceid", "ServiceName": "Faceid", "Status": "critical" } ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

咱們能夠看到,只有一個檢查咱們的web服務在critical狀態

另外,咱們能夠嘗試用DNS查詢web服務,Consul將不會返回結果.由於服務不健康.

[root@dhcp-10-201-102-198 ~]# dig @127.0.0.1 -p 8600 Faceid.service.consul SRV ; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.17.rc1.el6 <<>> @127.0.0.1 -p 8600 Faceid.service.consul SRV ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40884 ;; flags: qr aa rd; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 3 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;Faceid.service.consul. IN SRV ;; ANSWER SECTION: Faceid.service.consul. 0 IN SRV 1 1 9000 s3.node.dc1.consul. Faceid.service.consul. 0 IN SRV 1 1 9000 s1.node.dc1.consul. Faceid.service.consul. 0 IN SRV 1 1 9000 s2.node.dc1.consul. ;; ADDITIONAL SECTION: s3.node.dc1.consul. 0 IN A 10.201.102.200 s1.node.dc1.consul. 0 IN A 10.201.102.198 s2.node.dc1.consul. 0 IN A 10.201.102.199 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Tue Mar 28 18:20:15 2017 ;; MSG SIZE rcvd: 165
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

K /V

除了提供服務發現和健康檢查的集成.Consul提供了一個易用的鍵/值存儲.這能夠用來保持動態配置,協助服務協調,領袖選舉,作開發者能夠想到的任何事情.

[root@dhcp-10-201-102-198 ~]# curl -v http://localhost:8500/v1/kv/?recurse * About to connect() to localhost port 8500 (#0) * Trying ::1... 拒絕鏈接 * Trying 127.0.0.1... connected * Connected to localhost (127.0.0.1) port 8500 (#0) > GET /v1/kv/?recurse HTTP/1.1 > User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.21 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2 > Host: localhost:8500 > Accept: */* > < HTTP/1.1 404 Not Found < X-Consul-Index: 1 < X-Consul-Knownleader: true < X-Consul-Lastcontact: 0 < Date: Thu, 18 Aug 2016 08:21:39 GMT < Content-Length: 0 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact * Closing connection #0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

由於沒有key因此咱們獲得了一個404響應.如今咱們PUT一些示例的Key:

[root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/key1 [root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/key2?flags=42 [root@dhcp-10-201-102-198 ~]# curl -X PUT -d 'test' http://localhost:8500/v1/kv/web/sub/key3
  • 1
  • 2
  • 3

咱們建立了值爲」test」的3個Key,注意返回的值是通過了base64編碼的.用來支持非UTF8編碼字符.對Key web/key2咱們設置了一個標誌值爲 42.全部的key支持設置一個64位的整形數字標誌.Consul內部不適用這個值.可是他能夠被客戶端適用來作一些元數據.

完成設置後,咱們發起了一個GET請求來接收多個key的值,使用?recurse參數.

[root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/kv/web/?recurse | python -m json.tool [ { "CreateIndex": 502660, "Flags": 0, "Key": "web/key1", "LockIndex": 0, "ModifyIndex": 502660, "Value": "dGVzdA==" }, { "CreateIndex": 502663, "Flags": 42, "Key": "web/key2", "LockIndex": 0, "ModifyIndex": 502663, "Value": "dGVzdA==" }, { "CreateIndex": 502665, "Flags": 0, "Key": "web/sub/key3", "LockIndex": 0, "ModifyIndex": 502665, "Value": "dGVzdA==" } ]
  • 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

你能夠獲取單個的key

[root@dhcp-10-201-102-198 ~]# curl -s http://localhost:8500/v1/kv/web/key1 | python -m json.tool [ { "CreateIndex": 502660, "Flags": 0, "Key": "web/key1", "LockIndex": 0, "ModifyIndex": 502660, "Value": "dGVzdA==" } ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

刪除key也很簡單.經過DELETE動做來完成.咱們能夠經過指定完整路徑來刪除一個單獨的key.或者咱們可使用?recurse遞歸的刪除主路徑下全部key.

[root@dhcp-10-201-102-198 ~]# curl -X DELETE http://localhost:8500/v1/kv/web/sub?recurse true
  • 1
  • 2

能夠經過發送相同的URL並提供不一樣的消息體的PUT請求去修改一個Key.另外,Consul提供一個檢查並設置的操做,實現原子的Key修改.經過?cas=參數加上GET中最近的ModifyIndex來達到. 例如咱們想修改 「web/key1」:

curl -X PUT -d 'newval' http://localhost:8500/v1/kv/web/key1?cas=502660 true curl -X PUT -d 'newval' http://localhost:8500/v1/kv/web/key1?cas=502660 false
  • 1
  • 2
  • 3
  • 4

在這種狀況下,第一次CAS 更新成功由於ModifyIndex502660.而第二次失敗是由於ModifyIndex在第一次更新後已經不是502660了 .

咱們也可使用ModifyIndex來等待key值的改變.例如咱們想等待key2被修改:

[root@dhcp-10-201-102-198 ~]# curl "http://localhost:8500/v1/kv/web/key2" [{"LockIndex":0,"Key":"web/key2","Flags":42,"Value":"dGVzdA==","CreateIndex":502663,"ModifyIndex":502663}] [root@dhcp-10-201-102-198 ~]# curl "http://localhost:8500/v1/kv/web/key2?index=502663&wait=5s" [{"LockIndex":0,"Key":"web/key2","Flags":42,"Value":"dGVzdA==","CreateIndex":502663,"ModifyIndex":502663}]
  • 1
  • 2
  • 3
  • 4

經過提供 ?index=,咱們請求等待key值有一個比502663更大的ModifyIndex.雖然?wait=5s參數限制了這個請求最多5秒,不然返回當前的未改變的值. 這樣能夠有效的等待key的改變.另外,這個功能能夠用於等待一組key.直到其中的某個key有修改.

Conusl 命令行

見識了consul的強大,consul能夠經過一個簡單的CLI來控制,consul只有一個命令行應用,就是consul命令,consul命令能夠包含agent、members等參數進行使用,這一篇來具體看看consul CLI的具體用法,consul -h便可看到consul cli所支持的參數,而每一個參數裏面又支持其餘參數,下面咱們就來具體看看。

[root@dhcp-10-201-102-198 ~]# consul usage: consul [--version] [--help] <command> [<args>] Available commands are: agent Runs a Consul agent 運行一個consul agent configtest Validate config file event Fire a new event exec Executes a command on Consul nodes 在consul節點上執行一個命令 force-leave Forces a member of the cluster to enter the "left" state 強制節點成員在集羣中的狀態轉換到left狀態 info Provides debugging information for operators 提供操做的debug級別的信息 join Tell Consul agent to join cluster 加入consul節點到集羣中 keygen Generates a new encryption key 生成一個新的加密key keyring Manages gossip layer encryption keys kv Interact with the key-value store leave Gracefully leaves the Consul cluster and shuts down lock Execute a command holding a lock maint Controls node or service maintenance mode members Lists the members of a Consul cluster 列出集羣中成員 monitor Stream logs from a Consul agent 打印consul節點的日誌信息 operator Provides cluster-level tools for Consul operators reload Triggers the agent to reload configuration files 觸發節點從新加載配置文件 rtt Estimates network round trip time between nodes snapshot Saves, restores and inspects snapshots of Consul server state version Prints the Consul version 打印consul的版本信息 watch Watch for changes in Consul 監控consul的改變
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

更詳細見官網

Agent

agent指令是consul的核心,它運行agent來維護成員的重要信息、運行檢查、服務宣佈、查詢處理等等。

==> Usage: consul agent [options]
  Starts the Consul agent and runs until an interrupt is received. The agent represents a single node in a cluster. Options: -advertise=addr Sets the advertise address to use -advertise-wan=addr Sets address to advertise on wan instead of advertise addr -bootstrap Sets server to bootstrap mode -bind=0.0.0.0 Sets the bind address for cluster communication -http-port=8500 Sets the HTTP API port to listen on -bootstrap-expect=0 Sets server to expect bootstrap mode. -client=127.0.0.1 Sets the address to bind for client access. This includes RPC, DNS, HTTP and HTTPS (if configured) -config-file=foo Path to a JSON file to read configuration from. This can be specified multiple times. -config-dir=foo Path to a directory to read configuration files from. This will read every file ending in ".json" as configuration in this directory in alphabetical order. This can be specified multiple times. -data-dir=path Path to a data directory to store agent state -dev Starts the agent in development mode. -recursor=1.2.3.4 Address of an upstream DNS server. Can be specified multiple times. -dc=east-aws Datacenter of the agent (deprecated: use 'datacenter' instead). -datacenter=east-aws Datacenter of the agent. -encrypt=key Provides the gossip encryption key -join=1.2.3.4 Address of an agent to join at start time. Can be specified multiple times. -join-wan=1.2.3.4 Address of an agent to join -wan at start time. Can be specified multiple times. -retry-join=1.2.3.4 Address of an agent to join at start time with retries enabled. Can be specified multiple times. -retry-interval=30s Time to wait between join attempts. -retry-max=0 Maximum number of join attempts. Defaults to 0, which will retry indefinitely. -retry-join-ec2-region EC2 Region to use for discovering servers to join. -retry-join-ec2-tag-key EC2 tag key to filter on for server discovery -retry-join-ec2-tag-value EC2 tag value to filter on for server discovery -retry-join-gce-project-name Google Compute Engine project to discover servers in -retry-join-gce-zone-pattern Google Compute Engine region or zone to discover servers in (regex pattern) -retry-join-gce-tag-value Google Compute Engine tag value to filter for server discovery -retry-join-gce-credentials-file Path to credentials JSON file to use with Google Compute Engine -retry-join-wan=1.2.3.4 Address of an agent to join -wan at start time with retries enabled. Can be specified multiple times. -retry-interval-wan=30s Time to wait between join -wan attempts. -retry-max-wan=0 Maximum number of join -wan attempts. Defaults to 0, which will retry indefinitely. -log-level=info Log level of the agent. -node=hostname Name of this node. Must be unique in the cluster -node-meta=key:value An arbitrary metadata key/value pair for this node. This can be specified multiple times. -protocol=N Sets the protocol version. Defaults to latest. -rejoin Ignores a previous leave and attempts to rejoin the cluster. -server Switches agent to server mode. -syslog Enables logging to syslog -ui Enables the built-in static web UI server -ui-dir=path Path to directory containing the Web UI resources -pid-file=path Path to file to store agent PID
  • 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
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

event

event命令提供了一種機制,用來fire自定義的用戶事件,這些事件對consul來講是不透明的,但它們能夠用來構建自動部署、重啓服務或者其餘行動的腳本。

-http-addr:http服務的地址,agent能夠連接上來發送命令,若是沒有設置,則默認是127.0.0.1:8500。 -datacenter:數據中心。 -name:事件的名稱 -node:一個正則表達式,用來過濾節點 -service:一個正則表達式,用來過濾節點上匹配的服務 -tag:一個正則表達式,用來過濾節點上符合tag的服務,必須和-service一塊兒使用。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

exec

exec指令提供了一種遠程執行機制,好比你要在全部的機器上執行uptime命令,遠程執行的工做經過job來指定,存儲在KV中,agent使用event系統能夠快速的知道有新的job產生,消息是經過gossip協議來傳遞的,所以消息傳遞是最佳的,可是並不保證命令的執行。事件經過gossip來驅動,遠程執行依賴KV存儲系統(就像消息代理同樣)。

-http-addr:http服務的地址,agent能夠連接上來發送命令,若是沒有設置,則默認是127.0.0.1:8500。 -datacenter:數據中心。 -prefix:key在KV系統中的前綴,用來存儲請求數據,默認是_rexec -node:一個正則表達式,用來過濾節點,評估事件 -service:一個正則表達式,用來過濾節點上匹配的服務 -tag:一個正則表達式,用來過濾節點上符合tag的服務,必須和-service一塊兒使用。 -wait:在節點多長時間沒有響應後,認爲job已經完成。 -wait-repl: -verbose:輸出更多信息
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

force-leave

force-leave治療能夠強制consul集羣中的成員進入left狀態(空閒狀態),記住,即便一個成員處於活躍狀態,它仍舊能夠再次加入集羣中,這個方法的真實目的是強制移除failed的節點。若是failed的節點仍是網絡的一部分,則consul會週期性的從新連接failed的節點,若是通過一段時間後(默認是72小時),consul則會宣佈中止嘗試連接failed的節點。force-leave指令能夠快速的把failed節點轉換到left狀態。

-rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400。
  • 1

info

info指令提供了各類操做時能夠用到的debug信息,對於client和server,info有返回不一樣的子系統信息,目前有如下幾個KV信息:agent(提供agent信息),consul(提供consul庫的信息),raft(提供raft庫的信息),serf_lan(提供LAN gossip pool),serf_wan(提供WAN gossip pool)

-rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400
  • 1

join

join指令告訴consul agent加入一個已經存在的集羣中,一個新的consul agent必須加入一個已經有至少一個成員的集羣中,這樣它才能加入已經存在的集羣中,若是你不加入一個已經存在的集羣,則agent是它自身集羣的一部分,其餘agent則能夠加入進來。agents能夠加入其餘agent屢次。consul join [options] address。若是你想加入多個集羣,則能夠寫多個地址,consul會加入全部的地址。

-wan:agent運行在server模式,xxxxxxx -rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400。
  • 1
  • 2

keygen

keygen指令生成加密的密鑰,能夠用在consul agent通信加密

生成一個key

leave

leave指令觸發一個優雅的離開動做並關閉agent,節點離開後不會嘗試從新加入集羣中。運行在server狀態的節點,節點會被優雅的刪除,這是很嚴重的,在某些狀況下一個不優雅的離開會影響到集羣的可用性。

-rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400。
  • 1

members

members指令輸出consul agent目前所知道的全部的成員以及它們的狀態,節點的狀態只有alive、left、failed三種狀態。

-detailed:輸出每一個節點更詳細的信息。 -rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400。 -status:過濾出符合正則規則的節點 -wan:xxxxxx
  • 1
  • 2
  • 3
  • 4

monitor

monitor指令用來連接運行的agent,並顯示日誌。monitor會顯示最近的日誌,並持續的顯示日誌流,不會自動退出,除非你手動或者遠程agent本身退出。

-log-level:顯示哪一個級別的日誌,默認是info -rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400
  • 1
  • 2

reload

reload指令能夠從新加載agent的配置文件。SIGHUP指令在從新加載配置文件時使用,任何從新加載的錯誤都會寫在agent的log文件中,並不會打印到屏幕。

-rpc-addr:一個rpc地址,agent能夠連接上來發送命令,若是沒有指定,默認是127.0.0.1:8400
  • 1

version

打印consul的版本

watch

watch指令提供了一個機制,用來監視實際數據視圖的改變(節點列表、成員服務、KV),若是沒有指定進程,當前值會被dump出來

-http-addr:http服務的地址,agent能夠連接上來發送命令,若是沒有設置,則默認是127.0.0.1:8500。 -datacenter:數據中心查詢。 -token:ACL token -key:監視key,只針對key類型 -name:監視event,只針對event類型 -prefix:監視key prefix,只針對keyprefix類型 -service:監控service,只針對service類型 -state:過略check state -tag:過濾service tag -type:監控類型,通常有key、keyprefix、service、nodes、checks、event
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Consul 配置

agent有各類各樣的配置項能夠在命令行或者配置文件進行定義,全部的配置項都是可選擇的,當加載配置文件的時候,consul從配置文件或者配置目錄加載配置。後面定義的配置會合並前面定義的配置,可是大多數狀況下,合併的意思是後面定義的配置會覆蓋前面定義的配置,可是有些狀況,例如event句柄,合併僅僅是添加到前面定義的句柄後面。consul從新加載配置文件也支持以信號的方式接收update信號。

下面看看命令行參數:

-advertise:通知展示地址用來改變咱們給集羣中的其餘節點展示的地址,通常狀況下-bind地址就是展示地址 -bootstrap:用來控制一個server是否在bootstrap模式,在一個datacenter中只能有一個server處於bootstrap模式,當一個server處於bootstrap模式時,能夠本身選舉爲raft leader。 -bootstrap-expect:在一個datacenter中指望提供的server節點數目,當該值提供的時候,consul一直等到達到指定sever數目的時候纔會引導整個集羣,該標記不能和bootstrap公用 -bind:該地址用來在集羣內部的通信,集羣內的全部節點到地址都必須是可達的,默認是0.0.0.0 -client:consul綁定在哪一個client地址上,這個地址提供HTTP、DNS、RPC等服務,默認是127.0.0.1 -config-file:明確的指定要加載哪一個配置文件 -config-dir:配置文件目錄,裏面全部以.json結尾的文件都會被加載 -data-dir:提供一個目錄用來存放agent的狀態,全部的agent容許都須要該目錄,該目錄必須是穩定的,系統重啓後都繼續存在 -dc:該標記控制agent容許的datacenter的名稱,默認是dc1 -encrypt:指定secret key,使consul在通信時進行加密,key能夠經過consul keygen生成,同一個集羣中的節點必須使用相同的key -join:加入一個已經啓動的agent的ip地址,能夠屢次指定多個agent的地址。若是consul不能加入任何指定的地址中,則agent會啓動失敗,默認agent啓動時不會加入任何節點。 -retry-join:和join相似,可是容許你在第一次失敗後進行嘗試。 -retry-interval:兩次join之間的時間間隔,默認是30s -retry-max:嘗試重複join的次數,默認是0,也就是無限次嘗試 -log-level:consul agent啓動後顯示的日誌信息級別。默認是info,可選:trace、debug、info、warn、err。 -node:節點在集羣中的名稱,在一個集羣中必須是惟一的,默認是該節點的主機名 -protocol:consul使用的協議版本 -rejoin:使consul忽略先前的離開,在再次啓動後仍舊嘗試加入集羣中。 -server:定義agent運行在server模式,每一個集羣至少有一個server,建議每一個集羣的server不要超過5個 -syslog:開啓系統日誌功能,只在linux/osx上生效 -ui-dir:提供存放web ui資源的路徑,該目錄必須是可讀的 -pid-file:提供一個路徑來存放pid文件,可使用該文件進行SIGINT/SIGHUP(關閉/更新)agent
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

除了命令行參數外,配置也能夠寫入文件中,在某些狀況下配置文件會更簡單一些,例如:利用consul被用來管理系統。配置文件是json格式的,很容易編寫。配置文件不只被用來設置agent的啓動,也能夠用來提供健康檢測和服務發現的定義。配置文件的通常樣例以下:

{
  "datacenter": "dc1", "data_dir": "/opt/consul", "log_level": "INFO", "node_name": "s1", "server": true, "bootstrap_expect": 3, "bind_addr": "10.201.102.198", "client_addr": "0.0.0.0", "ui_dir": "/root/consul_ui", "retry_join": ["10.201.102.198","10.201.102.199","10.201.102.200","10.201.102.248"], "retry_interval": "30s", "enable_debug": false, "rejoin_after_leave": true, "start_join": ["10.201.102.198","10.201.102.199","10.201.102.200","10.201.102.248"], "enable_syslog": true, "syslog_facility": "local5" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

下面看看詳細的配置文件參數:

acl_datacenter:只用於server,指定的datacenter的權威ACL信息,全部的servers和datacenter必須贊成ACL datacenter
acl_default_policy:默認是allow
acl_down_policy:
acl_master_token:
acl_token:agent會使用這個token和consul server進行請求
acl_ttl:控制TTL的cache,默認是30s addresses:一個嵌套對象,能夠設置如下key:dns、http、rpc advertise_addr:等同於-advertise bootstrap:等同於-bootstrap bootstrap_expect:等同於-bootstrap-expect bind_addr:等同於-bind ca_file:提供CA文件路徑,用來檢查客戶端或者服務端的連接 cert_file:必須和key_file一塊兒 check_update_interval: client_addr:等同於-client datacenter:等同於-dc data_dir:等同於-data-dir disable_anonymous_signature:在進行更新檢查時禁止匿名簽名 disable_remote_exec:禁止支持遠程執行,設置爲true,agent會忽視全部進入的遠程執行請求 disable_update_check:禁止自動檢查安全公告和新版本信息 dns_config:是一個嵌套對象,能夠設置如下參數:allow_stale、max_stale、node_ttl 、service_ttl、enable_truncate domain:默認狀況下consul在進行DNS查詢時,查詢的是consul域,能夠經過該參數進行修改 enable_debug:開啓debug模式 enable_syslog:等同於-syslog encrypt:等同於-encrypt key_file:提供私鑰的路徑 leave_on_terminate:默認是false,若是爲true,當agent收到一個TERM信號的時候,它會發送leave信息到集羣中的其餘節點上。 log_level:等同於-log-level node_name:等同於-node ports:這是一個嵌套對象,能夠設置如下key:dns(dns地址:8600)、http(http api地址:8500)、rpc(rpc:8400)、serf_lan(lan port:8301)、serf_wan(wan port:8302)、server(server rpc:8300) protocol:等同於-protocol recursor: rejoin_after_leave:等同於-rejoin retry_join:等同於-retry-join retry_interval:等同於-retry-interval server:等同於-server server_name:會覆蓋TLS CA的node_name,能夠用來確認CA name和hostname相匹配 skip_leave_on_interrupt:和leave_on_terminate比較相似,不過隻影響當前句柄 start_join:一個字符數組提供的節點地址會在啓動時被加入 statsd_addr: statsite_addr: syslog_facility:當enable_syslog被提供後,該參數控制哪一個級別的信息被髮送,默認Local0 ui_dir:等同於-ui-dir verify_incoming:默認false,若是爲true,則全部進入連接都須要使用TLS,須要客戶端使用ca_file提供ca文件,只用於consul server端,由於client歷來沒有進入的連接 verify_outgoing:默認false,若是爲true,則全部出去連接都須要使用TLS,須要服務端使用ca_file提供ca文件,consul server和client都須要使用,由於二者都有出去的連接 watches:watch一個詳細名單
  • 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
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

HTTP API

consul的主要接口是RESTful HTTP API,該API能夠用來增刪查改nodes、services、checks、configguration。全部的endpoints主要分爲如下類別:

kv - Key/Value存儲 agent - Agent控制 catalog - 管理nodes和services health - 管理健康監測 session - Session操做 acl - ACL建立和管理 event - 用戶Events status - Consul系統狀態
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

下面咱們就單獨看看每一個模塊的具體內容。

agent

agent endpoints用來和本地agent進行交互,通常用來服務註冊和檢查註冊,支持如下接口

/v1/agent/checks : 返回本地agent註冊的全部檢查(包括配置文件和HTTP接口)
/v1/agent/services : 返回本地agent註冊的全部 服務
/v1/agent/members : 返回agent在集羣的gossip pool中看到的成員
/v1/agent/self : 返回本地agent的配置和成員信息 /v1/agent/join/<address> : 觸發本地agent加入node /v1/agent/force-leave/<node>>: 強制刪除node /v1/agent/check/register : 在本地agent增長一個檢查項,使用PUT方法傳輸一個json格式的數據 /v1/agent/check/deregister/<checkID> : 註銷一個本地agent的檢查項 /v1/agent/check/pass/<checkID> : 設置一個本地檢查項的狀態爲passing /v1/agent/check/warn/<checkID> : 設置一個本地檢查項的狀態爲warning /v1/agent/check/fail/<checkID> : 設置一個本地檢查項的狀態爲critical /v1/agent/service/register : 在本地agent增長一個新的服務項,使用PUT方法傳輸一個json格式的數據 /v1/agent/service/deregister/<serviceID> : 註銷一個本地agent的服務項
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

catalog

catalog endpoints用來註冊/註銷nodes、services、checks

/v1/catalog/register : Registers a new node, service, or check /v1/catalog/deregister : Deregisters a node, service, or check /v1/catalog/datacenters : Lists known datacenters /v1/catalog/nodes : Lists nodes in a given DC /v1/catalog/services : Lists services in a given DC /v1/catalog/service/<service> : Lists the nodes in a given service /v1/catalog/node/<node> : Lists the services provided by a node
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

health

health endpoints用來查詢健康情況相關信息,該功能從catalog中單獨分離出來

/v1/healt/node/<node>: 返回node所定義的檢查,可用參數?dc= /v1/health/checks/<service>: 返回和服務相關聯的檢查,可用參數?dc= /v1/health/service/<service>: 返回給定datacenter中給定node中service /v1/health/state/<state>: 返回給定datacenter中指定狀態的服務,state能夠是"any", "unknown", "passing", "warning", or "critical",可用參數?dc=
  • 1
  • 2
  • 3
  • 4

session

session endpoints用來create、update、destory、query sessions

/v1/session/create: Creates a new session /v1/session/destroy/<session>: Destroys a given session /v1/session/info/<session>: Queries a given session /v1/session/node/<node>: Lists sessions belonging to a node /v1/session/list: Lists all the active sessions
  • 1
  • 2
  • 3
  • 4
  • 5

acl

acl endpoints用來create、update、destory、query acl

/v1/acl/create: Creates a new token with policy /v1/acl/update: Update the policy of a token /v1/acl/destroy/<id>: Destroys a given token /v1/acl/info/<id>: Queries the policy of a given token /v1/acl/clone/<id>: Creates a new token by cloning an existing token /v1/acl/list: Lists all the active tokens
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

event

event endpoints用來fire新的events、查詢已有的events

/v1/event/fire/<name>: 觸發一個新的event,用戶event須要name和其餘可選的參數,使用PUT方法 /v1/event/list: 返回agent知道的events
  • 1
  • 2

status

status endpoints用來或者consul 集羣的信息

/v1/status/leader : 返回當前集羣的Raft leader
/v1/status/peers : 返回當前集羣中同事
  • 1
  • 2

Consul-Template

在consul-template沒出現以前,你們構建服務發現系統,大多采用的是zookeeper、etcd+confd這樣相似的系統,以前寫過一篇consul+confd的文,講的是如何動態生成配置文件的,現在consul官方推出了本身的模板系統,就是consul-template,這樣的話動態的配置系統能夠分化爲etcd+confd和consul+consul-template兩大陣營。consul是一個和etcd相似但又強於etcd的系統,關於etcd和consul能夠翻閱之前的文章,consul-template的定位就和confd差很少同樣了,confd的後端能夠是etcd或者consul,相信consul搭配consul-template能發揮更大的效果。consul-template提供了一個便捷的方式從consul中獲取存儲的值,consul-template守護進程會查詢consul實例,來更新系統上指定的任何模板,當更新完成後,模板能夠選擇運行一些任意的命令。

consul template的使用場景:consul template能夠查詢consul中的服務目錄、key、key-values等。這種強大的抽象功能和查詢語言模板可使consul template特別適合動態的建立配置文件。例如:建立apache/nginx proxy balancers、haproxy backends、varnish servers、application configurations。
  • 1

consul template的特性:

quiescence:consul template內製靜止平衡功能,能夠智能的發現consul實例中的更改信息。這個功能能夠防止頻繁的更新模板而引發系統的波動。 dry mode:不肯定當前架構的狀態?擔憂模板的變化會破壞子系統?無須擔憂,由於consul template還有-dry模式。在dry模式,consul template會將結果呈如今STDOUT,因此操做員能夠檢查輸出是否正常,以決定更換模板是否安全 CLI and Config:若是你喜歡在命令行上指定一切,consul template均可以hold住。隨着內置HCL的支持,consul template接收一個配置文件,命令行參數,或者二者的混合。經過這種方式你能夠繼續使用你如今已有的配置管理工具和consul template來配合。 verbose debugging:即便每件事你都作的近乎完美,可是有時候仍是會有失敗發生。consul template能夠提供更詳細的debug日誌信息。
  • 1
  • 2
  • 3
  • 4

安裝

你能夠在發佈頁下載發佈包.若是你但願本身編譯請查看說明文檔.

使用

-auth=<user[:pass]> 設置基本的認證用戶名和密碼 -consul-addr=<address> 設置Consul實例的地址 -max-stale=<duration> 查詢過時的最大頻率,默認是1s -dedup 啓用重複數據刪除,當許多consul template實例渲染一個模板的時候能夠下降consul的負載 -ssl 使用https鏈接Consul使用SSL -ssl-verify 經過SSL鏈接的時候檢查證書 -ssl-cert SSL客戶端證書發送給服務器 -ssl-key 客戶端認證時使用的SSL/TLS私鑰 -ssl-ca-cert 驗證服務器的CA證書列表 -token=<token> 設置Consul API的token -syslog 把標準輸出和標準錯誤重定向到syslog,syslog的默認級別是local0。 -syslog-facility=<f> 設置syslog級別,默認是local0,必須和-syslog配合使用 -template=<template> 增長一個須要監控的模板,格式是:'templatePath:outputPath(:command)',多個模板則能夠設置屢次 -wait=<duration> 當呈現一個新的模板到系統和觸發一個命令的時候,等待的最大最小時間。若是最大值被忽略,默認是最小值的4倍。 -retry=<duration> 當在和consul api交互的返回值是error的時候,等待的時間,默認是5s。 -config=<path> 配置文件或者配置目錄的路徑 -pid-file=<path> PID文件的路徑 -log-level=<level> 設置日誌級別,能夠是"debug","info", "warn" (default), and "err" -dry Dump生成的模板到標準輸出,不會生成到磁盤 -once 運行consul-template一次後退出,不以守護進程運行 -reap 子進程自動收割
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

查看所有選項,使用如下命令

consul-template -h
  • 1

命令行

一、查詢本地consl實例,生成模板後重啓nginx,若是consul不可用,若是api故障則每30s嘗試檢測一次值,consul-template運行一次後退出

consul-template -retry 30s -once -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"
  • 1

test.ctmpl

{{range service "Faceid"}} {{.ID}} {{.Address}}:{{.Port}} check inter 5000 fall 1 rise 2 weight 2{{end}}
  • 1
  • 2

test.out

Faceid 10.201.102.198:9000 check inter 5000 fall 1 rise 2 weight 2 Faceid 10.201.102.199:9000 check inter 5000 fall 1 rise 2 weight 2 Faceid 10.201.102.200:9000 check inter 5000 fall 1 rise 2 weight 2
  • 1
  • 2
  • 3

二、運行consul-temple做爲一個服務

consul-template -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"
  • 1

三、查詢一個實例,渲染多個模板,而後重啓相關服務

consul-template -retry 30s -once -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"\ -template "/tmp/redis.ctmpl:/var/redis/redis.conf:service redis restart" \ -template "/tmp/haproxy.ctmpl:/var/haproxy/haproxy.conf"
  • 1
  • 2
  • 3

四、查詢一個實例,dump模板到標準輸出,參數中的-template則會被忽略

consul-template -dry -consul-addr=10.201.102.198:8500 -template "test.ctmpl:test.out"
  • 1

以上參數除了在命令行使用,也能夠直接配置在文件中,下面看看Consul-Template的配置文件,簡稱HCL(HashiCorp Configuration Language),它是和JSON兼容的,下面看個例子:

#### 配置文件 ​```Consul-Template```配置文件是使用[HashiCorp Configuration Language (HCL)](https://github.com/hashicorp/hcl)編寫的.這意味着```Consul Template```是和JSON兼容的,查看更多信息請查看 [HCL 規範](https://github.com/hashicorp/hcl) 配置文件語法支持上面的全部的選項,除非在表格中進行標明. ​```json // 這是要鏈接的Consul Agent的地址.默認爲127.0.0.1:8500.這是Consul的默認綁定地址和端口. // 不建議你直接與 Consul的 Server直接進行交互,請與本地的Consul Agent進行交互.這樣作是有一些緣由 // 最重要的是本地agent能夠複用與server的鏈接.減小HTTP的鏈接數.另外這個地址更好記. consul = "127.0.0.1:8500" // 這是用於鏈接Consul的ACL token. 若是你的集羣未啓用就不須要設置. // // 這個選項也能夠經過環境變量 CONSUL_TOKEN 來進行設置 token = "abcd1234" // 這是監聽出發reload事件的信號,默認值以下所示.將這個值設置爲空將引發 CT ,從而不監聽reload事件 reload_signal = "SIGHUP" // 這是監聽出發core dump事件的信號,默認值以下所示.將這個值設置爲空將引發 CT ,從而不監聽core dump信號 dump_signal = "SIGQUIT" // 這是監聽出發graceful stop事件的信號,默認值以下所示.將這個值設置爲空將引發 CT ,從而不監聽graceful stop信號 kill_signal = "SIGINT" // 這是鏈接Consul的重試時間.Consul Template是高容錯的設計.這意味着,出現失敗他不會退出.而按照 // 分佈式系統的慣例進行指數補償和重試來等待集羣恢復. retry = "10s" // This is the maximum interval to allow "stale" data. By default, only the // Consul leader will respond to queries; any requests to a follower will // forward to the leader. In large clusters with many requests, this is not as // scalable, so this option allows any follower to respond to a query, so long // as the last-replicated data is within these bounds. Higher values result in // less cluster load, but are more likely to have outdated data. // 這是容許陳舊數據的最大時間.Consul默認只有領袖對請求進行相應.全部對追隨者的請求將被轉發給領袖. // 在有大量請求的大型集羣中,這顯得不夠有擴展性.因此這個選項容許任何追隨者響應查詢,只要最後複製的數據 // 在這個範圍內.數值越高,越減小集羣負載,可是更容易接受到過時數據. max_stale = "10m" // 這是log的等級,若是你找到了bug,請打開debug 日誌,這樣咱們能夠更好的定位問題.這個選項也可用在命令行. log_level = "warn" // 這是存放Consul Template 進程的PID文件的路徑,若是你計劃發送定製的信號到這個進程這會比較有用. pid_file = "/path/to/pid" // 這是一個靜止定時器,他定義了在模板渲染以前等待集羣達到一致狀態的最小和最大時間. // 這對於一些變化較大的系統中比較有用,能夠減小模板渲染的次數 wait = "5s:10s" // 這是 Vault配置的開始 // Vault是HashiCorp的另一個產品 vault {  // This is the address of the Vault leader. The protocol (http(s)) portion  // of the address is required. address = "https://vault.service.consul:8200"  // This is the token to use when communicating with the Vault server.  // Like other tools that integrate with Vault, Consul Template makes the  // assumption that you provide it with a Vault token; it does not have the  // incorporated logic to generate tokens via Vault's auth methods.  //  // This value can also be specified via the environment variable VAULT_TOKEN. token = "abcd1234"  // This option tells Consul Template to automatically renew the Vault token  // given. If you are unfamiliar with Vault's architecture, Vault requires  // tokens be renewed at some regular interval or they will be revoked. Consul  // Template will automatically renew the token at half the lease duration of  // the token. The default value is true, but this option can be disabled if  // you want to renew the Vault token using an out-of-band process.  //  // Note that secrets specified in a template (using {{secret}} for example)  // are always renewed, even if this option is set to false. This option only  // applies to the top-level Vault token itself. renew = true  // This section details the SSL options for connecting to the Vault server.  // Please see the SSL options below for more information (they are the same). ssl {  // ... } } // 這部分配置請求的基本的權限驗證信息 auth { enabled = true username = "test" password = "test" } // 這部分配置鏈接到Consul服務器的SSL信息. ssl {  // 使用SSL須要先打開這個開關 enabled = true  // This enables SSL peer verification. The default value is "true", which  // will check the global CA chain to make sure the given certificates are  // valid. If you are using a self-signed certificate that you have not added  // to the CA chain, you may want to disable SSL verification. However, please  // understand this is a potential security vulnerability. verify = false  // This is the path to the certificate to use to authenticate. If just a  // certificate is provided, it is assumed to contain both the certificate and  // the key to convert to an X509 certificate. If both the certificate and  // key are specified, Consul Template will automatically combine them into an  // X509 certificate for you. cert = "/path/to/client/cert" key = "/path/to/client/key"  // This is the path to the certificate authority to use as a CA. This is  // useful for self-signed certificates or for organizations using their own  // internal certificate authority. ca_cert = "/path/to/ca" } // 設置鏈接到syslog服務器的配置 // 用於進行日誌記錄syslog {  // 打開開關 enabled = true  // 設備名稱 facility = "LOCAL5" } // This block defines the configuration for de-duplication mode. Please see the // de-duplication mode documentation later in the README for more information // on how de-duplication mode operates. deduplicate {  // This enables de-duplication mode. Specifying any other options also enables  // de-duplication mode. enabled = true  // This is the prefix to the path in Consul's KV store where de-duplication  // templates will be pre-rendered and stored. prefix = "consul-template/dedup/" } // This block defines the configuration for exec mode. Please see the exec mode // documentation at the bottom of this README for more information on how exec // mode operates and the caveats of this mode. exec {  // This is the command to exec as a child process. There can be only one  // command per Consul Template process. command = "/usr/bin/app"  // This is a random splay to wait before killing the command. The default  // value is 0 (no wait), but large clusters should consider setting a splay  // value to prevent all child processes from reloading at the same time when  // data changes occur. When this value is set to non-zero, Consul Template  // will wait a random period of time up to the splay value before reloading  // or killing the child process. This can be used to prevent the thundering  // herd problem on applications that do not gracefully reload. splay = "5s"  // This defines the signal that will be sent to the child process when a  // change occurs in a watched template. The signal will only be sent after  // the process is started, and the process will only be started after all  // dependent templates have been rendered at least once. The default value  // is "" (empty or nil), which tells Consul Template to restart the child  // process instead of sending it a signal. This is useful for legacy  // applications or applications that cannot properly reload their  // configuration without a full reload. reload_signal = "SIGUSR1"  // This defines the signal sent to the child process when Consul Template is  // gracefully shutting down. The application should begin a graceful cleanup.  // If the application does not terminate before the `kill_timeout`, it will  // be terminated (effectively "kill -9"). The default value is "SIGTERM". kill_signal = "SIGINT"  // This defines the amount of time to wait for the child process to gracefully  // terminate when Consul Template exits. After this specified time, the child  // process will be force-killed (effectively "kill -9"). The default value is  // "30s". kill_timeout = "2s" } // 這部分定義了對模板的配置,和其餘配置塊不一樣.這部分能夠針對不一樣模板配置屢次.也能夠在CLI命令 // 直接進行配置 template {  // 這是輸入模板的配置文件路徑,必選項 source = "/path/on/disk/to/template.ctmpl"  // 這是源模板渲染以後存放的路徑,若是父目錄不存在Consul Template會嘗試進行建立 destination = "/path/on/disk/where/template/will/render.txt"  // This is the optional command to run when the template is rendered. The  // command will only run if the resulting template changes. The command must  // return within 30s (configurable), and it must have a successful exit code.  // Consul Template is not a replacement for a process monitor or init system.  // 這是當模板渲染完成後可選的要執行的命令.這個命令只會在模板發生改變後纔會運行.這個命令必需要在30秒  // 內進行返回(可配置),必須返回一個成功的退出碼.Consul Template不能替代進程監視或者init 系統  // 的功能 command = "restart service foo"  // 這是最大的等待命令返回的時間,默認是30秒 command_timeout = "60s"  // 這是渲染後的文件的權限,若是不設置,Consul Template將去匹配以前已經存在的文件的權限.  // 若是文件不存在,權限會被設置爲 0644 perms = 0600  // 這個選項對渲染以前的文件進行備份.他保持一個備份.  // 這個選項在發生意外更高時,有一個回滾策略. backup = true  // 模板的分隔符,默認是 "{{"和"}}".可是對於一些模板用其餘的分隔符可能更好  // 能夠避免與自己的衝突 left_delimiter = "{{" right_delimiter = "}}"  // 這是最小和最大等待渲染一個新模板和執行命令的時間.使用 分號 個號.若是忽略最大值,最大  // 值會被設置爲最小值的4倍.這個選項沒有默認值.這個值相對全局因此的等待時間有最高優先級 wait = "2s:6s" }
  • 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
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180

注意: 不是全部的選項都是必選的.例如: 若是你沒有使用Vault你不用設置這一塊. 相似的你沒有使用syslog系統你也不須要指定syslog配置.

爲了更加安全,token也能夠從環境變量裏讀取,使用 CONSUL_TOKEN 和 VAULT_TOKEN.強烈建議你不要把token放到未加密的文本配置文件中.

模版語法

Consul Template 使用了Go的模板語法.若是你對他的語法不熟悉建議你讀下文檔.他的語法看起來與 Mustache, Handlebars, 或者 Liquid 相似.

在Go 提供的模板函數以外,Consul Template暴露了如下的函數:

API 函數

datacenters
查詢目錄中的全部數據中心.使用如下語法:

{{datacenters}}
  • 1

file
讀取並輸出磁盤上的本地文件,若是沒法讀取產生一個錯誤.使用以下語法

{{file "/path/to/local/file"}}
  • 1

這個例子將輸出 /path/to/local/file 文件內容到模板. 注意:這不會在嵌套模板中被處理

key
查詢Consul指定key的值,若是key的值不能轉換爲字符串,將產生錯誤.使用以下語法:

{{key "service/redis/maxconns@east-aws"}}
  • 1

上面的例子查詢了在east-aws數據中心的 service/redis/maxconns的值.若是忽略數據中心參數,將會查詢本地數據中心的值:

{{key "service/redis/maxconns"}}
  • 1

Consul鍵值結構的美妙在於,這徹底取決於你!

key_or_default
查詢Consul中指定的key的值,若是key不存在,則返回默認值.使用方式以下

{{key_or_default "service/redis/maxconns@east-aws" "5"}}
  • 1

注意Consul Template使用了多個階段的運算.在第一階段的運算若是Consul沒有返回值,則會一直使用默認值.後續模板解析中若是值存在了則會讀取真實的值.這很重要,運維Consul Templae不會由於key_or_default沒找到key而阻塞模板的的渲染.即便key存在若是Consul沒有按時返回這個數據,也會使用默認值來進行替代.

ls
查看Consul的全部以指定前綴開頭的key-value對.若是有值沒法轉換成字符串則會產生一個錯誤:

{{range ls "service/redis@east-aws"}} {{.Key}} {{.Value}}{{end}}
  • 1
  • 2

若是Consul實例在east-aws數據中心存在這個結構service/redis,渲染後的模板應該相似這樣:

minconns 2
maxconns 12
  • 1
  • 2

若是你忽略數據中心屬性,則會返回本地數據中心的查詢結果.

node
查詢目錄中的一個節點信息

{{node "node1"}}
  • 1

若是未指定任何參數,則當前agent所在節點將會被返回:

{{node}}
  • 1

你能夠指定一個可選的參數來指定數據中心:

{{node "node1" "@east-aws"}}
  • 1

若是指定的節點沒有找到則會返回nil.若是節點存在就會列出節點的信息和節點提供的服務.

{{with node}}{{.Node.Node}} ({{.Node.Address}}){{range .Services}} {{.Service}} {{.Port}} ({{.Tags | join ","}}){{end}} {{end}}
  • 1
  • 2
  • 3

nodes
查詢目錄中的所有節點,使用以下語法

{{nodes}}
  • 1

這個例子會查詢Consul的默認數據中心.你可使用可選參數指定一個可選參數來指定數據中心:

{{nodes "@east-aws"}}
  • 1

這個例子會查詢east-aws數據中心的全部幾點.

secret
查詢Vault中指定路徑的密匙.若是指定的路徑不存在或者VaultToken沒有足夠權限去讀取指定的路徑,將會產生一個錯誤.若是路徑存在可是key不存在則返回「.

{{with secret "secret/passwords"}}{{.Data.password}}{{end}}
  • 1

可使用以下字段:

LeaseID - the unique lease identifier LeaseDuration - the number of seconds the lease is valid Renewable - if the secret is renewable Data - the raw data - this is a map[string]interface{}, so it can be queried using Go's templating "dot notation" If the map key has dots "." in it, you need to access the value using the index function: {{index .Data "my.key.with.dots"}} If additional arguments are passed to the function, then the operation is assumed to be a write operation instead of a read operation. The write operation must return data in order to be valid. This is especially useful for the PKI secret backend, for example. {{ with secret "pki/issue/my-domain-dot-com" "common_name=foo.example.com" }} {{ .Data.certificate }} {{ end }} The parameters must be key=value pairs, and each pair must be its own argument to the function: {{ secret "path/" "a=b" "c=d" "e=f" }} Please always consider the security implications of having the contents of a secret in plain-text on disk. If an attacker is able to get access to the file, they will have access to plain-text secrets.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Please note that Vault does not support blocking queries. As a result, Consul Template will not immediately reload in the event a secret is changed as it does with Consul’s key-value store. Consul Template will fetch a new secret at half the lease duration of the original secret. For example, most items in Vault’s generic secret backend have a default 30 day lease. This means Consul Template will renew the secret every 15 days. As such, it is recommended that a smaller lease duration be used when generating the initial secret to force Consul Template to renew more often.

secrets
Query Vault to list the secrets at the given path. Please note this requires Vault 0.5+ and the endpoint you want to list secrets must support listing. Not all endpoints support listing. The result is the list of secret names as strings.

{{range secrets "secret/"}}{{.}}{{end}}
  • 1

The trailing slash is optional in the template, but the generated secret dependency will always have a trailing slash in log output.

To iterate and list over every secret in the generic secret backend in Vault, for example, you would need to do something like this:

{{range secrets "secret/"}} {{with secret (printf "secret/%s" .)}} {{range $k, $v := .Data}} {{$k}}: {{$v}} {{end}} {{end}} {{end}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

You should probably never do this. Please also note that Vault does not support blocking queries. To understand the implications, please read the note at the end of the secret function.

service
查詢Consul中匹配表達式的服務.語法以下:

{{service "release.web@east-aws"}}
  • 1

上面的例子查詢Consul中,在east-aws數據中心存在的健康的 web服務.tag和數據中心參數是可選的.從當前數據中心查詢全部節點的web服務而無論tag,查詢語法以下:

{{service "web"}}
  • 1

這個函數返回[]*HealthService結構.可按照以下方式應用到模板:

{{range service "web@data center"}} server {{.Name}} {{.Address}}:{{.Port}}{{end}}
  • 1
  • 2

產生以下輸出:

server nyc_web_01 123.456.789.10:8080 server nyc_web_02 456.789.101.213:8080
  • 1
  • 2

默認值會返回健康的服務,若是你想獲取全部服務,能夠增長any選項,以下:

{{service "web" "any"}}
  • 1

這樣就會返回註冊過的全部服務,而不論他的狀態如何.

若是你想過濾指定的一個或者多個健康狀態,你能夠經過逗號隔開多個健康狀態:

{{service "web" "passing, warning"}}
  • 1

這樣將會返回被他們的節點和服務級別的檢查定義標記爲 「passing」 或者 「warning」的服務. 請注意逗號是 OR而不是AND的意思.

指定了超過一個狀態過濾,幷包含any將會返回一個錯誤.由於any是比全部狀態更高級的過濾.

後面這2種方式有些架構上的不一樣:

{{service "web"}} {{service "web" "passing"}}
  • 1
  • 2

前者會返回Consul認爲healthypassing的全部服務.後者將返回全部已經在Consul註冊的服務.而後會執行一個客戶端的過濾.一般若是你想獲取健康的服務,你應該不要使用passing參數,直接忽略第三個參數便可.然而第三個參數在你想查詢 passing或者warning的服務會比較有用,以下:

{{service "web" "passing, warning"}}
  • 1

服務的狀態也是可見的,若是你想本身作一些額外的過濾,語法以下:

{{range service "web" "any"}} {{if eq .Status "critical"}} // Critical state!{{end}} {{if eq .Status "passing"}} // Ok{{end}}
  • 1
  • 2
  • 3
  • 4
  • 5

執行命令時,在Consul將服務設置爲維護模式,只須要在你的命令上包上Consul的 maint 調用:

#!/bin/sh set -e consul maint -enable -service web -reason "Consul Template updated" service nginx reload consul maint -disable -service web
  • 1
  • 2
  • 3
  • 4
  • 5

另外若是你沒有安裝Consul agent,你能夠直接調用API請求:

#!/bin/sh set -e curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=true&reason=Consul+Template+Updated" service nginx reload curl -X PUT "http://$CONSUL_HTTP_ADDR/v1/agent/service/maintenance/web?enable=false"
  • 1
  • 2
  • 3
  • 4
  • 5

services
查詢Consul目錄中的全部服務,使用以下語法:

{{services}}
  • 1

這個例子將查詢Consul的默認數據中心,你能夠指定一個可選參數來指定數據中心:

{{services "@east-aws"}}
  • 1

請注意: services函數與service是不一樣的,service接受更多參數而且查詢監控的服務列表.這個查詢Consul目錄並返回一個服務的tag的Map,以下:

{{range services}} {{.Name}} {{range .Tags}} {{.}}{{end}} {{end}}
  • 1
  • 2
  • 3
  • 4
  • 5

tree
查詢全部指定前綴的key-value值對,若是其中的值有沒法轉換爲字符串的則引起錯誤:

{{range tree "service/redis@east-aws"}} {{.Key}} {{.Value}}{{end}}
  • 1
  • 2

若是Consul實例在east-aws數據中心有一個service/redis結構,模板的渲染結果相似下面:

minconns 2 maxconns 12 nested/config/value "value"
  • 1
  • 2
  • 3

ls不一樣,tree返回前綴下的全部key.和Unix的tree命令比較像.若是忽略數據中心參數,則會使用本地數據中心

查看更多

項目Github地址

Haproxy 實例

根據haproxy服務的配置文件建立一個consul-template模版渲染文件:haproxy.ctmpl

# Consul Haproxy configured global maxconn 20480 ulimit-n 65535 log 127.0.0.1 local5 uid 200 gid 200 chroot /usr/local/haproxy nbproc 1 daemon pidfile /usr/local/haproxy/logs/haproxy.pid defaults log global mode http option httplog option dontlognull option forwardfor option abortonclose retries 3 maxconn 3000 stats enable stats hide-version stats uri /admin stats auth admin:admin stats refresh 10s balance roundrobin timeout connect 5000ms timeout client 50000ms timeout server 50000ms timeout check 2000ms listen web_haproxy bind 0.0.0.0:8080 mode http log 127.0.0.1 local5 err stats refresh 5s stats uri /admin stats realm liang lian stats auth admin:admin stats hide-version stats admin if TRUE frontend consul bind 0.0.0.0:8500 mode http log global default_backend consul-cluster backend consul-cluster mode http {{range service "Faceid"}} server {{.ID}} {{.Address}}:{{.Port}} check inter 5000 fall 1 rise 2 weight 2{{end}}
  • 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
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

運行consul-template做爲一個服務,經過上面的渲染模版渲染一個haproxy.cfg的配置文件,而後重啓haproxy服務

consul-template -consul-addr=10.201.102.185:8500 -template "/root/haproxy.ctmpl:/etc/haproxy.cfg:service haproxy restart"
  • 1

10.201.102.185 看我上篇文章Haproxy,這是consul集羣的VIP,爲了不單獨調某一臺服務器服務器出現故障後consul-template沒法工做。

渲染後的haproxy.cfg

# Consul Haproxy configured global maxconn 20480 ulimit-n 65535 log 127.0.0.1 local5 uid 200 gid 200 chroot /usr/local/haproxy nbproc 1 daemon pidfile /usr/local/haproxy/logs/haproxy.pid defaults log global mode http option httplog option dontlognull option forwardfor option abortonclose retries 3 maxconn 3000 stats enable stats hide-version stats uri /admin stats auth admin:admin stats refresh 10s balance roundrobin timeout connect 5000ms timeout client 50000ms timeout server 50000ms timeout check 2000ms listen web_haproxy bind 0.0.0.0:8080 mode http log 127.0.0.1 local5 err stats refresh 5s stats uri /admin stats realm liang lian stats auth admin:admin stats hide-version stats admin if TRUE frontend consul bind 0.0.0.0:8500 mode http log global default_backend consul-cluster backend consul-cluster mode http server Faceid 10.201.102.198:9000 check inter 5000 fall 1 rise 2 weight 2 server Faceid 10.201.102.199:9000 check inter 5000 fall 1 rise 2 weight 2 server Faceid 10.201.102.200:9000 check inter 5000 fall 1 rise 2 weight 2
  • 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
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

整個就是搭建consul集羣,平臺中的服務會註冊到consul集羣中,haproxy避免consul-template調consul時出現單點故障consul-template沒法工做作的高可用,Consul-template就是能在整個平臺的各個系統和應用中使用,查詢consul集羣來獲取平臺上各個應用的存活狀態和IP。

整套下來實現了兩個重點:

實現了中心服務註冊查詢
平臺中其餘節點的查詢服務和配置文件自動更新

參考資料

https://my.oschina.net/guol/blog/675281
https://www.consul.io/docs/guides/index.html
https://www.gitbook.com/book/vincentmi/consul-guide/details

https://my.oschina.net/abcfy2/blog/675665

下載

點擊下載PDF文件

相關文章
相關標籤/搜索