이재홍의 언제나 최신 Kubernetes - Unit 7.3 kOps로 클러스터 생성하기

저작권 안내
  • 책 또는 웹사이트의 내용을 복제하여 다른 곳에 게시하는 것을 금지합니다.
  • 책 또는 웹사이트의 내용을 발췌, 요약하여 강의 자료, 발표 자료, 블로그 포스팅 등으로 만드는 것을 금지합니다.

AWS에서 EC2로 Kubernetes 클러스터 구축하기

이재홍 http://www.pyrasis.com

kOps로 클러스터 생성하기

AWS에 kOps로 Kubernetes 클러스터를 생성하는 구성도는 다음과 같습니다.

그림 7-5 kOps로 Kubernetes 클러스터 생성

S3 버킷 생성하기

kOps로 클러스터를 만들기 전에 인증서와 설정 정보를 저장할 S3 버킷을 만들어야 합니다. 다음 과정으로 S3 버킷을 생성합니다.

  1. AWS 콘솔 접속
  2. S3으로 이동
  3. 버킷 만들기 버튼 클릭
  4. 버킷 이름에 clusters.k8s.hello.com 입력(clusters.k8s.hello.com은 제가 생성했으므로 각자 다른 것을 입력합니다. 예: clusters.k8s.hello.com-1). 만약 도메인을 구입했다면 clusters.k8s.<구입한 도메인>으로 입력합니다(<S3 버킷 이름>).
  5. AWS 리전은 ap-northeast-2로 설정
  6. 버킷 만들기 버튼 클릭

EC2 키 페어 생성하기

이제 EC2 인스턴스에 접속할 키 페어를 생성할 차례입니다. 다음 과정으로 키 페어를 생성하고 다운로드합니다.

  1. AWS 콘솔 접속
  2. EC2로 이동
  3. 키 페어 메뉴 클릭
  4. 키 페어 생성 버튼 클릭
  5. 이름에 hello 입력
  6. 프라이빗 키 파일 형식을 .pem 선택
  7. 키 페어 생성 버튼 클릭

이렇게 하면 hello.pem 파일이 다운로드됩니다.

다음 명령을 실행하여 Private Key인 hello.pem 에서 Public Key hello.pub를 추출해냅니다.

macOS, 리눅스
$ chmod 400 ./hello.pem
$ ssh-keygen -y -f ./hello.pem > hello.pub
윈도우 PowerShell
icacls .\hello.pem /reset
icacls .\hello.pem /inheritance:r
icacls .\hello.pem /c /t /grant ${env:UserName}:F
ssh-keygen -y -f .\hello.pem | Out-File -Encoding ascii hello.pub

Route 53 호스팅 영역 생성하기

kOps로 쿠버네티스 클러스터를 생성하려면 Route 53 호스팅 영역(hosted zone)이 필요합니다.

도메인을 구입한 경우

도메인을 구입했다면 구입한 도메인에 대한 호스팅 영역을 생성합니다. AWS에서 도메인을 구입했다면 자동으로 생성됩니다.

  1. AWS 콘솔 접속
  2. Route 53으로 이동
  3. 호스팅 영역 메뉴 클릭
  4. 호스팅 영역 생성 버튼 클릭
  5. 도메인 이름에 <구입한 도메인> 입력
  6. 호스팅 영역 생성 버튼 클릭

도메인을 구입하지 않은 경우

도메인을 구입하지 않은 경우 프라이빗 호스팅 영역을 생성합니다.

  1. AWS 콘솔 접속
  2. Route 53으로 이동
  3. 호스팅 영역 메뉴 클릭
  4. 호스팅 영역 생성 버튼 클릭
  5. 도메인 이름에 hello.com 입력
  6. 유형을 프라이빗 호스팅 영역 선택
  7. 리전을 아시아 태평양(서울) [ap-northeast-2] 선택
  8. VPC ID는 기본 VPC 선택
  9. 호스팅 영역 생성 버튼 클릭

YAML 파일 생성하기

kOps는 커맨드라인 옵션을 사용하여 설정을 하는 방식이지만, 설정 파일을 Git 등으로 관리할 수 있도록 YAML로 만듭니다.

도메인을 구입한 경우

아래 s3://clusters.k8s.<구입한 도메인>은 본인이 생성한 S3 버킷의 이름으로 바꿔줍니다. 그리고 --name과 YAML 파일명에는 k8s.ap-northeast-2.aws.<구입한 도메인>을 입력합니다.

macOS, 리눅스
$ export KOPS_STATE_STORE=s3://clusters.k8s.<구입한 도메인>
$ kops create cluster --name=k8s.ap-northeast-2.aws.<구입한 도메인> --cloud=aws --zones='ap-northeast-2a,ap-northeast-2b,ap-northeast-2c' --dry-run -o yaml > k8s.ap-northeast-2.aws.<구입한 도메인>.yaml
윈도우 PowerShell
$env:KOPS_STATE_STORE="s3://clusters.k8s.<구입한 도메인>"
kops create cluster --name=k8s.ap-northeast-2.aws.<구입한 도메인> --cloud=aws --zones='ap-northeast-2a,ap-northeast-2b,ap-northeast-2c' --dry-run -o yaml > k8s.ap-northeast-2.aws.<구입한 도메인>.yaml

인그레스를 생성했을 때 Route 53에 레코드를 자동 생성할 수 있도록 k8s.ap-northeast-2.aws.<구입한 도메인>.yaml 파일을 다음과 같이 수정해줍니다. 즉, spec 아래에 externalDns.watchIngresstrue로 설정해줍니다.

k8s.ap-northeast-2.aws.<구입한 도메인>.yaml
apiVersion: kops.k8s.io/v1alpha2
kind: Cluster
metadata:
  creationTimestamp: null
  name: k8s.ap-northeast-2.aws.<구입한 도메인>
spec:
  externalDns:
    watchIngress: true
  api:
    dns: {}
  authorization:
    rbac: {}

도메인을 구입하지 않은 경우

아래 s3://<S3 버킷 이름>은 본인이 생성한 S3 버킷의 이름으로 바꿔줍니다. 하지만, --name과 YAML 파일명에는 k8s.ap-northeast-2.aws.hello.com을 그대로 입력해야 합니다.

macOS, 리눅스
$ export KOPS_STATE_STORE=s3://<S3 버킷 이름>
$ kops create cluster --name=k8s.ap-northeast-2.aws.hello.com --cloud=aws --zones='ap-northeast-2a,ap-northeast-2b,ap-northeast-2c' --dns private --dry-run -o yaml > k8s.ap-northeast-2.aws.hello.com.yaml
윈도우 PowerShell
$env:KOPS_STATE_STORE="s3://<S3 버킷 이름>"
kops create cluster --name=k8s.ap-northeast-2.aws.hello.com --cloud=aws --zones='ap-northeast-2a,ap-northeast-2b,ap-northeast-2c' --dns private --dry-run -o yaml > k8s.ap-northeast-2.aws.hello.com.yaml

YAML 파일로 클러스터 생성하기

이제 앞에서 만든 YAML 파일로 클러스터를 생성해보겠습니다. 먼저 다음 명령을 실행하여 S3에 클러스터 설정 및 sshpublickey를 적용합니다. 아직은 EC2 인스턴스가 생성되지 않습니다.

도메인을 구입한 경우

macOS, 리눅스
$ cat ./k8s.ap-northeast-2.aws.<구입한 도메인>.yaml | kops create -f -
$ kops create sshpublickey --name k8s.ap-northeast-2.aws.<구입한 도메인> -i hello.pub
윈도우 PowerShell
cat .\k8s.ap-northeast-2.aws.<구입한 도메인>.yaml | kops create -f -
kops create sshpublickey --name k8s.ap-northeast-2.aws.<구입한 도메인> -i hello.pub

이상이 없으면 실제로 적용을 해봅니다. 이제 실제로 EC2 인스턴스가 생성됩니다.

$ kops update cluster --name k8s.ap-northeast-2.aws.<구입한 도메인> --yes

*********************************************************************************

A new kops version is available: 1.25.2
Upgrading is recommended
More information: https://github.com/kubernetes/kops/blob/master/permalinks/upgrade_kops.md#1.25.2

*********************************************************************************

I1125 12:16:09.581824    9528 executor.go:111] Tasks: 0 done / 109 total; 48 can run
W1125 12:16:09.693436    9528 vfs_castore.go:379] CA private key was not found
I1125 12:16:09.699437    9528 keypair.go:225] Issuing new certificate: "etcd-manager-ca-events"
I1125 12:16:09.712633    9528 keypair.go:225] Issuing new certificate: "apiserver-aggregator-ca"
I1125 12:16:09.727296    9528 keypair.go:225] Issuing new certificate: "etcd-peers-ca-events"
I1125 12:16:09.730567    9528 keypair.go:225] Issuing new certificate: "etcd-manager-ca-main"
I1125 12:16:09.732792    9528 keypair.go:225] Issuing new certificate: "etcd-peers-ca-main"
I1125 12:16:09.733800    9528 keypair.go:225] Issuing new certificate: "etcd-clients-ca"
W1125 12:16:09.734626    9528 vfs_castore.go:379] CA private key was not found
I1125 12:16:09.757601    9528 keypair.go:225] Issuing new certificate: "kubernetes-ca"
I1125 12:16:09.765643    9528 keypair.go:225] Issuing new certificate: "service-account"
I1125 12:16:10.774088    9528 executor.go:111] Tasks: 48 done / 109 total; 23 can run
I1125 12:16:11.666874    9528 executor.go:111] Tasks: 71 done / 109 total; 30 can run
I1125 12:16:12.317385    9528 executor.go:111] Tasks: 101 done / 109 total; 4 can run
I1125 12:16:13.289549    9528 executor.go:155] No progress made, sleeping before retrying 4 task(s)
I1125 12:16:23.304076    9528 executor.go:111] Tasks: 101 done / 109 total; 4 can run
I1125 12:16:25.822231    9528 executor.go:111] Tasks: 105 done / 109 total; 4 can run
I1125 12:16:25.919122    9528 executor.go:111] Tasks: 109 done / 109 total; 0 can run
I1125 12:16:27.221437    9528 dns.go:238] Pre-creating DNS records
I1125 12:16:27.817503    9528 update_cluster.go:326] Exporting kubeconfig for cluster
kOps has set your kubectl context to k8s.ap-northeast-2.aws.<구입한 도메인>
W1125 12:16:27.845592    9528 update_cluster.go:350] Exported kubeconfig with no user authentication; use --admin, --user or --auth-plugin flags with `kops export kubeconfig`

Cluster is starting.  It should be ready in a few minutes.

Suggestions:
 * validate cluster: kops validate cluster --wait 10m
 * list nodes: kubectl get nodes --show-labels
 * ssh to the master: ssh -i ~/.ssh/id_rsa ubuntu@api.k8s.ap-northeast-2.aws.<구입한 도메인>
 * the ubuntu user is specific to Ubuntu. If not using Ubuntu please use the appropriate user based on your OS.
 * read about installing addons at: https://kops.sigs.k8s.io/addons.

AWS 콘솔에서 EC2 인스턴스 목록을 확인해보면 마스터와 워커 노드들이 생성되고 있을 것입니다.

다음 명령을 입력하여 ~/.kube/config에 방금 생성한 클러스터의 설정을 추가합니다.

$ kops export kubeconfig --admin

잠시 기다리면 EC2 인스턴스가 생성되고 클러스터가 초기화됩니다. kubectl get nodes 명령을 입력하여 노듣 목록을 출력해봅니다.

$ kubectl get nodes
NAME                  STATUS   ROLES           AGE    VERSION
i-01a4d885fd48acc61   Ready    control-plane   4m4s   v1.25.4
i-082f35a3d294a5e7d   Ready    node            54s    v1.25.4
i-0c48a73869254c456   Ready    node            37s    v1.25.4
i-0e5dad97f6500d40a   Ready    node            51s    v1.25.4

도메인을 구입하지 않은 경우

