brunch

You can make anything
by writing

C.S.Lewis

by Master Seo Sep 15. 2021

EKS 4탄-15. EKS-Fargate 실습

실습 4탄 =  15/17

Fargate 

Statless 한 프런트엔드 서비스를 Fargate에서 서비스 하라. ALB이용.

가장 비용 저렴한 방식을 사용하라.Fargate only ?  ,   EC2 EKS + Fargate EKS ?

Fargate profile 생성이 필수다.

role 생성도 필수다.



<1> EKS-Fargate  장점 

<2> EKS-Fargate 제약

<3> 실습 1 - EKS-Fargate Profile?

<4> Fargate를 위한 네트워크 구성 하기

<5> Fargaterole 파일 생성

<6> 샘플 nginx 디플로이

<7> 삭제

<8> 참고 동영상

<9> 다음 과정 ~   EKS에서  EBS 사용 실습




<1> EKS-Fargate  장점 


1

완전 관리형  서버 리스 서비스.



2

EKS-EC2의 경우  EKS는  데이터 플레인(Work node)은 사용자가 관리한다.

그러나, Fargate는  데이터 플레인(Work node)을 AWS에서 관리해준다.

관리해야 하는 EC2가 없다.

실제 콘솔의 EC2 목록에 가도 Fargate EC2는 없다.


Fargate는 Pod가 올라가는 EC2도 AWS가 관리해준다.
CA (Cluster Autoscaler)가 불필요.

클러스터를 늘릴 필요가 없다.

CA는 EKS쓰다가 Pod가 늘어나면 , Node를 늘려주는 기능인데 AWS가 해주니 불필요.



3

비용은 Pod 실행 시간으로 계산된다.

Node마다 aws-node, kube-dns, kube-proxy 1개가 생긴다. 

이 비용도 더해서 계산해야 한다.

EC2 EKS 는  pod가 EC2 각 1개씩 설치되더라도 EC2 비용이 발생된다.

Fargate EKS는 Pod의 실행시간으로 계산된다.



4

기존 EC2 Node와 같이 사용 가능하다.

EC2 + Fargate 혼합이 사용 가능하다.



5

Statless 한 프런트엔드 서비스를 Fargate에서 서비스 가능

ALB이용.



6

소스 변경 없이 Fargate로 이전 가능하다.



7

Fargate 보안 수준?

VM당 Pod 1개로 네트워크 구분이 가능하다.

물리 서버에 1개의 pod가 격리되어 서비스된다.

1개의 Pod= 1개의 Node가 된다.

Node의 ip와 pod의 ip가 동일하다.


쿠버네티스트는 Node 5,000개 까지 권장한다.

따라서, Fargate에서는 Pod 5000개까지 사용권장



8

container보다 빠른 새로운 가상화 기술 Firecracker 사용

Firecracker로 람다나 Fargate 사용.




<2>  Fargate 제약


1

리소스 제약 존재 (최대  4 vCPU, 30 GB 메모리)



2

Statless 한 프런트엔드 서비스를 Fargate에서 서비스 가능.

ALB이용

Statful 한 서비스 사용 안됨.

Statful 한 서비스는 EKS에서 서비스 한다.

예) Fargate에서 프런트 서비스하고, EKS는 Mysql 등 백앤드 서비스 함.



3

데몬 셋 사용 불가능



4

NLB/ ELB 사용 불가. 

ELB + 인그레스 조합으로는 가능.

ALB 사용가능



5

Fargate는 Public Subnet에 생성 불가능 - 에러가 난다.

Private Subnet에만 구성이 가능하다. 

따라서, NAT 사용해야 한다.




<3> Fargate Profile?



1

어떤 케이스에  Fargate에 생성하도록 하는 하는 파일이다.

예) Pod생성 시 , 네임 서비스가 A인 경우, 라벨이 B인 경우 생성하라는 프로파일로 지정한다.

AWS 웹 콘솔에서도 생성 가능

https://docs.aws.amazon.com/ko_kr/eks/latest/userguide/fargate-profile.html



2

사용?

Pod 생성시 

Fargate Profile과 일치하면(디폴트 네임스페이스, 라벨을 가진것)  Fargate에 생성하라~

Fargate Profile과 일치 하지 않으면 EC2에 생성하라



3

순서?

Fargate Profile 생성 - Pod 생성순이다.



4

노드 없다.

k get no

pod는  인스턴스가 없으니 pending 


Fargate Profile 생성

aws eks create-fargate-profile -- cli-input-json file://sss.json --region ap-northeast-2



5

eks 웹 콘솔에서  확인 - 새로고침 (30초 걸림)



6

노드를  보면 Fargate  node가 1개 생성됨.

pod도 생성됨



7

EC2 지정 프로파일에 반드시 생성하도록 하라라고 지정할 수도 있다.

EC2 지정 프로파일이  Fargate Profile 보다 우선한다.




<4> 실습1 - Fargate를 위한 네트워크 구성 하기


Fargate 는 Private subnet에 있어야 하므로 NAT 를 만든다.

role이 필요해 만든다.

Fargate  Profile만든다.



1

Fargate Pod들이 생성될 서브넷은 반드시 Private subnet이어야 한다.

Public에는 생성이 안된다.

NAT 필요

Private Subnet에 디폴트 라우팅을 NAT로 설정 필요.

Fargate  Profile에서 Pod가 생성될 Subnet , 네임스페이스, 레이블 등 조건으로 Fargate에 생성되도록 함



2

현재 서브넷?

Public Subnet 2개

Private Subnet 2개



3

다음 과정은 NATGW 생성하는 과정이다.

EIP할당, NAT 생성과 Private에서 public Subnet에 있는 NAT로 라우팅이 잡아진다.

콘솔에서 클릭 클릭으로 해서 작업 해도 된다.

nat는 public에 생성.

pri-rt 라우팅 테이블 생성하고 , pri subnet연결 , 0.0.0.0/0 nat로 연결



4

PublicSubnet 변수 지정 ?

PublicSubnet1=$(aws ec2 describe-subnets --filters Name=tag:Name,Values=$CLUSTER_NAME-PublicSubnet1 --query 'Subnets[0].SubnetId' --output text)


echo $PublicSubnet1


PrivateSubnetRouteTable=$(aws ec2 describe-route-tables --filters Name=tag:Name,Values=$CLUSTER_NAME-PrivateSubnetRouteTable --query 'RouteTables[0].RouteTableId' --output text)


 echo $PrivateSubnetRouteTable



4

EIP1개 받고

NATGW생성하고

Private 라우팅 정보 추가 되는 CloudFormation.


curl -O https://s3.ap-northeast-2.amazonaws.com/cloudformation.cloudneta.net/AKOS/natgw.yaml


sed -i "s/<PublicSubnet1>/$PublicSubnet1/g" natgw.yaml

sed -i "s/<PrivateSubnetRouteTable>/$PrivateSubnetRouteTable/g" natgw.yaml


aws cloudformation deploy --template-file natgw.yaml --stack-name myeks-natgw





<5> 실습2 -  fargaterole 파일 생성


1

fargaterole 파일 생성 ?



cat <<EOT> fargaterole.json

{

   "Version":"2012-10-17",

   "Statement":[

      {

         "Effect":"Allow",

         "Principal":{

            "Service": "eks-fargate-pods.amazonaws.com"

         },

         "Action":"sts:AssumeRole",

         "Condition":{            

         }

      }

   ]

}

EOT




2

권한이 필요하다.

파게이트 프로파일이 사용할 Role을 만든다!!!

role을 만듬.

Assume 에서 사용할수 있는 role을 만듬

FargateRole


FargateRole=$(aws iam create-role --role-name FargateRole --assume-role-policy-document file://fargaterole.json --output text --query 'Role.Arn')


echo $FargateRole



3

# IAM Role에 정책 적용

role-name FargateRole

AmazonEKSFargatePodExecutionRolePolicy 정책을 적용함

EKS Fargate Pod를 실행시킬수 있는 역할 필요함!!


aws iam attach-role-policy --role-name FargateRole --policy-arn arn:aws:iam::aws:policy/AmazonEKSFargatePodExecutionRolePolicy



4

# PrivateSubnet1 변수 지정 ?


PrivateSubnet1=$(aws ec2 describe-subnets --filters Name=tag:Name,Values=$CLUSTER_NAME-PrivateSubnet1 --query 'Subnets[0].SubnetId' --output text)


PrivateSubnet2=$(aws ec2 describe-subnets --filters Name=tag:Name,Values=$CLUSTER_NAME-PrivateSubnet2 --query 'Subnets[0].SubnetId' --output text)



5


echo $FargateRole

echo $PrivateSubnet1

echo $PrivateSubnet2

// 반드시 private에 Fargate설치 해야 한다. 



6

조건 ? 

네임스페이스가 fp-demo 이고

라벨이 "node": "fargate" 인거만  Fargate에 배포하라!!!

            "namespace": "fp-demo",

            "labels": {

                "node": "fargate"



7

FargateRole 은 Fargate Pod를 실행시킬수 있는 역할이다.


cat <<EOT> fargateprofile.json

{

    "fargateProfileName": "fp-demo",

    "clusterName": "$CLUSTER_NAME",

    "podExecutionRoleArn": "$FargateRole",

    "subnets": [

        "$PrivateSubnet1",

        "$PrivateSubnet2"

    ],

    "selectors": [

        {

            "namespace": "fp-demo",

            "labels": {

                "node": "fargate"

            }

        }

    ]

}

EOT


// role 사용

// private subnet 에 설치

// namespace , labels에 맞는것에만 Fargate에 설치 됨

// namespace": "fp-demo이고    "labels": 이 매칭 되면  Fargate에 생성된다.



8

# Fargate profile 생성 : 대략 2분 

aws eks create-fargate-profile --cli-input-json file://fargateprofile.json


콘솔에서 확인 가능하다.

EKS > 클러스터 > myeks > 구성 > Fargate 프로파일 




9

Fargate Profiles 확인


eksctl get fargateprofile --cluster $CLUSTER_NAME

NAME SELECTOR_NAMESPACE_LABELS POD_ROLE_ARN     SUBNETS      TAGS   STATUS

fp-demo fp-demo  <none>   arn:aws:iam::xxxxx5:role/FargateRole subnet-,subnet-<none> ACTIVE



10

보안 그룹 추가 ?

# eksctl-host에서 파 게이트에 생성된 파드들과 접속 가능하게 보안 그룹 설정 룰(rule) 추가

EKSSGID=$(aws eks describe-cluster --name $CLUSTER_NAME --query cluster.resourcesVpcConfig.clusterSecurityGroupId --output text)


aws ec2 authorize-security-group-ingress --group-id $EKSSGID --protocol '-1' --cidr 192.168.1.100/32



11

fp-demo 네임 스페이스 생성과 변경 ?

kubectl create ns fp-demo

kubens fp-demo



12

Kube-operation-view 미리 실행





<6> 샘플 nginx 디플로이먼트 배포


watch -d kubectl get node,pod



1

# We will deploy an sample nginx application as a ReplicaSet of 1 Pod


프로파일에 있는 node: fargate 가 아래 labels에 node: fargate 에 동일한 이름으로 매칭되어 있으면 된다.


cat <<EoF> nginx.yaml

apiVersion: apps/v1

kind: Deployment

metadata:

  name: nginx-to-scaleout

spec:

  replicas: 1

  selector:

    matchLabels:

      app: nginx

  template:

    metadata:

      labels:

        service: nginx

        app: nginx

        node: fargate

    spec:

      containers:

      - image: nginx

        name: nginx-to-scaleout

        resources:

          limits:

            cpu: 500m

            memory: 512Mi

          requests:

            cpu: 500m

            memory: 512Mi

EoF



// node: fargate  로 이름이 같으면 된다. 



2

# 확인: 노드, 파드 상세 정보 

 파 게이트 노드의 IP와 파드의 IP가 똑같다

kubectl apply -f nginx.yaml  



3

# 파드 배포 실행 후 2~3분 정도 시간 소요

kubectl get deployment

kubectl get node

kubectl get node -l eks.amazonaws.com/compute-type=fargate -o wide  

# AWS 웹 콘솔에서 - EC2 개수 확인 시 추가된 EC2 인스턴스가 없다!



4

kubectl get pod -owide


# 파드 상세 정보 화인

FpPod1=$(kubectl get pod -oname | cut -d "/" -f 2)

kubectl describe pod $FpPod1  



5

kubectl exec -it $FpPod1 -- curl ipinfo.io/ip  

공인 IP가 나온다.

// NAT IP와 동일하다.



6

nginx 파드 Shell 접속 후 인터넷 통신 확인

kubectl exec -it $FpPod1 -- curl www.google.com

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-SG"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="aSV27wQY/Czvymm3svV6jw==">(function(){window.google=



7

Scale our ReplicaSet

# Let’s scale out the replicaset to 10

# 파 게이트 사용 시 데이터 플레인 용량 관리에서 해방되므로 Cloud AutoScaler를 고려하지 않아도 된다!


kubectl scale --replicas=10 deployment/nginx-to-scaleout




8

# MicroVM 단위가 fargate node로 표현되어 출력됨

watch -d kubectl get node,pod


Fargate의 node ip가  Pod IP와 동일하다.

가상  VM이 1대 1로 매칭 되므로



9

Fargate는 micro VM 당 = Pod가 1개씩 만들어진다!!!



10

복합적으로 사용가능하다.


EC2 node  + fargate로 같이 사용가능하다.






<7> 삭제



1

디플로이먼트 삭제

kubectl delete -f nginx.yaml



2

Fargate profile 삭제 : 대략 3분 

aws eks delete-fargate-profile --cluster-name $CLUSTER_NAME --fargate-profile-name fp-demo



3

NATGW 삭제

aws cloudformation delete-stack --stack-name myeks-natgw



4

fp-demo 네임스페이스 삭제

kubens default

kubectl delete ns fp-demo



5

IAM Role에 정책 해지

aws iam detach-role-policy --role-name FargateRole --policy-arn arn:aws:iam::aws:policy/AmazonEKSFargatePodExecutionRolePolicy

aws iam delete-role --role-name FargateRole



6

Fargate log 남도록 하기

기본적으로 Fargate log는 남지 않는다.

https://docs.aws.amazon.com/eks/latest/userguide/fargate-logging.html





<8> 참고 동영상


https://www.youtube.com/watch?v=N0uLK5syctU&feature=youtu.be




<9> 다음 과정 =   EKS에서  EBS 사용 실습


https://brunch.co.kr/@topasvga/1901



감사합니다.

매거진의 이전글 EKS 4탄-14.  EKS AutoScaling 실습
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari