본문 바로가기

리눅스

[draft] 우분투에 Consul을 설치하고 설정하는 방법

728x90

우분투에 Consul을 설치하고 설정하는 방법(install consul)

consul ports table

Use Default Ports
DNS: The DNS server (TCP and UDP) 8600
HTTP: The HTTP API (TCP Only) 8500
HTTPS: The HTTPs API disabled (8501)*
gRPC: The gRPC API disabled (8502)*
LAN Serf: The Serf LAN port (TCP and UDP) 8301
Wan Serf: The Serf WAN port (TCP and UDP) 8302
server: Server RPC address (TCP Only) 8300
Sidecar Proxy Min: 자동으로 할당된 사이드카 서비스 등록에 사용할 포함된 최소 포트 번호입니다. 21000
Sidecar Proxy Max: 자동으로 할당된 사이드카 서비스 등록에 사용할 최대 포트 번호를 포함합니다. 21255

** HTTPS 및 gRPC의 경우 표에 지정된 포트가 권장 사항입니다.

Consul 설치

우분투에 consul 서버 설치

필요한 패키지 설치

sudo apt-get update && sudo apt-get install -y gnupg software-properties-common

HashiCorp GPG 키 추가

curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

HashiCorp 저장소 추가

echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list

패키지 리스트 업데이트

sudo apt-get update

Consul 설치

sudo apt-get install -y consul

Consul 버전 정보 확인

consul --version
$ consul --version
Consul v1.19.1
Revision 9f62fb41
Build Date 2024-07-11T14:47:27Z
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)

Consul 설정

  • Consul의 기본 설정 파일을 /etc/consul.d/consul.hcl에 작성합니다.
sudo tee /etc/consul.d/consul.hcl > /dev/null <<EOF
datacenter = "my-dc-1"
data_dir = "/opt/consul"
ui_config{
  enabled = true
}
client_addr = "0.0.0.0"
server = true
bind_addr = "0.0.0.0"
bootstrap_expect = 1
EOF
더보기

---

cat /etc/consul.d/consul.hcl
# Copyright (c) HashiCorp, Inc.
# SPDX-License-Identifier: BUSL-1.1

# Full configuration options can be found at https://www.consul.io/docs/agent/config

# datacenter
# This flag controls the datacenter in which the agent is running. If not provided,
# it defaults to "dc1". Consul has first-class support for multiple datacenters, but 
# it relies on proper configuration. Nodes in the same datacenter should be on a 
# single LAN.
#datacenter = "my-dc-1"

# data_dir
# This flag provides a data directory for the agent to store state. This is required
# for all agents. The directory should be durable across reboots. This is especially
# critical for agents that are running in server mode as they must be able to persist
# cluster state. Additionally, the directory must support the use of filesystem
# locking, meaning some types of mounted folders (e.g. VirtualBox shared folders) may
# not be suitable.
data_dir = "/opt/consul"

# client_addr
# The address to which Consul will bind client interfaces, including the HTTP and DNS
# servers. By default, this is "127.0.0.1", allowing only loopback connections. In
# Consul 1.0 and later this can be set to a space-separated list of addresses to bind
# to, or a go-sockaddr template that can potentially resolve to multiple addresses.
#client_addr = "0.0.0.0"

# ui
# Enables the built-in web UI server and the required HTTP routes. This eliminates
# the need to maintain the Consul web UI files separately from the binary.
# Version 1.10 deprecated ui=true in favor of ui_config.enabled=true
#ui_config{
#  enabled = true
#}

# server
# This flag is used to control if an agent is in server or client mode. When provided,
# an agent will act as a Consul server. Each Consul cluster must have at least one
# server and ideally no more than 5 per datacenter. All servers participate in the Raft
# consensus algorithm to ensure that transactions occur in a consistent, linearizable
# manner. Transactions modify cluster state, which is maintained on all server nodes to
# ensure availability in the case of node failure. Server nodes also participate in a
# WAN gossip pool with server nodes in other datacenters. Servers act as gateways to
# other datacenters and forward traffic as appropriate.
#server = true