macOS, 리눅스
$ cat ./k8s.ap-northeast-2.aws.hello.com.yaml | kops create -f -
$ kops create sshpublickey --name k8s.ap-northeast-2.aws.hello.com -i hello.pub
윈도우 PowerShell
cat .\k8s.ap-northeast-2.aws.hello.com.yaml | kops create -f -
kops create sshpublickey --name k8s.ap-northeast-2.aws.hello.com -i hello.pub

이상이 없으면 실제로 적용을 해봅니다. 이제 실제로 EC2 인스턴스가 생성됩니다.

$ kops update cluster --name k8s.ap-northeast-2.aws.hello.com --yes

*********************************************************************************

A new kops version is available: 1.25.2
Upgrading is recommended
More information: https://github.com/kubernetes/kops/blob/master/permalinks/upgrade_kops.md#1.25.2

*********************************************************************************

I1125 12:16:09.581824    9528 executor.go:111] Tasks: 0 done / 109 total; 48 can run
W1125 12:16:09.693436    9528 vfs_castore.go:379] CA private key was not found
I1125 12:16:09.699437    9528 keypair.go:225] Issuing new certificate: "etcd-manager-ca-events"
I1125 12:16:09.712633    9528 keypair.go:225] Issuing new certificate: "apiserver-aggregator-ca"
I1125 12:16:09.727296    9528 keypair.go:225] Issuing new certificate: "etcd-peers-ca-events"
I1125 12:16:09.730567    9528 keypair.go:225] Issuing new certificate: "etcd-manager-ca-main"
I1125 12:16:09.732792    9528 keypair.go:225] Issuing new certificate: "etcd-peers-ca-main"
I1125 12:16:09.733800    9528 keypair.go:225] Issuing new certificate: "etcd-clients-ca"
W1125 12:16:09.734626    9528 vfs_castore.go:379] CA private key was not found
I1125 12:16:09.757601    9528 keypair.go:225] Issuing new certificate: "kubernetes-ca"
I1125 12:16:09.765643    9528 keypair.go:225] Issuing new certificate: "service-account"
I1125 12:16:10.774088    9528 executor.go:111] Tasks: 48 done / 109 total; 23 can run
I1125 12:16:11.666874    9528 executor.go:111] Tasks: 71 done / 109 total; 30 can run
I1125 12:16:12.317385    9528 executor.go:111] Tasks: 101 done / 109 total; 4 can run
I1125 12:16:13.289549    9528 executor.go:155] No progress made, sleeping before retrying 4 task(s)
I1125 12:16:23.304076    9528 executor.go:111] Tasks: 101 done / 109 total; 4 can run
I1125 12:16:25.822231    9528 executor.go:111] Tasks: 105 done / 109 total; 4 can run
I1125 12:16:25.919122    9528 executor.go:111] Tasks: 109 done / 109 total; 0 can run
I1125 12:16:27.221437    9528 dns.go:238] Pre-creating DNS records
I1125 12:16:27.817503    9528 update_cluster.go:326] Exporting kubeconfig for cluster
kOps has set your kubectl context to k8s.ap-northeast-2.aws.hello.com
W1125 12:16:27.845592    9528 update_cluster.go:350] Exported kubeconfig with no user authentication; use --admin, --user or --auth-plugin flags with `kops export kubeconfig`

Cluster is starting.  It should be ready in a few minutes.

Suggestions:
 * validate cluster: kops validate cluster --wait 10m
 * list nodes: kubectl get nodes --show-labels
 * ssh to the master: ssh -i ~/.ssh/id_rsa ubuntu@api.k8s.ap-northeast-2.aws.hello.com
 * the ubuntu user is specific to Ubuntu. If not using Ubuntu please use the appropriate user based on your OS.
 * read about installing addons at: https://kops.sigs.k8s.io/addons.

AWS 콘솔에서 EC2 인스턴스 목록을 확인해보면 마스터와 워커 노드들이 생성되고 있을 것입니다.

다음 명령을 입력하여 ~/.kube/config에 방금 생성한 클러스터의 설정을 추가합니다.

$ kops export kubeconfig --admin

잠시 기다리면 EC2 인스턴스가 생성되고 클러스터가 초기화됩니다.

우리는 실제로 hello.com 도메인을 구입하지 않았으므로, 로컬에서 임시로 사용할 수 있도록 설정해야 합니다. 운영체제별로 설정 파일이 조금 다른데, 각자 운영체제에 맞는 파일을 수정합니다.

IP 주소는 클러스터의 마스터 노드 IP 주소를 사용해야 하는데, 다음과 같은 과정으로 IP 주소를 찾을 수 있습니다.

  1. AWS 콘솔 접속
  2. EC2로 이동
  3. 인스턴스 메뉴 클릭
  4. 이름이 master-ap-northeast-2a.masters.k8s.ap-northeast-2.aws.hello.com인 인스턴스 클릭 클릭
  5. 세부 정보에 퍼블릭 IPv4 주소 부분을 복사(<마스터 노드의 퍼블릭 IPv4 주소>)

리눅스, macOS는 /etc/hosts 파일을 수정해야 합니다. root 권한이 있어야 하므로 sudo vim으로 수정합니다.

리눅스, macOS
$ sudo vim /etc/hosts

/etc/hosts 파일의 마지막 부분에 다음 내용을 추가한 뒤 저장합니다.

/etc/hosts
<마스터 노드의 퍼블릭 IPv4 주소> api.k8s.ap-northeast-2.aws.hello.com

윈도우는 C:\Windows\System32\drivers\etc\hosts 파일을 수정해야 합니다. 관리자 권한이 필요하므로, 메모장을 관리자 권한으로 실행한 뒤 파일을 엽니다.

C:\Windows\System32\drivers\etc\hosts 파일의 마지막 부분에 다음 내용을 추가한 뒤 저장합니다.

C:\Windows\System32\drivers\etc\hosts
<마스터 노드의 퍼블릭 IPv4 주소> api.k8s.ap-northeast-2.aws.hello.com

메모장에서 hosts 파일이 보이지 않는다면?

메모장에서 hosts 파일이 보이지 않는다면, 열기 창에서 열기(O) 버튼 위의 텍스트 문서(*.txt)모든 파일 (*.*)로 바꿔주면 됩니다.

kubectl get nodes 명령을 입력하여 노듣 목록을 출력해봅니다. 노드 4개가 완전히 생성된 뒤 Ready 상태가 될 때까지 시간이 다소 걸립니다. 노드가 일부만 보인다면 조금 더 기다렸다가 명령을 실행해봅니다.

$ kubectl get nodes
NAME                  STATUS   ROLES           AGE    VERSION
i-01a4d885fd48acc61   Ready    control-plane   4m4s   v1.25.4
i-082f35a3d294a5e7d   Ready    node            54s    v1.25.4
i-0c48a73869254c456   Ready    node            37s    v1.25.4
i-0e5dad97f6500d40a   Ready    node            51s    v1.25.4

이렇게 kOps로 AWS에 쿠버네티스 클러스터를 생성해보았습니다. 다음 장에서는 Nginx 인그레스 컨트롤러를 설치한 뒤 로드밸런서(AWS의 ELB)에 웹 서버 디플로이먼트와 서비스를 연결하는 방법을 알아보겠습니다.

클러스터 삭제 방법

여기서 더 이상 진행하지 않고 클러스터를 삭제하려면 다음 명령을 실행합니다.

$ kops delete cluster --name k8s.ap-northeast-2.aws.<구입한 도메인> --yes

또는

$ kops delete cluster --name k8s.ap-northeast-2.aws.hello.com --yes

저작권 안내

이 웹사이트에 게시된 모든 글의 무단 복제 및 도용을 금지합니다.
  • 블로그, 게시판 등에 퍼가는 것을 금지합니다.
  • 비공개 포스트에 퍼가는 것을 금지합니다.
  • 글 내용, 그림을 발췌 및 요약하는 것을 금지합니다.
  • 링크 및 SNS 공유는 허용합니다.

Published

2022-10-22