Kubernetes - (3) Kubectl 활용한 리소스 관리

임쿠쿠·2022년 4월 28일
0

kubernetes

목록 보기
3/8
post-thumbnail

1. Pods

1) Pod 체크

kubectl get pods
kubectl get pods -o wide

상세정보

kubectl describe pod pod명

2) Pod 실행

kubectl run Pod명 --image=이미지명

yaml 파일 실행

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: nginx
    tier: frontend
spec:
  containers:
  - name: nginx
    image: nginx
kubectl apply -f pod.yaml
kubectl create -f pod.yaml

yaml 파일 수정

kubectl apply -f pod.yaml
kubectl edit pod pod명

3) Pod 삭제

kubectl delete pod pod명

4) Init Container

  • 특정 POD을 생성 시, init Container가 작업이 완료되야 해당 POD Running
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
  - name: init-myservice
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"]
  - name: init-mydb
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"]

2. Replica

1) Replica controller

  • 레플리카 컨트롤러를 통해 pod이 fail 시 지정된 수 만큼 재생성
  • 유저 혹은 트래픽에 따라 여러 노드에 걸쳐 scaling & Load Balancing 지원

replica_rc.yaml

apiVersion: v1
kind: ReplicationController
metadata:
  name: myapp-rc
  labels:
    app: myapp
    tier: frontend
spec:
  template: // POD 정보 기입
    metadata:
    name: nginx
    labels:
      app: myapp
      tier: frontend
    spec:
      containers:
      - name: nginx-container
        image: nginx	
replicas: 3

실행

kubectl create -f replica_rc.yaml

체크

kubectl get replicationcontroller

2) ReplicaSets

  • matchLabels을 통해 수많은 Pod 중 관리할 Pod을 식별 후 모니터링

replica_rs.yaml

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: myapp-rs
  labels:
    app: myapp
    tier: frontend
spec:
  template: // POD 정보 기입
    metadata:
    name: nginx
    labels:
      app: myapp
      tier: frontend
    spec:
      containers:
      - name: nginx-container
        image: nginx	
replicas: 3
selector:
   matchLabels:
     type: frontend // template lable과 일치

실행

kubectl create -f replica_rs.yaml

체크

kubectl get replicaset

수정

kubectl edit replicaset rs명

스케일링

kubectl replace -f replica_rs.yaml
kubectl scale --replicas=6 -f replica_rs.yaml
kubectl scale rs rs명 --replicas=5

중요) RS POD image 교체 시, 실행중인 POD 삭제 후 자동 재생성

3. Deployment

1) 이점

  • 새로운 app 버전 출시 후, 실행중인 모든 POD을 한번에 업데이트하면 유저에게 영향을 미치므로 하나씩 업데이트 진행 ~ rolling update
  • 새로운 app에서 문제가 발생 시, 이전 버전으로 roll back
  • app버전 / modify resource allocation / scaling 함께 진행시킬 경우
  • 레플리카로 만든 multi POD을 하나로 묶음

2) Deployment Practice

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-rs
  labels:
    app: myapp
    tier: frontend
spec:
  template: // POD 정보 기입
    metadata:
    name: nginx
    labels:
      app: myapp
      tier: frontend
    spec:
      containers:
      - name: nginx-container
        image: nginx	
replicas: 3
selector:
   matchLabels:
     type: frontend // template lable과 일치

실행

kubectl create -f deployment.yaml

체크

kubectl get deployments

번외

kubectl create deployment deployment명 --image=이미지명
kubectl scale deployment --replicas=3 deployment명

4. Services

1) Services 요약

  • Services enable communication between various components whithin and outside of the application or users
  • 각각의 서비스(프론트/백엔드/DB)로 나누어 커뮤니케이션 하며 loose coupling 및 micro service 구현
  • POD에 접근하기 위해 Node 내부에서는 ssh 접속가능하지만 외부 유저는 직접 접근 불가능
    -> NodePortService를 통해 외부에서 해당 포트로 접속 시, Service는 해당 포트를 리슨하고 POD에 포워딩

2) Services Types

(1) NodePort

  • Node Port를 통해 내부 POD 접근 (Node 포트와 POD 포트를 매핑)
  • TargetPort : POD의 포트
  • Port : 서비스의 포트 / 서비스는 고유의 IP를 가지고 있고 서비스의 클러스터 IP라고 한다.
  • NodePort : 외부에서 접속하는 Node의 포트 / 기본적으로 범위는 30000 ~ 32767 이다.

service-np.yaml

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  type: NodePort
  ports:
    - targetPort: 80
      port: 80
      nodePort: 30008
  selector: // 수많은 POD 중 어떤 POD인지 명시
    app: myapp
    type: front-end

실행

kubectl create -f service-np.yaml

체크