# Bind addr
# You may use IPv4 or IPv6 but if you have multiple interfaces you must be explicit.
#bind_addr = "[::]" # Listen on all IPv6
#bind_addr = "0.0.0.0" # Listen on all IPv4
#
# Advertise addr - if you want to point clients to a different address than bind or LB.
#advertise_addr = "127.0.0.1"

# Enterprise License
# As of 1.10, Enterprise requires a license_path and does not have a short trial.
#license_path = "/etc/consul.d/consul.hclic"

# bootstrap_expect
# This flag provides the number of expected servers in the datacenter. Either this value
# should not be provided or the value must agree with other servers in the cluster. When
# provided, Consul waits until the specified number of servers are available and then
# bootstraps the cluster. This allows an initial leader to be elected automatically.
# This cannot be used in conjunction with the legacy -bootstrap flag. This flag requires
# -server mode.
#bootstrap_expect=3

# encrypt
# Specifies the secret key to use for encryption of Consul network traffic. This key must
# be 32-bytes that are Base64-encoded. The easiest way to create an encryption key is to
# use consul keygen. All nodes within a cluster must share the same encryption key to
# communicate. The provided key is automatically persisted to the data directory and loaded
# automatically whenever the agent is restarted. This means that to encrypt Consul's gossip
# protocol, this option only needs to be provided once on each agent's initial startup
# sequence. If it is provided after Consul has been initialized with an encryption key,
# then the provided key is ignored and a warning will be displayed.
#encrypt = "..."

# retry_join
# Similar to -join but allows retrying a join until it is successful. Once it joins 
# successfully to a member in a list of members it will never attempt to join again.
# Agents will then solely maintain their membership via gossip. This is useful for
# cases where you know the address will eventually be available. This option can be
# specified multiple times to specify multiple agents to join. The value can contain
# IPv4, IPv6, or DNS addresses. In Consul 1.1.0 and later this can be set to a go-sockaddr
# template. If Consul is running on the non-default Serf LAN port, this must be specified
# as well. IPv6 must use the "bracketed" syntax. If multiple values are given, they are
# tried and retried in the order listed until the first succeeds. Here are some examples:
#retry_join = ["consul.domain.internal"]
#retry_join = ["10.0.4.67"]
#retry_join = ["[::1]:8301"]
#retry_join = ["consul.domain.internal", "10.0.4.67"]
# Cloud Auto-join examples:
# More details - https://www.consul.io/docs/agent/cloud-auto-join
#retry_join = ["provider=aws tag_key=... tag_value=..."]
#retry_join = ["provider=azure tag_name=... tag_value=... tenant_id=... client_id=... subscription_id=... secret_access_key=..."]
#retry_join = ["provider=gce project_name=... tag_value=..."]

---

Consul 설정 파일 유효성 검사

sudo consul validate /etc/consul.d/

시스템 데몬 리로드

sudo systemctl daemon-reload

Consul 서비스 시작 및 활성화

sudo systemctl --now enable consul.service

Consul 서비스 상태 확인

sudo systemctl status consul --no-pager
728x90

CentOS에 consul 서버 설치

필요한 패키지 설치

sudo yum install -y yum-utils

HashiCorp 저장소 추가

sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

Consul 설치

sudo yum install -y consul

Consul 버전 정보 확인

consul --version
$ consul --version
Consul v1.14.3
Revision bd257019
Build Date 2022-12-13T17:13:55Z
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)

consul.hcl 설정

vim /etc/consul.d/consul.hcl
더보기

---

cat /etc/consul.d/consul.hcl
# Full configuration options can be found at https://www.consul.io/docs/agent/config

# datacenter
# This flag controls the datacenter in which the agent is running. If not provided,
# it defaults to "dc1". Consul has first-class support for multiple datacenters, but
# it relies on proper configuration. Nodes in the same datacenter should be on a
# single LAN.
#datacenter = "my-dc-1"

# data_dir
# This flag provides a data directory for the agent to store state. This is required
# for all agents. The directory should be durable across reboots. This is especially
# critical for agents that are running in server mode as they must be able to persist
# cluster state. Additionally, the directory must support the use of filesystem
# locking, meaning some types of mounted folders (e.g. VirtualBox shared folders) may
# not be suitable.
data_dir = "/opt/consul"

