GKE에 Consul 배포하기

GKE에 Consul 배포하기 (Deploy Consul on GKE)

이 문서는 Google Cloud의 Google Kubernetes Engine(GKE) 클러스터에 Consul 데이터센터를 배포하는 방법을 알려드릴게요. 배포 후 CLI·UI·API로 Consul을 사용하는 단계까지 차근차근 따라 해볼 수 있어요.

출처: 문서

본문

이 항목은 Google Cloud의 Google Kubernetes Engine(GKE) 클러스터에 Consul 데이터센터를 배포하는 방법을 설명합니다. Consul을 배포한 후 CLI, UI 및/또는 API를 사용하여 Consul과 상호 작용합니다.

사전 요구 사항 (Prerequisites)

GKE에 Consul을 배포하려면 다음이 필요합니다:

Google Cloud CLI 초기화 (Initialize Google Cloud CLI)

Google Cloud CLI를 초기화합니다.

$ gcloud init

서비스 계정 인증 (Service account authentication, optional)

GCP IAM 서비스 계정을 만들고 명령줄에서 이 계정으로 인증해야 합니다.

GCP IAM 서비스 계정 key-file을 획득한 후 gcloud로 인증합니다.

$ gcloud auth activate-service-account --key-file="<path-to/my-consul-service-account.json>"

GKE 클러스터 생성 (Create a GKE cluster)

공식 Consul Helm 차트 또는 Consul K8S CLI를 사용하여 Consul을 배포하려면 최소한 3개 노드 GKE 클러스터가 필요합니다. GKE 문서 [https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-cluster]에 따라 GKE에 3개 노드 클러스터를 만듭니다.

kubectl을 클러스터와 통신하도록 구성 (Configure kubectl to talk to your cluster)

kubectl을 Kubernetes 클러스터에 연결하도록 구성합니다. 이 명령은 자격 증명을 다운로드하고 Kubernetes CLI가 이를 사용하도록 구성합니다. my-consul-cluster, us-west1-b 및 my-project를 클러스터 이름, 영역(zone), 프로젝트 이름으로 바꾸세요.

$ gcloud container clusters get-credentials my-consul-cluster --zone us-west1-b --project my-project

Kubernetes 클러스터에 연결되었는지 확인합니다.

$ kubectl cluster-info
Kubernetes master is running at https://<your GKE ip(s)>
GLBCDefaultBackend is running at https://<your GKE ip(s)>/api/v1/namespaces/kube-system/services/default-http-backend:http/proxy
Heapster is running at https://<your GKE ip(s)>/api/v1/namespaces/kube-system/services/heapster/proxy
KubeDNS is running at https://<your GKE ip(s)>/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
Metrics-server is running at https://<your GKE ip(s)>/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy

To further debug and diagnose cluster problems, use `kubectl cluster-info dump`.

Consul 배포 (Deploy Consul)

공식 Consul Helm 차트 또는 Consul K8S CLI를 사용하여 완전한 Consul 데이터센터를 배포할 수 있습니다. 기본적으로 이 방법들은 총 3개의 Consul 서버를 설치합니다. 이 설치 옵션에 대해 자세히 알아보려면 Consul Kubernetes 설치 문서 [/consul/docs/deploy/server/k8s/helm]를 검토하세요.

values 파일 생성 (Create a values file)

파일 내용은 GKE에 Workload Identity Federation(WIF)을 사용하는지 여부에 따라 다릅니다. WIF가 비활성화된 경우 다음 Helm 값으로 Kubernetes에 Consul을 배포하기에 충분합니다.

values.yaml

# Contains values that affect multiple components of the chart.
global:
  # The main enabled/disabled setting.
  # If true, servers, clients, Consul DNS and the Consul UI will be enabled.
  enabled: true
  # The prefix used for all resources created in the Helm chart.
  name: consul
  # The name of the datacenter that the agents should register as.
  datacenter: dc1
  # Enables TLS across the cluster to verify authenticity of the Consul servers and clients.
  tls:
    enabled: true
  # Enables ACLs across the cluster to secure access to data and APIs.
  acls:
    # If true, automatically manage ACL tokens and policies for all Consul components.
    manageSystemACLs: true
# Configures values that configure the Consul server cluster.
server:
  enabled: true
  # The number of server agents to run. This determines the fault tolerance of the cluster.
  replicas: 3
# Contains values that configure the Consul UI.
ui:
  enabled: true
  # Registers a Kubernetes Service for the Consul UI as a LoadBalancer.
  service:
    type: LoadBalancer
# Configures and installs the automatic Consul Connect sidecar injector.
connectInject:
  enabled: true

Workload Identity Federation(WIF)을 사용하여 GKE 클러스터와 GCP 리소스 간의 접근을 관리하는 경우 Consul 클라이언트 서비스 계정에 주석(annotation)을 추가해야 합니다. GSA_NAME과 PROJECT_ID를 GCP 서비스 계정 이름과 프로젝트 ID로 바꾸세요.

values.yaml

# Contains values that affect multiple components of the chart.
global:
  # The main enabled/disabled setting.
  # If true, servers, clients, Consul DNS and the Consul UI will be enabled.
  enabled: true
  # The prefix used for all resources created in the Helm chart.
  name: consul
  # The name of the datacenter that the agents should register as.
  datacenter: dc1
  # Enables TLS across the cluster to verify authenticity of the Consul servers and clients.
  tls:
    enabled: true
  # Enables ACLs across the cluster to secure access to data and APIs.
  acls:
    # If true, automatically manage ACL tokens and policies for all Consul components.
    manageSystemACLs: true
# Configures values that configure the Consul server cluster.
server:
  enabled: true
  # The number of server agents to run. This determines the fault tolerance of the cluster.
  replicas: 3
client:
  serviceAccount:
    annotations: |
      "iam.gke.io/gcp-service-account": "GSA_NAME@PROJECT_ID.iam.gserviceaccount.com"
# Contains values that configure the Consul UI.
ui:
  enabled: true
  # Registers a Kubernetes Service for the Consul UI as a LoadBalancer.
  service:
    type: LoadBalancer
# Configures and installs the automatic Consul Connect sidecar injector.
connectInject:
  enabled: true

사용자 지정 서비스 계정 생성 (Create a custom service account)

WIF를 사용할 때 consul-server-acl-init 컨테이너는 Google Compute 리소스를 조회하는 데 필요한 권한이 있는 사용자 지정 서비스 계정이 필요합니다.

먼저 Helm 템플릿과 Consul values 파일을 사용하여 GCP IAM 서비스 계정 정의를 생성합니다.

$ helm template consul hashicorp/consul -n consul -f values.yaml -s templates/server-acl-init-serviceaccount.yaml | tee consul-gcp-service-account.yaml
---
# Source: consul/templates/server-acl-init-serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: consul-server-acl-init
  namespace: consul
  labels:
    app: consul
    chart: consul-helm
    heritage: Helm
    release: consul
    component: server-acl-init

그런 다음 Consul 네임스페이스를 만들고 네임스페이스 이름이 Consul을 배포하는 데 사용할 이름과 일치하는지 확인합니다. 기본적으로 Kubernetes의 Consul은 consul 네임스페이스를 사용합니다.

$ kubectl create namespace consul
namespace/consul created

마지막으로 서비스 계정 정의를 네임스페이스에 적용합니다.

$ kubectl apply -f consul-gcp-service-account.yaml
serviceaccount/consul-server-acl-init created

클러스터에 Consul 설치 (Install Consul in your cluster)

이제 공식 Consul Helm 차트 또는 Consul K8S CLI를 사용하여 Kubernetes 클러스터에 완전한 Consul 데이터센터를 배포할 수 있습니다.

Consul K8S CLI (Mac & Linux)

consul-k8s로 AKS 클러스터에 Consul을 설치합니다. 메시지가 표시되면 y로 설치를 확인합니다.

$ consul-k8s install -config-file=values.yaml -set global.image=hashicorp/consul:1.14.0

추가 설정에 대해 자세히 알아보려면 공식 Consul K8S CLI 문서 [/consul/docs/reference/cli/consul-k8s]를 검토하세요.

Helm

Helm으로 kind 클러스터에 Consul을 설치합니다. 메시지가 표시되면 y로 설치를 확인합니다.

$ helm install --values values.yaml consul hashicorp/consul --create-namespace --namespace consul --version "1.0.0"

기본 설정에 대해 자세히 알아보려면 공식 Helm 차트 값 [/consul/docs/reference/k8s/helm#configuration-values]을 검토하세요.

Consul 리소스가 성공적으로 생성되었는지 확인합니다.

$ kubectl get pods --namespace consul
NAME                                           READY   STATUS    RESTARTS   AGE
consul-connect-injector-6fc8d669b8-2n82l       1/1     Running   0          2m34s
consul-connect-injector-6fc8d669b8-9mqfm       1/1     Running   0          2m34s
consul-controller-554c7f79c4-2xc64             1/1     Running   0          2m34s
consul-server-0                                1/1     Running   0          2m34s
consul-server-1                                1/1     Running   0          2m34s
consul-server-2                                1/1     Running   0          2m34s
consul-webhook-cert-manager-64889c4964-wxc9b   1/1     Running   0          2m34s

Consul 클러스터와 상호 작용하도록 CLI 구성 (Configure your CLI to interact with Consul cluster)

이 섹션에서는 Consul CLI가 Consul 클러스터와 상호 작용할 수 있도록 터미널에 환경 변수를 설정합니다. Consul CLI는 이러한 환경 변수를 동작 기본값으로 읽으며, consul 명령을 실행할 때 이 값을 참조합니다.

토큰은 사용자, 서비스, Consul 에이전트를 인증하는 데 사용되는 ACL 시스템의 아티팩트입니다. 이 Consul 데이터센터에서 ACL이 활성화되어 있으므로 리소스에 대한 접근을 요청하는 엔티티는 리소스에 대한 권한을 부여하는 정책, 서비스 ID 또는 노드 ID와 연결된 토큰을 포함해야 합니다. ACL 시스템은 토큰을 확인하고 연결된 권한에 따라 리소스에 대한 접근을 허용하거나 거부합니다. 부트스트랩 토큰은 모든 리소스와 API에 대한 무제한 권한을 가집니다.

해당 Kubernetes 시크릿에서 ACL 부트스트랩 토큰을 검색하고 환경 변수로 설정합니다.

$ export CONSUL_HTTP_TOKEN=$(kubectl get --namespace consul secrets/consul-bootstrap-acl-token --template={{.data.token}} | base64 -d)

Consul 대상 주소를 설정합니다.

$ export CONSUL_HTTP_ADDR=https://$(kubectl get services/consul-ui --namespace consul -o jsonpath='{.status.loadBalancer.ingress[0].ip}')

Consul 클러스터와의 통신을 단순화하기 위해 SSL 검증 확인을 제거합니다.

$ export CONSUL_HTTP_SSL_VERIFY=false

참고

프로덕션 환경에서는 이 SSL 검증을 true로 유지하는 것이 좋습니다. 개발 환경과 데모 목적에서 TLS가 구성되지 않은 Consul 클러스터가 있는 경우에만 이 검증을 제거하세요.

Consul 서비스 보기 (View Consul services)

이 섹션에서는 CLI, UI 및/또는 API를 사용하여 Consul 서비스를 보고 서비스 메시의 세부 사항을 탐색합니다.

CLI

CLI 명령 consul catalog services를 실행하여 Consul에 등록된 서비스 목록을 반환합니다. Consul 클러스터에서 실행 중인 유일한 서비스가 consul뿐이므로 이 서비스만 반환되는 것을 확인할 수 있습니다.

$ consul catalog services
consul

에이전트는 서버 또는 클라이언트 모드로 실행됩니다. 서버 에이전트는 서비스 및 노드 IP 주소, 헬스 체크, 구성을 포함한 모든 상태 정보를 저장합니다. 클라이언트 에이전트는 데이터센터의 대부분을 구성하는 경량 프로세스입니다. 서버 에이전트에 서비스 헬스 상태를 보고합니다. 서비스가 실행되는 모든 포드에서 클라이언트가 실행되어야 합니다.

CLI 명령 consul members를 실행하여 환경의 Consul 에이전트 목록을 반환합니다.

$ consul members
Node             Address          Status  Type    Build        Protocol  DC   Partition  Segment
consul-server-0  10.0.4.117:8301  alive   server  1.14.0beta1  2         dc1  default    <all>
consul-server-1  10.0.5.11:8301   alive   server  1.14.0beta1  2         dc1  default    <all>
consul-server-2  10.0.4.55:8301   alive   server  1.14.0beta1  2         dc1  default    <all>

UI

토큰 값을 터미널에 출력하고 클립보드에 복사합니다. 이 ACL 토큰을 사용하여 Consul UI에서 인증합니다.

$ echo $CONSUL_HTTP_TOKEN
fe0dd5c3-f2e1-81e8-cde8-49d26cee5efc

별도의 터미널 창을 열고 대상으로 consul-ui 서비스 이름을 사용하여 kubectl port-forward로 Consul UI를 노출합니다. 기본적으로 Consul UI는 TLS를 활성화할 때 포트 6443, TLS가 비활성화될 때 포트 8500에서 실행됩니다.

$ kubectl port-forward svc/consul-ui --namespace consul 6443:443

브라우저에서 https://localhost:6443 [https://localhost:6443]을 열어 Consul UI를 찾습니다. 이 환경은 리소스에 자체 서명된 TLS 인증서를 사용하므로 인증서 경고를 클릭하여 계속 진행합니다.

왼쪽 탐색 창에서 Services를 클릭하여 배포된 서비스를 검토합니다. 현재는 consul 서비스만 찾을 수 있습니다.

기본적으로 익명(anonymous) ACL 정책은 Consul 서비스, 노드, 인텐션의 내용을 볼 수 있게 허용합니다. Consul UI에서 변경하고 더 많은 세부 정보를 보려면 오른쪽 상단의 Log In을 클릭하고 부트스트랩 ACL 토큰을 입력하세요.

ACL 토큰으로 성공적으로 인증하면 추가 Consul 구성 요소를 보고 UI에서 변경할 수 있게 됩니다. 왼쪽 탐색 창의 Access Controls 섹션에서 더 많은 옵션을 보고 관리할 수 있음을 확인할 수 있습니다.

왼쪽 탐색 창에서 Nodes를 클릭합니다.

에이전트는 서버 또는 클라이언트 모드로 실행됩니다. 서버 에이전트는 서비스 및 노드 IP 주소, 헬스 체크, 구성을 포함한 모든 상태 정보를 저장합니다. 클라이언트 에이전트는 데이터센터의 대부분을 구성하는 경량 프로세스입니다. 서버 에이전트에 서비스 헬스 상태를 보고합니다. 서비스가 실행되는 모든 포드에서 클라이언트가 실행되어야 합니다.

API

Consul에 등록된 서비스 목록을 봅니다.

$ curl -k \
    --header "X-Consul-Token: $CONSUL_HTTP_TOKEN" \
    $CONSUL_HTTP_ADDR/v1/catalog/services

샘플 출력:

{"consul":[]}

에이전트는 서버 또는 클라이언트 모드로 실행됩니다. 서버 에이전트는 서비스 및 노드 IP 주소, 헬스 체크, 구성을 포함한 모든 상태 정보를 저장합니다. 클라이언트 에이전트는 데이터센터의 대부분을 구성하는 경량 프로세스입니다. 서버 에이전트에 서비스 헬스 상태를 보고합니다. 서비스가 실행되는 모든 포드에서 클라이언트가 실행되어야 합니다.

환경의 서버 및 클라이언트 Consul 에이전트 목록을 봅니다.

$ curl -k \
    --header "X-Consul-Token: $CONSUL_HTTP_TOKEN" \
    $CONSUL_HTTP_ADDR/v1/agent/members\?pretty

샘플 출력:

[
  {
    "Name": "consul-server-0",
    "Addr": "10.244.0.13",
    "Port": 8301,
    "Tags": {
      "acls": "1",
      "bootstrap": "1",
      "build": "1.14.0",
      "dc": "dc1",
      "ft_fs": "1",
      "ft_si": "1",
      "grpc_port": "8502",
      "id": "8016fc4d-767f-8552-b018-0812228bd135",
      "port": "8300",
      "raft_vsn": "3",
      "role": "consul",
      "segment": "",
      "use_tls": "1",
      "vsn": "2",
      "vsn_max": "3",
      "vsn_min": "2",
      "wan_join_port": "8302"
    },
    "Status": 1,
    "ProtocolMin": 1,
    "ProtocolMax": 5,
    "ProtocolCur": 2,
    "DelegateMin": 2,
    "DelegateMax": 5,
    "DelegateCur": 4
  }
  ## ...
]

Consul 카탈로그에 나열된 모든 서비스는 확장성 문제를 단순화하고 애플리케이션 탄력성을 개선하는 Consul의 서비스 디스커버리 기능으로 지원됩니다. 자세한 내용은 서비스 디스커버리 개요 [/consul/docs/use-case/service-discovery] 페이지를 검토하세요.

다음 단계 (Next steps)

Google Kubernetes Engine(GKE) 클러스터에 Consul 데이터센터를 배포하는 방법을 배웠습니다. Consul을 배포한 후 CLI, UI, API로 Consul과 상호 작용했습니다.

배포 모범 사례에 대해 자세히 알아보려면 Kubernetes 참조 아키텍처 튜토리얼 [/consul/tutorials/kubernetes/kubernetes-reference-architecture]을 검토하세요.

더 알아보기 (Learn more)