data engineering

setting k8s using rke + aws ec2

qkqhxla1 2021. 6. 23. 19:45

예전에 https://qkqhxla1.tistory.com/1026 에서 rke(rancher kubernetes engine)환경에서 aws cluster를 추가하는 글을 썼었는데 처음부터 만드는 글이 아니라 단순하게 클러스터 추가와 aws 설정에 초점이 맞추어져있었다. 이번에는 처음에 구성하는 글을 적으려고 한다. 근데 aws를 사용하는데 eks가 아니라 단순히 여러대 있는 서버에 설치하듯이 ec2 ubuntu에 세팅할 예정이다. eks로 세팅하는건 아직 잘 몰라서 익숙한 방법인 이 방법으로 세팅한다. 아마 나중에 eks로 세팅할 일이 있으면 다시 글을 적을것 같다.

왠만해서는 처음부터 다시 다 세팅할 일이 없는데.... 인증서 관련 장애로 rancher ui가 다 날라가버렸다. 어떻게든 살리려 노력했으나 살릴수 없었고, ui는 죽어있지만 이전에 만들어놨던 pod이나 잡은 남아있어서 그거로 버티면서 새 kubernetes rancher서버로 옮겨가려고 했던 과정들을 적는다. 힘들었지만 이럴때 아니면 이런 세팅 언제해보면서 배워보겠냐는 마인드로 작업을 하니 좀 괜찮았다..

이전 캡쳐본을 참고하자면 이번에 만드는건 빨간색 사각형 부분이다.

master 3대만 만들어서 올릴 예정이다.
rke라는건 https://rancher.com/products/rke/ 에 나와있는데 rancher kubernetes engine의 약자로 쿠버네티스를 설치해주는 엔진 중 하나이다. gke등 다른 엔진도 존재한다. rke를 마스터 3대중 한대에 설치해서 세팅하려고 한다.
rke는 마스터 3대중 한대가 아니라 다른곳에서도 가능하다. 다만 rke를 설치하는곳에서 마스터 3대로 ssh접속이 가능해야 하고, ssh로 접속하는 계정은 도커 권한이 있어야 한다.

rke 튜토리얼을 보고 따라하자. 마스터 3대중 한대에 rke를 다운받고 세팅한다.

$ mkdir rke
$ cd rke
$ wget https://github.com/rancher/rke/releases/download/v1.2.9-rc2/rke_linux-amd64
$ mv rke_linux-arm64 rke
$ chmod 755 rke

rke가 세팅되었으면 cluster.yml을 만들어야 한다. cluster.yml은 rke로 세팅할 클러스터가 어떤 클러스터인지 등의 정보를 담고 있다. cluster.yml에 내 마스터 3대의 정보가 들어가야 한다. cluster.yml은 내가 하나하나 yml을 찾아서 만들 필요 없이 rke config --name cluster.yml
로 생성이 가능하다. 

$ ./rke config --name cluster.yml
[+] Cluster Level SSH Private Key Path [~/.ssh/id_rsa]:
[+] Number of Hosts [1]: 3  # 본체 마스터 3대라고 했다.
[+] SSH Address of host (1) [none]: 10.1.2.3  # 마스터 1번의 주소.
[+] SSH Port of host (1) [22]:
[+] SSH Private Key Path of host (10.1.2.3) [none]:
[-] You have entered empty SSH key path, trying fetch from SSH key parameter
[+] SSH Private Key of host (10.1.2.3) [none]:
[-] You have entered empty SSH key, defaulting to cluster level SSH key: ~/.ssh/id_rsa  # 위에서 ~/.ssh/id_rsa에 저장해놨다고 했다.
[+] SSH User of host (10.1.2.3) [ubuntu]: myUser # ~/.ssh/id_rsa로 접근가능한 유저 정보를 입력한다.
[+] Is host (10.1.2.3) a Control Plane host (y/n)? [y]: y  # 마스터므로 control plane, worker, etcd 3개에 y 체크해준다.
[+] Is host (10.1.2.3) a Worker host (y/n)? [n]: y
[+] Is host (10.1.2.3) an etcd host (y/n)? [n]: y
[+] Override Hostname of host (10.1.2.3) [none]: myserver-1
[+] Internal IP of host (10.1.2.3) [none]:
[+] Docker socket path on host (10.1.2.3) [/var/run/docker.sock]:
# 3번반복.. 
...
 
[+] Network Plugin Type (flannel, calico, weave, canal, aci) [canal]:
[+] Authentication Strategy [x509]:
[+] Authorization Mode (rbac, none) [rbac]:
[+] Kubernetes Docker image [rancher/hyperkube:v1.20.6-rancher1]:
[+] Cluster domain [cluster.local]:
[+] Service Cluster IP Range [10.43.0.0/16]:
[+] Enable PodSecurityPolicy [n]:
[+] Cluster Network CIDR [10.42.0.0/16]:
[+] Cluster DNS Service IP [10.43.0.10]:
[+] Add addon manifest URLs or YAML files [no]:

요런식으로 입력해주면 현재 위치에 cluster.yml이 만들어진다. 

# If you intened to deploy Kubernetes in an air-gapped environment,
# please consult the documentation on how to configure custom RKE images.
nodes:
- address: 10.1.2.3
  port: "22"
  internal_address: ""
  role:
  - controlplane
  - worker
  - etcd
  hostname_override: myserver-1
  user: ubuntu
  docker_socket: /var/run/docker.sock
  ssh_key: ""
  ssh_key_path: ~/.ssh/id_rsa
  ssh_cert: ""
  ssh_cert_path: ""
  labels: {}
  taints: []
- address: 10.2.3.4
.....

% 참고로 위의 설정을 보면 나는 ubuntu계정의 ~/.ssh/id_rsa를 사용한다고 했는데, 이뜻은 저 서버의 우분투 계정에서 ssh ubuntu@10.1.2.3으로 접속했을때 비밀번호같은걸 묻지 않고 바로 접속이 되어야 한다. 접속이 되지 않는다면 설치중 에러가 뜬다.
rke up을 해준다. rke up은 기본적으로 같은 위치의 cluster.yml를 참조하게 되고, 여기에 적혀있는 서버들로 들어가서 rke클러스터 세팅을 해주는 명령어이다. cluster.yml에 마스터 3대의 정보를 적었으니 ssh로 각각 접근해서 설치가 된다. 참고로 도커 관련 권한이 있어야 한다.

$ ./rke up
WARN[0000] This is not an officially supported version (v1.2.9-rc2) of RKE. Please download the latest official release at https://github.com/rancher/rke/releases
INFO[0000] Running RKE version: v1.2.9-rc2
INFO[0000] Initiating Kubernetes cluster
INFO[0000] [certificates] GenerateServingCertificate is disabled, checking if there are unused kubelet certificates
INFO[0000] [certificates] Generating Kubernetes API server certificates
......
INFO[0186] [ingress] ingress controller nginx deployed successfully
INFO[0186] [addons] Setting up user addons
INFO[0186] [addons] no user addons defined
INFO[0186] Finished building Kubernetes cluster successfully
$

rke up을 성공적으로 마무리하면 cluster.rkestate와 kube_config_cluster.yml 파일이 현재 위치에 생성된다. kube_config_cluster.yml는 kubect과 helm사용시 참조하는 파일이다. ~/.kube/config에 넣어두자. 나중에 kubectl설치후 작동시에 기본적으로 참조하는 위치가 ~/.kube/config이기 때문이다.

이제 마스터 3대에 클러스터 세팅은 완료된 상태인데 껍데기(?)만 만들어진 상태이다. ui도 보이지 않고 추가적으로 더 세팅을 해줘야 한다. aws상이니 로드밸런서를 잘 세팅해서 마스터 3대로 로드밸런싱을 잘 하도록 세팅했다. tcp 80, 443번 두개 포트를 대상으로 로드밸런싱을 하면 된다.

aws가 아닐 경우 nginx로도 가능하다. 여기 참조
잠시 아래 nginx세팅을 보자. 미리 my-aws.rancher.test.net 을 호출시 nginx서버로 보내도록 도메인을 만들어놓은 상태이다.
https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/ 를 참조해서 /etc/nginx/nginx.conf를 간단히 만들어준다. 80, 443만 오도록 하면 된다. 

load_module /usr/lib/nginx/modules/ngx_stream_module.so;
worker_processes 4;
worker_rlimit_nofile 40000;
 
events {
    worker_connections 8192;
}
 
stream {
    upstream rancher_servers_http {
        least_conn;
        server 10.1.2.3:80 max_fails=3 fail_timeout=5s;
        server 10.2.3.4:80 max_fails=3 fail_timeout=5s;
        server 10.3.4.5:80 max_fails=3 fail_timeout=5s;
    }
    server {
        listen     80;
        proxy_pass rancher_servers_http;
    }
 
    upstream rancher_servers_https {
        least_conn;
        server 10.1.2.3:443 max_fails=3 fail_timeout=5s;
        server 10.2.3.4:443 max_fails=3 fail_timeout=5s;
        server 10.3.4.5:443 max_fails=3 fail_timeout=5s;
    }
 
    server {
        listen     443;
        proxy_pass rancher_servers_https;
    }
}

현재 my-aws.rancher.test.net 도메인을 호출하면 nginx를 호출하게되고, nginx에서 마스터 3대(10.1.2.3, 10.2.3.4, 10.3.4.5)로 로드밸런싱이 된 상태이다. 

잠시 nginx얘기를 했는데 요지는 aws 로드밸런서던 nginx던 마스터 3대로 로드밸런싱이 되면 된다는거다.


이제 kubectl과 helm을 설치하자.
https://kubernetes.io/ko/docs/tasks/tools/install-kubectl-linux/를 참조해서 kubectl을 설치한다.

$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
$ chmod 755 kubectl
$ sudo mv kubectl /usr/local/bin  # 어디서든 호출할 수 있도록..

위에서 kube_config_cluster.yml를 ~/.kube/config경로에 넣었는데 설정이 잘 들어갔는지 확인겸
kubectl cluster-info을 입력해서 잘 작동하는지 확인해보자. 잘 나오면 설정이 잘 들어간거다.

이제 helm을 설치하자. https://helm.sh/ko/docs/intro/install/를 참조한다.

$ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3
$ chmod 700 get_helm.sh
$ ./get_helm.sh

이제 cert manager를 설치한다. cert manager는 HTTPS 통신을 위한 인증서를 생성하고, 인증서의 만료 기간이 되면 자동으로 인증서를 갱신해주는 역할을 한다.
https://cert-manager.io/docs/installation/kubernetes/를 참조해 설치한다.

$ kubectl create namespace cert-manager
$ helm repo add jetstack https://charts.jetstack.io
$ helm repo update
$ kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.4.0/cert-manager.crds.yaml
$ helm install \
  cert-manager jetstack/cert-manager \
  --namespace cert-manager \
  --create-namespace \
  --version v1.4.0

마지막으로 드디어 랜쳐 ui를 설치하고 올린다.
https://rancher.com/docs/rancher/v2.x/en/installation/install-rancher-on-k8s/ 를 참조하자.

$ helm repo add rancher-latest https://releases.rancher.com/server-charts/latest
$ kubectl create namespace cattle-system
$ helm upgrade --install rancher rancher-latest/rancher \
   --namespace cattle-system \
   --set hostname=my-aws.rancher.test.net

hostname을 내가 위에서 세팅했다고 한 my-aws.rancher.test.net 으로 적었다.
위의 랜쳐 설치가 성공적으로 끝나면 my-aws.rancher.test.net로 들어가보면 랜쳐 ui가 뜬다.