# client_addr
# The address to which Consul will bind client interfaces, including the HTTP and DNS
# servers. By default, this is "127.0.0.1", allowing only loopback connections. In
# Consul 1.0 and later this can be set to a space-separated list of addresses to bind
# to, or a go-sockaddr template that can potentially resolve to multiple addresses.
#client_addr = "0.0.0.0"

# ui
# Enables the built-in web UI server and the required HTTP routes. This eliminates
# the need to maintain the Consul web UI files separately from the binary.
# Version 1.10 deprecated ui=true in favor of ui_config.enabled=true
#ui_config{
#  enabled = true
#}

# server
# This flag is used to control if an agent is in server or client mode. When provided,
# an agent will act as a Consul server. Each Consul cluster must have at least one
# server and ideally no more than 5 per datacenter. All servers participate in the Raft
# consensus algorithm to ensure that transactions occur in a consistent, linearizable
# manner. Transactions modify cluster state, which is maintained on all server nodes to
# ensure availability in the case of node failure. Server nodes also participate in a
# WAN gossip pool with server nodes in other datacenters. Servers act as gateways to
# other datacenters and forward traffic as appropriate.
#server = true

# Bind addr
# You may use IPv4 or IPv6 but if you have multiple interfaces you must be explicit.
#bind_addr = "[::]" # Listen on all IPv6
#bind_addr = "0.0.0.0" # Listen on all IPv4
#
# Advertise addr - if you want to point clients to a different address than bind or LB.
#advertise_addr = "127.0.0.1"

# Enterprise License
# As of 1.10, Enterprise requires a license_path and does not have a short trial.
#license_path = "/etc/consul.d/consul.hclic"

# bootstrap_expect
# This flag provides the number of expected servers in the datacenter. Either this value
# should not be provided or the value must agree with other servers in the cluster. When
# provided, Consul waits until the specified number of servers are available and then
# bootstraps the cluster. This allows an initial leader to be elected automatically.
# This cannot be used in conjunction with the legacy -bootstrap flag. This flag requires
# -server mode.
#bootstrap_expect=3

# encrypt
# Specifies the secret key to use for encryption of Consul network traffic. This key must
# be 32-bytes that are Base64-encoded. The easiest way to create an encryption key is to
# use consul keygen. All nodes within a cluster must share the same encryption key to
# communicate. The provided key is automatically persisted to the data directory and loaded
# automatically whenever the agent is restarted. This means that to encrypt Consul's gossip
# protocol, this option only needs to be provided once on each agent's initial startup
# sequence. If it is provided after Consul has been initialized with an encryption key,
# then the provided key is ignored and a warning will be displayed.
#encrypt = "..."

# retry_join
# Similar to -join but allows retrying a join until it is successful. Once it joins
# successfully to a member in a list of members it will never attempt to join again.
# Agents will then solely maintain their membership via gossip. This is useful for
# cases where you know the address will eventually be available. This option can be
# specified multiple times to specify multiple agents to join. The value can contain
# IPv4, IPv6, or DNS addresses. In Consul 1.1.0 and later this can be set to a go-sockaddr
# template. If Consul is running on the non-default Serf LAN port, this must be specified
# as well. IPv6 must use the "bracketed" syntax. If multiple values are given, they are
# tried and retried in the order listed until the first succeeds. Here are some examples:
#retry_join = ["consul.domain.internal"]
#retry_join = ["10.0.4.67"]
#retry_join = ["[::1]:8301"]
#retry_join = ["consul.domain.internal", "10.0.4.67"]
# Cloud Auto-join examples:
# More details - https://www.consul.io/docs/agent/cloud-auto-join
#retry_join = ["provider=aws tag_key=... tag_value=..."]
#retry_join = ["provider=azure tag_name=... tag_value=... tenant_id=... client_id=... subscription_id=... secret_access_key=..."]
#retry_join = ["provider=gce project_name=... tag_value=..."]

---

Consul 설정 파일 유효성 검사

sudo consul validate /etc/consul.d/

시스템 데몬 리로드

sudo systemctl daemon-reload

Consul 서비스 시작 및 활성화

sudo systemctl --now enable consul.service

Consul 서비스 상태 확인

sudo systemctl status consul --no-pager

Consul을 바이너리 파일로 설치

Consul의 최신 버전을 사용하거나 특정 버전을 설치할 때 유용합니다.

 

필요한 패키지 설치

sudo apt-get update && sudo apt-get install -y wget unzip

Consul 바이너리 파일 다운로드

curl -fsSL https://releases.hashicorp.com/consul/1.14.4/consul_1.14.4_linux_amd64.zip -o /tmp/consul.zip

압축 해제

unzip /tmp/consul.zip -d /tmp/

권한 설정

chmod +x /tmp/consul

바이너리 파일 이동

mv /tmp/consul /usr/local/bin/consul

사용자 및 그룹 생성

sudo useradd --system --home /etc/consul.d --shell /bin/false consul

필요한 디렉토리 생성

sudo mkdir -p /etc/consul.d /opt/consul /var/log/consul

디렉토리 권한 설정

sudo chown -R consul:consul /etc/consul.d
sudo chown -R consul:consul /opt/consul

기본 설정 파일 작성

sudo tee /etc/consul.d/consul.hcl > /dev/null <<EOF
datacenter = "dc1"
data_dir = "/opt/consul"
log_level = "INFO"
node_name = "consul-server"
server = true
bootstrap_expect = 1
bind_addr = "0.0.0.0"
client_addr = "0.0.0.0"
ui = true
EOF

설정 파일 권한 설정

sudo chown consul:consul /etc/consul.d/consul.hcl
sudo chmod 640 /etc/consul.d/consul.hcl

시스템 서비스 파일 작성

sudo tee /usr/lib/systemd/system/consul.service > /dev/null <<EOF
[Unit]
Description="HashiCorp Consul - A service mesh solution"
Documentation=https://www.consul.io/
Requires=network-online.target
After=network-online.target
ConditionFileNotEmpty=/etc/consul.d/consul.hcl

[Service]
Type=notify
EnvironmentFile=-/etc/consul.d/consul.env
User=consul
Group=consul
ExecStart=/usr/local/bin/consul agent -config-dir=/etc/consul.d/
ExecReload=/bin/kill --signal HUP $MAINPID
KillMode=process
KillSignal=SIGTERM
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

Consul 설정 파일 유효성 검사

sudo consul validate /etc/consul.d/

시스템 데몬 리로드

sudo systemctl daemon-reload

Consul 서비스 시작

sudo systemctl start consul

부팅 시 Consul 서비스 자동 시작 설정

sudo systemctl enable consul

클러스터의 상태와 구성 정보를 확인

Consul 클러스터의 모든 노드를 확인

consul members
Node          Address           Status  Type    Build  Protocol  DC
consul-server 192.168.1.1:8301  alive   server  1.13.0  2         dc1
consul-client 192.168.1.2:8301  alive   client  1.13.0  2         dc1

Consul 서버 클러스터의 Raft 피어 목록을 확인

consul operator raft list-peers
Node           ID                                    Address          State     Voter  RaftProtocol
consul-server1 987a6543-21dc-4b3f-9d2a-1f7f4d3c1e3a  192.168.1.1:8300  leader    true   3
consul-server2 abcdef12-34ab-56cd-78ef-90ab12cd34ef  192.168.1.2:8300  follower  true   3
consul-server3 12345678-90ab-cdef-1234-567890abcdef  192.168.1.3:8300  follower  true   3

Consul 웹 UI 접속

Consul이 설치되고 실행 중이면 기본적으로 웹 UI를 제공합니다. 웹 브라우저에서 http://<서버_IP>:8500으로 접속하여 Consul 웹 UI에 접속할 수 있습니다.

http://<서버_IP>:8500

 

참고URL

- Install Consul : https://developer.hashicorp.com/consul/downloads

- Consul 필수 포트(Required Ports) : https://developer.hashicorp.com/consul/docs/install/ports

 

728x90