Skip to content

Instantly share code, notes, and snippets.

@ianychoi
Last active July 31, 2021 12:48
Show Gist options
  • Save ianychoi/8427985d1ad7770504c53483688431b2 to your computer and use it in GitHub Desktop.
Save ianychoi/8427985d1ad7770504c53483688431b2 to your computer and use it in GitHub Desktop.
쿠버네티스 - LoadBalancer 서비스 실습

쿠버네티스 - LoadBalancer 서비스 실습

  • 참고: 해당 실습은 Azure 클라우드에서 실습하는 것을 기준으로 구성

  • 먼저 Azure Kubernetes Service를 만든다 (예: 리소스 그룹: osamtest, 리소스 이름: osamaks)

  • Azure Cloud Shell을 실행하고, 쿠버네티스 서비스에 접근 가능하도록 config 파일을 받아온다.

  • 참고: 쿠버네티스 config 파일을 통해 다른 리눅스 터미널에서도 kubectl 명령어만 설치되어 있으면 명령어 실행이 가능함

# Azure Cloud Shell에서 아래 명령을 실행하여 config 파일을 만든다.

$ az aks get-credentials --resource-group osamtest --name osamaks
Merged "osamaks" as current context in /home/ian/.kube/config

## 만약 바로 다음에서 설명하는 것과 같이, 다른 리눅스 터미널에서 실습하는 경우에는 --file 옵션을 지정하여 별도로 파일 저장
$ az aks get-credentials --resource-group osamtest --name osamaks --file kubeconfig
Merged "osamaks" as current context in kubeconfig
  • Azure Cloud Shell에서가 아닌, 다른 리눅스 터미널에서 실습하는 경우는 아래 부분을 따라가도록 하자.
# 참고: 로컬에서 대신 실행하고자 하는 경우 kubeconfig 파일 내용을 사용해야 한다.
# 참고2: K3s와 K3s 등 환경에 따라 Config 파일 위치가 다름. 반드시 아래 kubectl get node -v7 명령어를 통해 나오는 첫 번째 줄로 파일 위치 확인!

root@k3s-m:~# kubectl get node -v7
I0731 02:27:05.150531    7116 loader.go:372] Config loaded from file:  /etc/rancher/k3s/k3s.yaml
I0731 02:27:05.174981    7116 round_trippers.go:432] GET https://127.0.0.1:6443/api/v1/nodes?limit=500
I0731 02:27:05.177299    7116 round_trippers.go:438] Request Headers:
I0731 02:27:05.177427    7116 round_trippers.go:442]     Accept: application/json;as=Table;v=v1;g=meta.k8s.io,application/json;as=Table;v=v1beta1;g=meta.k8s.io,application/json
I0731 02:27:05.177471    7116 round_trippers.go:442]     User-Agent: kubectl/v1.21.3+k3s1 (linux/amd64) kubernetes/1d1f220
I0731 02:27:05.187511    7116 round_trippers.go:457] Response Status: 200 OK in 10 milliseconds
NAME     STATUS     ROLES                  AGE    VERSION
k3s-w2   NotReady   <none>                 5d9h   v1.21.3+k3s1
k3s-w1   NotReady   <none>                 5d9h   v1.21.3+k3s1
k3s-m    Ready      control-plane,master   5d9h   v1.21.3+k3s1
root@k3s-m:~# cd /etc/rancher/k3s
root@k3s-m:/etc/rancher/k3s# cp k3s.yaml k3s.yaml-backup

# 설정 파일 용량이 비교적 큰 관계로, 사양에 따라 cat 명령어가 잘 안될 수 있다. vi를 이용해 보는 것으로 함
root@k3s-m:/etc/rancher/k3s# vi k3s.yaml
(1. ":1,$d"를 입력하면 전체 삭제)
(2. "i"를 입력하면 삽입 모드가 되며, 이후 마우스 오른쪽 버튼 등을 클릭하여 붙여넣기)
(3. ESC키를 누른 후, ":wq"를 입력하면 저장 후 빠져나옴)

# 잘 동작하는지 확인
root@k3s-m:/etc/rancher/k3s# kubectl get node
NAME                                STATUS   ROLES   AGE   VERSION
aks-agentpool-52047766-vmss000000   Ready    agent   32m   v1.19.11
root@k3s-m:/etc/rancher/k3s# cd
root@k3s-m:~# kubectl get node
NAME                                STATUS   ROLES   AGE   VERSION
aks-agentpool-52047766-vmss000000   Ready    agent   32m   v1.19.11
root@k3s-m:~#
  • echo-pod.yaml : 디플로이먼트 생성
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deploy-echo
spec:
  replicas: 3
  selector:
    matchLabels:
      app: deploy-websrv
  template:
    metadata:
      labels:
        app: deploy-websrv
    spec:
      containers:
      - name: cndk-websrv
        image: k8s.gcr.io/echoserver:1.5
        ports:
        - containerPort: 8080
  • 확인
