Consul 安装说明(Linux)

一、环境准备

在开始部署 Consul 服务之前,需要确保 Linux 环境满足以下基本要求:

1、系统要求

Consul 支持大多数 Linux 发行版,以下是一些常见的系统要求:

  • 操作系统:64 位操作系统,如 Ubuntu 16.04+、CentOS 7 + 等。
  • CPU 架构:x86_64 或 ARM。
  • 内存:至少 512MB RAM,推荐 1GB 或更多,具体取决于预期的工作负载。
  • 硬盘空间:至少 200MB 的可用硬盘空间。

2、网络配置

确保 Linux 服务器的网络配置正确,以下是一些网络要求:

  • 防火墙:确保 Consul 使用的端口(默认为 8300、8301、8302、8500 等)在防火墙上开放。
  • DNS:确保服务器可以解析 Consul 集群中的节点名称或 IP 地址。
  • 时间同步:建议配置 NTP 服务以确保集群中的所有节点时间同步。

3、依赖安装

Consul 不需要特殊的依赖,但是建议安装以下工具来帮助安装和管理 Consul:

  • wget/curl:用于下载 Consul 的二进制文件。
  • tar:用于解压下载的 Consul 包。
  • systemd(可选):如果使用 systemd 来管理 Consul 服务,需要确保它已经安装。

在确保以上环境准备就绪后,可以开始 Consul 的安装和配置过程。

二、Consul 安装

Consul 的安装可以通过多种方式进行,包括包管理器、源代码编译以及直接下载预编译的二进制文件。下面介绍使用包管理器和直接下载二进制文件两种常见方法。

下载地址:Install | Consul | HashiCorp Developer

1、通过包管理器下载

Ubuntu/Debian
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) 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 update && sudo apt install consul
CentOS/RHEL
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install consul
Fedora 40
sudo dnf install -y dnf-plugins-core
sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
sudo dnf -y install consul
Fedora 41
sudo dnf install -y dnf-plugins-core
sudo dnf config-manager addrepo --from-repofile=https://rpm.releases.hashicorp.com/fedora/hashicorp.repo
sudo dnf -y install consul
Amazon Linux
sudo yum install -y yum-utils shadow-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum -y install consul
Homebrew
brew tap hashicorp/tap
brew install hashicorp/tap/consul

2、二进制文件下载

如果希望直接下载预编译的二进制文件,可以访问 Consul 的官方网站或 GitHub 发布页面获取最新版本的二进制文件。以下是一个示例命令:

VERSION="1.20.5"
wget https://releases.hashicorp.com/consul/${VERSION}/consul_${VERSION}_linux_amd64.zip
unzip consul_${VERSION}_linux_amd64.zip
sudo mv consul /usr/local/bin/

确保替换 VERSION 变量为 Consul 的最新版本号。

3、查看 Consul 是否安装成功

在安装 Consul 之后,可以通过运行 consul –version 来验证安装是否成功。如果返回了 Consul 的版本信息,则表示 Consul 已经成功安装。

[root@localhost ~]# consul version

Consul v1.20.5
Revision 74efe419
Build Date 2025-03-11T10:16:18Z
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)

三、Consul 配置

Consul 的配置文件决定了 Consul 的行为和服务集群的拓扑结构。配置 Consul 涉及到编辑配置文件和设置环境变量。以下是如何配置 Consul 的详细步骤。

1、配置文件结构

Consul 的配置文件通常是一个名为 consul.json 的 JSON 文件,也可以是 HCL(HashiCorp Configuration Language)格式的.hcl 文件。配置文件可以包含以下部分:

  • agent:配置 Consul agent 的行为。
  • server:配置 Consul server 节点的特定设置。
  • client:配置 Consul client 节点的特定设置。
  • cluster:配置集群层面的设置,如数据中心的名称。
  • acl:访问控制列表的配置,用于权限管理。
  • encrypt:配置集群加密。

通过 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=..."]

2、修改配置

vim /etc/consul.d/consul.hcl

# 数据中心名称
datacenter = "consul-cluster"

# 节点名称
node_name = "my-consul-sever"

# 启用当前节点作为 Consul 服务器
server = true

# 设置预期的服务器节点数量,当达到这个数量时,集群将自动启动
bootstrap_expect = 1

# 指定 Consul 数据的存储目录
data_dir = "Data"

# 设置当前节点的绑定地址(用于集群内的通信)
bind_addr = "127.0.0.1"

# 设置允许的客户端连接地址
client_addr = "0.0.0.0"

# 启用 Consul Web UI
ui_config {
  enabled = true
}

# 配置端口
ports {
  serf_lan = 8301   # 默认 Serf LAN 端口
  serf_wan = 8302   # 默认 Serf WAN 端口
  server = 8300     # Consul 服务器端口
  http = 8500       # HTTP API 端口(UI 端口)
  dns = 8600        # DNS 端口
}

# 设置日志级别(可选,默认为 "INFO")
log_level = "INFO"

4、配置 Consul 服务(脚本安装可忽略)

如果使用 systemd 来管理 Consul 服务,可以创建一个 systemd 服务文件来指定 Consul 的配置文件路径和其他启动参数。以下是一个示例的 systemd 服务文件 /lib/systemd/system/consul.service

[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/bin/consul agent -config-dir=/etc/consul.d/
ExecStart=/usr/bin/consul agent -config-file=/etc/consul.d/consul.hcl
ExecReload=/bin/kill --signal HUP $MAINPID
KillMode=process
KillSignal=SIGTERM
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

服务的配置文件通常位于 /etc/systemd/system//lib/systemd/system/ 目录下。这些文件通常以 .service 结尾。

[Unit]
Description=Consul
Documentation=https://www.consul.io/docs/
Wants=network-online.target
After=network-online.target

[Service]
#ExecStart=/usr/local/bin/consul agent -config-dir /etc/consul.d/
ExecStart=/usr/local/bin/consul agent -config-file=/etc/consul.d/consul.hcl
ExecReload=/bin/kill -HUP $MAINPID
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

在这个服务文件中,-config-dir 参数指定了 Consul 的配置文件所在的目录。

完成配置文件的创建和 systemd 服务文件的设置后,可以通过启动 Consul 服务来应用这些配置:

sudo systemctl start consul
sudo systemctl enable consul

使用 systemctl status consul 可以检查 Consul 服务的状态,确保它正在运行。

配置 Consul 是确保服务按预期运行的关键步骤,正确的配置可以最大化 Consul 的功能并保障集群的安全和稳定性。

四. 启动 Consul 服务

在完成 Consul 的安装和配置之后,接下来需要启动 Consul 服务。Consul 可以通过命令行直接启动,也可以通过 systemd 服务管理器来启动。以下是启动 Consul 服务的两种方法。

4.1 命令行启动

如果只是进行测试或者临时启动 Consul,可以使用命令行直接启动 Consul agent。以下是一个基本的启动命令:

consul agent -dev

这条命令会启动一个开发模式的 Consul agent,它适用于单节点开发和测试。对于生产环境,你需要指定配置文件和相应的参数。

如果要使用配置文件启动 Consul,可以使用以下命令:

consul agent -config-file /path/to/consul.hcl

确保替换 /path/to/consul.hcl 为你的 Consul 配置文件的实际路径。

4.2 使用 systemd 启动

在生产环境中,推荐使用 systemd 来管理 Consul 服务,这样可以确保服务在系统重启后自动启动,并且可以方便地进行服务管理。

首先,确保已经创建了 Consul 的 systemd 服务文件,如上一节中提到的 consul.service 。然后,可以使用以下命令启动 Consul 服务:

sudo systemctl start consul

要使 Consul 服务在系统启动时自动启动,可以使用以下命令:

sudo systemctl enable consul

启动服务后,可以使用以下命令检查 Consul 服务的状态:

sudo systemctl status consul

如果 Consul 服务正在运行,你将看到服务的状态信息。此外,你也可以通过 Consul 的 HTTP API 或者 CLI 命令来检查集群的状态和成员信息。

consul members

这将列出集群中所有节点的状态信息,包括节点的角色(server 或 client)、地址和健康状态。

启动 Consul 服务是部署过程中的关键步骤,确保 Consul 服务正常运行是后续进行服务注册和发现的基础。

参考资料

作者:Jeebiz  创建时间:2025-04-12 14:49
最后编辑:Jeebiz  更新时间:2025-04-13 16:32