kubectl get services // 해당 service의 클러스터 IP를 통해 외부에서 접근 가능
  • 같은 노드에 동일한 라벨의 mutli POD이 있을 경우 서비스는 랜덤 알고리즘을 통해 로드밸런 진행
  • mutli 노드에 동일한 라벨의 mutli POD이 있을 경우 서비스는 mutli노드 모든 영역으로 확장되고 각 Node의 NodePort로 접속 시 동일하게 mutli Node에 대해 로드밸런싱 진행

(2) Cluseter IP

  • 서비스는 클러스터 안에 가상 IP를 생성하여 각각 다른 서비스와 연결
  • POD의 IP는 생성, 제거 등이 수시로 이루어지기 때문에 static하지 않다. service는 프론트/백엔드/레디스 리소스가 각각 여러 POD을 가질경우 이를 그룹핑하여 리소스간에 single interpace 역할 담당

service-ci.yaml

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  type: ClusterIP
  ports:
    - targetPort: 80
      port: 80
  selector: // 수많은 POD 중 어떤 POD인지 명시
    app: myapp
    type: front-end

(3) LoadBalancer

  • 두개의 도메인에 각각의 Service가 있으면 유저는 해당 Service의 NodePort로 접근해야한다.
  • 두 Service에 대한 하나의 인터페이스 생성 및 로드밸런싱 진행

service-lb.yaml

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  type: LoadBalancer
  ports:
    - targetPort: 80
      port: 80
      nodePort: 30008

5. NameSpaces

  • POD / Service / Deployment를 묶어서 지정

namespace별 POD 조회

kubectl get pods --namespace=네임스페이스명
// 특정 네임스페이스를 디폴트로 지정하여 get pods로 바로 조회
kubectl config set-context $(kubectl config current-context) --namespace=네임스페이스명 
// 특정 네임스페이스의 서비스 조회
kubectl -n 네임스페이스명 get svc
// 특정 네임스페이스 서버 접근 시 host name
서비스명.네임스페이스명.svc.cluster.local
ex) db-service.dev.svc.cluster.local
// 모든 pod 조회
kubectl ge pods -all-namespaces
kubectl get pods --all-namespaces | grep POD명

namespace지정 후 POD 생성

kubectl create -f pod.yaml --namespace=네임스페이스명
kubectl run POD명 --image=이미지명 -n 네임스페이스명

namespace 생성

apiVersion: v1
kind: Namespace
metadata:
  name: dev
kubectl create -f namespace.yaml
kubectl create namespace 네임스페이스명

Resource Quota

  • 특정 네임스페이스의 리소스 제한
apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-quota
  namespace: dev
spec:
  hard:
    pods: "10"
    requests.cpu: "4"
    requests.memory: 5Gi
    limits.cpu: "10"
    limits.memory: 10Gi
kubectl create -f quota.yaml

6. Mananging the infrastructure

1) Imperative Commands

  • 목적을 이루기 위해 단계별 명시 후 실행
    ex) 순차적 코드 실행
kubectl run --image=nginx nginx
kubectl create deployment --image=nignx nginx
kubectl expose deployment nginx --port 80
kubectl edit deployment nginx
kubectl scale deployment nginx --replicas =5
kubectl set image deployment nginx nginx=nginx:1.18
kubectl create -f nginx.yaml
kubectl replace -f niinx.yaml
kubectl delete -f nginx.yaml

단점

  • 멀티 컨테이너 / deployment를 코드 실행으로 해결하기 어려움
  • 해당 코드의 실행을 다른 사람이 추적하기 어려움
  • 복잡한 환경에서 위 명령만으로는 작업하기 힘듬

2) Declarative Commands

  • 목적을 이루기 위한 모든 정보를 기입 (defines the expected state of the applications and services)
  • apply command는 로컬 yaml 파일 적용 시 쿠버네티스 클러스트 안에 내부적으로 Live object configuration을 만들고 이를 통해 생성 / 수정할지 결정
    ex) 해당 리소스가 존재하는지에 따라 생성 / 업데이트 진행
kubectl apply -f nginx.yaml
kubectl apply -f /path/to/config-files // 디렉토리 파일들 적용

3) Practice

라벨 기입 후 POD 생성

1) kubectl run POD명 --image=image명 --dry-run=client -oyaml > 파일명.yaml // 이후 yaml 파일에서 label 수정
2) kubectl run POD명 -l tier=라벨명 --image=image명

POD으로 서비스 생성

kubectl expose pod pod명 --port=PORT --name 서비스명

POD생성과 동시에 서비스 생성

kubectl run POD명 --image=image명 --port=PORT --expose

POD으로 포트 지정 후 생성

kubectl run POD명 --image=image명 --port=PORT

이미지/레플리카/네임스페이스 deployment생성

kubectl create deployment deployment명 --image=image명 --replicas=3 --n namespace명

namespace 생성

kubectl create ns namespace명
profile
Pay it forward

0개의 댓글