# (옵션) 터미널1
watch -d 'kubectl get pods,svc,ep -o wide'

# 파드 생성
curl -s -O https://raw.githubusercontent.com/gasida/DKOS/main/5/echo-pod.yaml
kubectl apply -f echo-pod.yaml

# Pod IP만 출력
kubectl get pod -o wide -l app=deploy-websrv |awk 'NR>1 {print $6}'

# Pod IP로 curl 접속을 해보자 - K3s/K8s 테스트와 달리 외부 네트워크에서 확인하므로 안된다. Ctrl+C를 통해 중지한다.
curl -s http://10.244.0.9:8080

# (옵션) 터미널2 Pod 로그 실시간 확인 : 출력 정보 확인
kubectl logs -l app=deploy-websrv -f

# 테스트용 파드 생성 후 실습해보자 - 잘된다.
kubectl run -it --rm netdebug --image=nicolaka/netshoot --restart=Never -- zsh
-------------
 netdebug  ~  curl -s http://10.244.0.9:8080


Hostname: deploy-echo-56f947c867-dctkr

Pod Information:
        -no pod information available-

Server values:
        server_version=nginx: 1.13.0 - lua: 10008

Request Information:
        client_address=10.244.0.12
        method=GET
        real path=/
        query=
        request_version=1.1
        request_uri=http://10.244.0.9:8080/

Request Headers:
        accept=*/*
        host=10.244.0.9:8080
        user-agent=curl/7.77.0

Request Body:
        -no body in request-


 netdebug  ~exit
pod "netdebug" deleted
  • 로드밸런서 서비스 생성을 위한 azure-lb.yaml
apiVersion: v1
kind: Service
metadata:
  name: azure-lb-websrv
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 8080
  selector:
    app: deploy-websrv
  • 로드밸런서 생성 & 테스트!
# 생성
curl -s -O https://gist.githubusercontent.com/ianychoi/54ea4bfcb9c4bb56eb8bf9a86cda9841/raw/2523d9e8eb3b25f067254d76743a506d82d46059/azure-lb.yaml
kubectl apply -f azure-lb.yaml

# 서비스의 IP(CLUSTER-IP)가 할당되었으며, 쿠버네티스 네트워크 내 파드에서는 서비스의 IP 또는 서비스 이름(도메인)으로 서비스에 접근 가능
# **EXTERNAL-IP** 주소는 Azure에서 자동으로 할당해 준 것으로, 이 주소와 80(YAML ports.port)를 통해 포드에 접근 할 수 있다
kubectl get svc -o wide

# kubectl get svc -o=wide
NAME              TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)        AGE   SELECTOR
azure-lb-websrv   LoadBalancer   10.0.232.21   20.194.40.143   80:31026/TCP   82s   app=deploy-websrv
kubernetes        ClusterIP      10.0.0.1      <none>          443/TCP        56m   <none>

# 엔드포인트 확인
kubectl get endpoints

# kubectl get endpoints
NAME              ENDPOINTS                                           AGE
azure-lb-websrv   10.244.0.10:8080,10.244.0.11:8080,10.244.0.9:8080   113s
kubernetes        52.231.112.58:443                                   57m

# 웹 접속 로그 출력
kubectl logs -l app=deploy-websrv -f

----------------------
# [클라이언트] EXTERNAL-IP 접속 테스트
EXIP=20.194.40.143

curl -s --connect-timeout 1 $EXIP | egrep '(Hostname|nginx|client_address)'

for i in {1..100}; do curl -s $EXIP | grep Hostname ; done | sort | uniq -c | sort -nr

for i in {1..100}; do curl -s $EXIP | grep client_address ; done | sort | uniq -c | sort -nr

while true; do curl -s --connect-timeout 1 $EXIP | egrep '(Hostname|nginx|client_address)'; echo "--------------" ; date "+%Y-%m-%d %H:%M:%S" ; sleep 1; done
----------------------
  • 오브젝트 삭제
# 서비스 삭제
kubectl delete svc azure-lb-websrv

# 디플로이먼트 삭제
kubectl delete deploy --all

# config 원상 복구!

cd /etc/rancher/k3s
cp k3s.yaml-backup k3s.yaml
  • 더 이상 테스트가 필요없으며 Azure 클라우드에서 리소스 삭제하는 것을 잊지 말자! 비용 절감!! Azure Cloud Shell에서 명령어 (참고: 리소스 그룹이 남아 있어서 삭제하는 것도 좋음. 하지만 삭제하지 않아도 비용 과금이 발생하지 않음)
$ az aks delete --resource-group osamtest --name osamaks
Are you sure you want to perform this operation? (y/n): y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment