Kubernetes CLI 

K8s의 기본 구성 요소 보기 >>  K8s 1) 쿠버네티스 기본 


Cluster

  • 여기에서는 EKS(Elastic Kubernetes Service)을 이용하여 클러스터를 생성 (AKS, GKE 등 대체 가능)
  • 사전 구성으로 IAM User 생성 및 AWS CLI에 Credential은 프로그래밍 방식 액세스 설정 필요

 

설치 및 사용법

 

eksctl 설치

# 이하 '$' 생략
curl --silent --location "https://github.com/weaveworks/eksctl/releases/download/latest_release/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
sudo mv -v /tmp/eksctl /usr/local/bin

 

kubectl 설치

#AWS CLI 버전 확인
#kubectl 접근을 위해 AWS CLI 버전 1.21 이상 유효. 1.21 이하면 업데이트 핋요
aws --version 
pip install awscli --upgrade --user

#kubectl 설치
curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.21.2/2021-07-05/bin/linux/amd64/kubectl
chmod +x ./kubectl
mkdir -p $HOME/bin && cp ./kubectl $HOME/bin/kubectl && export PATH=$PATH:$HOME/bin
echo 'export PATH=$PATH:$HOME/bin' >> ~/.bashrc
kubectl version --client

 

참조용 Cluster 생성 Flag 매트릭

eksctl create cluster \
		--name eks-an2-cnl-dev \
		--version 1.21 \
		--vpc-private-subnets SUBNET-ID-1,SUBNET-ID-2
		--without-nodegroup
eksctl create nodegroup \
		--cluster eks-an2-cnl-dev \
		--name nodegroup-an2-cnl-dev \
		--node-type t3.micro \
		--nodes 2 \
		--nodes-min 1 \
		--nodes-max 3 \
		#node-private-networking 옵션은 private-subnet 통신 과정에서 유리하게 작용
		--node-private-networking \ 
		--managed=false
        
#그 외 Flag 매트릭
General flags:
  -n, --name string               EKS cluster name (generated if unspecified, e.g. "scrumptious-sculpture-1648975311")
      --tags stringToString       A list of KV pairs used to tag the AWS resources (e.g. "Owner=John Doe,Team=Some Team") (default [])
  -r, --region string             AWS region
      --zones strings             (auto-select if unspecified)
      --version string            Kubernetes version (valid options: 1.12, 1.13, 1.14, 1.15) (default "1.14")
  -f, --config-file string        load configuration from a file (or stdin if set to '-')
      --timeout duration          maximum waiting time for any long-running operation (default 25m0s)
      --install-vpc-controllers   Install VPC controller that's required for Windows workloads
      --managed                   Create EKS-managed nodegroup
      --fargate                   Create a Fargate profile scheduling pods in the default and kube-system namespaces onto Fargate

Initial nodegroup flags:
      --nodegroup-name string          name of the nodegroup (generated if unspecified, e.g. "ng-46273157")
      --without-nodegroup              if set, initial nodegroup will not be created
  -t, --node-type string               node instance type (default "m5.large")
  -N, --nodes int                      total number of nodes (for a static ASG) (default 2)
  -m, --nodes-min int                  minimum nodes in ASG (default 2)
  -M, --nodes-max int                  maximum nodes in ASG (default 2)
      --node-volume-size int           node volume size in GB
      --node-volume-type string        node volume type (valid options: gp2, io1, sc1, st1) (default "gp2")
      --max-pods-per-node int          maximum number of pods per node (set automatically if unspecified)
      --ssh-access                     control SSH access for nodes. Uses ~/.ssh/id_rsa.pub as default key path if enabled
      --ssh-public-key string          SSH public key to use for nodes (import from local path, or use existing EC2 key pair)
      --node-ami string                Advanced use cases only. If 'ssm' is supplied (default) then eksctl will use SSM Parameter; if 'auto' is supplied then eksctl will automatically set the AMI based on version/region/instance type; if static is supplied (deprecated), then static AMIs will be used; if any other value is supplied it will override the AMI to use for the nodes. Use with extreme care.
      --node-ami-family string         Advanced use cases only. If 'AmazonLinux2' is supplied (default), then eksctl will use the official AWS EKS AMIs (Amazon Linux 2); if 'Ubuntu1804' is supplied, then eksctl will use the official Canonical EKS AMIs (Ubuntu 18.04). (default "AmazonLinux2")
  -P, --node-private-networking        whether to make nodegroup networking private
      --node-security-groups strings   Attach additional security groups to nodes, so that it can be used to allow extra ingress/egress access from/to pods
      --node-labels stringToString     Extra labels to add when registering the nodes in the nodegroup, e.g. "partition=backend,nodeclass=hugememory" (default [])
      --node-zones strings             (inherited from the cluster if unspecified)

Cluster and nodegroup add-ons flags:
      --asg-access            enable IAM policy for cluster-autoscaler
      --external-dns-access   enable IAM policy for external-dns
      --full-ecr-access       enable full access to ECR
      --appmesh-access        enable full access to AppMesh
      --alb-ingress-access    enable full access for alb-ingress-controller

VPC networking flags:
      --vpc-cidr ipNet                 global CIDR to use for VPC (default 192.168.0.0/16)
      --vpc-private-subnets strings    re-use private subnets of an existing VPC
      --vpc-public-subnets strings     re-use public subnets of an existing VPC
      --vpc-from-kops-cluster string   re-use VPC from a given kops cluster

 

Cluster 생성

#yaml 기반
eksctl create cluster -f cluster.yaml

 

Cluster 삭제

#eksctl로 생성된 클러스터만 eksctl로 삭제 가능
#삭제전 Cluster에서 실행 중인 서비스 조회
kubectl get svc --all -namespaces

#EXTERNAL-IP(LB) 삭제
kubectl delete svc <서비스 이름>

#Cluster 삭제
eksctl delete cluster --name <클러스터 이름>

#수행 LOG 마지막 줄
#2024-05-17 14:43:37 [✔]  all cluster resources were deleted

 


Pod

  • Pod는 대체적으로 container와 1:1 관계 (1:n 관계도 가능)
  • container는 Pod로 캡슐화가 되어있다.
  • k8s는 container에 직접 배포하지 않기에 캡슐화된 Pod를 배포한다.

 

Pod생성

 

kubectl run

kubectl run nginx --image nginx # nginx pod 기본 생성 명령어

#Namespace를 지정한 Pod 생성
kubectl run nginx --image nginx --namespace=<파드 이름>

#yaml 예시
apiVersion:
kind:
metadata:
	namespace:<파드 이름>
spec:

 

kubectl create

- yaml을 통해서 만드는 방식 (동일 Pod 존재할 경우 에러 발생)

kubectl ceate -f create-nginx.ymal

 

kubectl apply

- Pod가 없으면 new Pod를 생성, Pod가 존재하면 Update 한다.

kubectl apply -f apply-nginx.yaml

 

Pod 조회

kubectl get pods

#상세 조회
kubectl decribe pod nginx <오브젝트> <이름>

#nginx 파드의 상세 조회
kubectl describe pod nginx

#yaml 형식 조회
kubectl get pod nginx -o yaml

#조회 결과 output 저장
kubectl get pod nginx -o > output.yaml

#생성하지 않은 채로 output 저장
kubectl run nginx --image nginx --dry-run=client -o > yaml output.yaml

#output 조회
cat output.yaml

 

Pod 로그 조회

kubectl logs <파드 이름>

#tail -f 조회
kubectl logs -f <파드 이름>

 

Pod 삭제

kubectl delete <오브젝트> <이름>

#실행중인 nginx Pod 삭제
kubectl delete pod nginx

 

 

리소스 확인

 

Pod requests, limits 값 확인

kubectl get po -o yaml <파드 이름>

 


Deployment

  • 뒤이어 나올 ReplicaSet의 상위개념이라고 볼 수 있다.
  • ReplicaSet을 생성하는 Deployment를 정의할 수 있으며, 롤링 업데이트 등 세분화 조작할 수 있는 기능이다.

 

사용법

 

Deployment 생성

#create
kubectl create deployment <디플로이먼트 이름> --image=<이미지 이름>

#yaml
kubectl apply -f <YAML 파일>

 

Deployment 수정

kubectl edit deployment <디플로이먼트 이름>

#Deployment를 추가한 ReplicaSet Pod 설정
kubectl scale --replicas=N deployment <디플로이먼트 이름>

 

Deployment 업데이트(Roll Out)

- Pod가 실행 중인 상태에서 이미지 버전 변경 배포

- 이전 배포 정보는 스케일 다운, 새 배포는 ReplicaSet을 새로 생성하여 스케일 업

- 스케일 다운과 스케일 업은 부분적으로 동시에 발생

kubectl set image deployment/<디플로이먼트 이름> <컨테이너 이름>=<새 배포 태그>

#예시
kubectl set image deployment/sojuking-deployment nginx=nginx:1.23.4

 

Deployment Roll Out 조회

#상태 확인
kubectl rollout status deployment <디플로이먼트 이름>

#이력 확인
kubectl rollout history deployment <디플로이먼트 이름>

#리비전별 상세조회 Flag
# --revision=N

 

Deployment Roll Back

kubectl rollout undo deployment/<디플로이먼트 이름>

#특정 리비전 번호 N으로 롤백
kubectl rollout undo deployment/<디플로이먼트 이름> --to-revision=N

 

Deployment Scaling

#N개의 복제 파드 조정
kubectl scale deployment/<디플로이먼트 이름> --replicas=N

 

Deployment 조회

kubectl get deployment

#namespace
kubectl get deployment -n <네임스페이스>

 

Deployment 삭제

kubectl delete deployment <디플로이먼트 이름>

Set

ReplicaSet

  • Pod 개수를 유지하게 하는 가용성을 보증하는 장치
  • 예를 들어 Pod의 개수를 5개로 설정하였으면, Node가 다운되어 Pod가 사라져도 자동생성으로 Pod 수를 5개로 유지

 

사용법

 

ReplicaSet 생성

#create
kubectl create -f nginx-rs.yaml

#apply
kubectl apply -f nginx-rs.yaml

 

ReplicaSet 확인

#Cluster에 실행중인 ReplicaSet 조회
kubectl get rs

#ReplicaSet 상세 조회
kubectl describd rs

#yaml 형식 조회
kubectl get rs <레플리카셋 이름> -o=yaml

#Pod의 ReplicaSet 조회
kubectl get pod <파드> -o yaml

#실행 예시
kubectl get pod new-replica-set-a10jr -o yaml

#yaml 예시
apiVersion: app/v1
kind: ReplicaSet
metadata:
    name:
spec:
    template:
        metadata:
            name: <파드 이름>
            labels:
                app:
                type:
        spec:
            containers:
            - name: nginx-controller
              image: nginx
    seletor:
        matchLabels:
            type: <파드 라벨>

 

ReplicaSet Scaling

#N개의 복제 파드 조정
kubectl scale rs <레플리카셋 이름> --replicas=N

#예시
kubectl scale rs sojuking --replicas=5

 

ReplicaSet 편집

kubectl edit rs <레플리카셋 이름>

 

ReplacaSet 리소스 삭제

#리소스만 삭제
kubectl delete rs --cascade=orphan <레플리카셋 이름>

#Pod까지 삭제
kubectl delete rs <레플리카셋 이름>

 

DaemonSet

  • Cluster 내 새로운 Node가 하나 생길 때마다, Pod 복제본이 자동으로 Node에 생성 (자동 배포 기능)
  • Cluster 내 모든 Node에는 항상 1개 이상의 Pod 복사본이 존재하도록 보장

 

ReplacaSet과 마찬가지로 DaemonSet도 kind만 제외하고 정의 내용이 같다.

#yaml 예시
apiVersion: app/v1
kind: DaemonSet
metadata:
    name:
spec:
    template:
        metadata:
            name: <파드 이름>
            labels:
                app:
                type:
        spec:
            containers:
            - name: nginx-controller
              image: nginx
    seletor:
        matchLabels:
            type: <파드 라벨>

 

StatefulSet

  • StatefulSet은 각 파드의 독자성을 유지
  • Pod 집합의 Deployment와 Scailing을 관리하며, Pod의 순서 및 고유성을 보장
  • 상태가 없는 앱/웹은 Deployment로 배포, 상태가 있는 DB 같은 경우는 StatefulSet으로 배포한다.

 

 StatefulSet은 Cluster IP가 없는 헤드리스 서비스를 사용해야 한다.

vi soju-sts.yaml

#yaml 예시
apiVersion: app/v1
kind: StatefulSet
metadata:
    name: soju-sts
spec:
  selector:
    matchLabels:
      app: soju-sts
  serviceName: soju-svc-headless #추가된 헤드리스 서비스 이름
  replicas: 2
  template:
    metadata:
      labels:
        app: soju-sts
    spec:
      containers:
      - name: myapp
        image: ghcr.io/fn1vkd2/go-myweb:lupine
        ports:
        - containerPort: 8080

 

Cluster IP가 없는 Service

vi soju-svc-headless.yaml #StatefulSet에 정의한 헤드리스 서비스의 본체

apiVersion: v1
kind: Service
metadata:
  name: soju-svc-headless
  labels:
    app: soju-svc-headless
spec:
  ports:
  - name: http
    port: 80
  clusterIP: None #헤드리스 서비스 정의( Cluster IP: None)
  selector:
    app: soju-sts #soju-sts.yaml의 label 조회

 

StatefulSet 생성

kubectl -f soju-sts.yaml -f soju-svc-headless.yaml

 

StatefulSet 조회

kubectl get sts, svc, ep #sts: statefulSet, svc: service, ep: endpoint

#Controller 뒤의 번호 생성 조회 (고유성)
kubectl get pod -o wide

#network-multitool 이미지 실행
kubectl run nettool --image ghcr.io/fn1vkd2/network-multitool -it --rm

#nettool < Pod 이름 생성
#--image 이미지 지정
#-it Pod를 인터랙티브 모드 실행, 터미널 할당 및 실시간 상호작용 상태
#--rm Pod 종료시 자동 Pod 삭제

#호스트 질의 - 서비스 이름 지정
host soju-svc headless

# StatefulSet + headless >> Pod의 이름으로 통신하여 Pod의 IP 변환
host soju-sts-0.soju-svc-headless
host soju-sts-1.soju-svc-headless

 


Job

Job

  • 프로세스가 종료되면 Container가 다시는 시작되지 않는 배치라 보면 된다.
  • 노드에 장애가 발생하면 ReplicaSet의 파드와 같은 방식으로 다른 노드로 재스케줄 기능이 있다.
  • 프로세스 오류일 경우 Container를 재실행하도록 할 수 있다.

YAML 리소스 구성

apiVersion: batch/v1 # API 그룹은 batch 버전 v1
kind: Job
metadata:
  name: soju-job
spec:    
  template:
    spec:
      containers:
      - name: soju-job
        image: 2.mi.g
        command: ["Job 끝내고 쐐애주나 마시자!"]
      restartPolicy: Never #Pod의 재시작 정책 설정
      completions: 2 #실행 종료되어야 하는 파드 수 설정 (기본값 1)
      parallelism: 2 #잡 병렬성 관리(기본값 1)
  backoffLimit: 2 #재시도 횟수 설정
  activeDeadlineSeconds: 100 #Pod의 실행시간 설정(넘으면 Pod 종료 시도 및 Job은 Fail)

 

Job 삭제

#Job을 삭제하면 관련 Pod도 같이 삭제가 된다.
kubectl delete job <잡 이름>

 

Cronjob

  • 반복 작업을 실행하는 데 사용하는 리소스 중 하나, 지정된 시간 또는 간격으로 작업 생성한다.
  • Linux의 crontab 기능을 떠올리면 된다.

 

YAML  리소스 구성

apiVersion: batch/v1 # API 그룹은 batch
kind: CronJob
metadata:
  name: soju-cronjob
spec:
  schedule: "*/1 * * * *"   #매 1분마다 실행
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: soju-cronjob
            image: busybox
            command: ["퇴근하고 쐐애주나 마시자!"]
          restartPolicy: OnFailure
  concurrencyPolicy: Forbid

 

CronJob 조회

kubectl get cronjobs

 

CronJob 삭제

kube delete cronjobs <크론잡 이름>

Resource 

  • 다수의 컨테이너가 Pod에 있으면 Request와 Limit은 각각의 컨테이너에 개별적으로 할당
  • Resource 중 CPU는 Resource Limit 보다 초과로 사용 불가, Memory는 사용 가능하나 Pod 다운 및 OOM 발생

 

Resource 감시

 

kubectl top 설치

-top을 사용하기 위하여 명령어로 설치

git clone https://github.com/kodekloudhub/kubernetes-metrics-server.git
cd kubernetes-metrics-server/
kubectl create -f

 

CPU, Memory 사용율 확인

#node 확인
kubectl top node

#pod 확인
kubectl top pod

 

 

Resource 제한

 

Resource Limit 

-Pod 내 리소스 사용량을 제한

apiVersion: v1
kind: Pod
metadata:
    name:
spec:
    containers:
    - name: sojuking
      image: nginx
      ports:
        - containerPort: 8080
      resources:
        requests: #요구되는 리소스 양
          memory: "2Gi"
          cpu: 2
        limit: #리소스 사용 제한
          memory: "4Gi"
          cpu: 4

 

 

Resource Quotas

- K8s 내 배포된 전체 애플리케이션이 소모하는 전체 리소스의 양을 제한

- namespace 레벨에서 적용

apiVersion: v1
kind: ResourceQuota
metadata:
  name: sojuking-quota
spec:
  hard:
    requests.cpu: 2
    requests.memory: 2Gi
    limits.cpu: 10
    limits.memory: 10Gi

krew

  • kubectl을 보다 편리하게 사용할 수 있게 해주는 Plugin 관리 도구이다.
  • kubectl v1.12 이상의 버전에서 사용 가능하다.
  • git 설치가 되어 있어야 한다.

 

설치법

 

설치 명령어

(
  set -x; cd "$(mktemp -d)" &&
  OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
  ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
  KREW="krew-${OS}_${ARCH}" &&
  curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
  tar zxvf "${KREW}.tar.gz" &&
  ./"${KREW}" install krew
)

 

Path 추가

export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"

 

설치 확인

kubectl krew

 

 

사용법

 

Plugin 설치

kubectl krew install NAME <플러그인 이름>

#예시
kubectl krew install sojuking

 

Plugim 사용

kubectl <플러그인 이름>

 

Plugin 업데이트

kubectl krew upgrade <플러그인 이름>

#모든 플러그인 업그레이드
kubectl krew upgrade

 

Plugin 검색

kubectl krew search KEYWORD

#모든 플러그인 목록 확인 (키워드 제거)
kubectl krew search

#설치 플러그인 목록 확인
kubectl krew list

 

 

Plugin 삭제

kubectl krew uninstall <플러그인 이름>

 


 

 

 

'Architecture' 카테고리의 다른 글

K8s 1) 쿠버네티스 기본  (0) 2024.05.17
Kafka 3) MSK Cluster 모니터링 메트릭  (2) 2024.01.11
Kafka 2) 모니터링  (2) 2024.01.11
Kafka 1) 연결 모니터링  (2) 2024.01.11
MSA 5) MSA 분리 전략 : 도메인 주도 설계  (0) 2023.11.01

개요

DB관련 글을 작성중에 문득 어느 곳에서는 '컬럼'이라고 발음하고,
어느 곳에서는 '칼럼'이라고 발음 하는 경우를 꽤나 많이 보았다.
과연 무엇이 맞는 표기법인지 궁금하여 분석해 봤다.


시작

A. 아래는 구글에  column을 칼럼으로 검색하였을 경우이다.


B. 아래는 구글에 column을 컬럼으로 검색한 결과이다.

 
- 대체적으로 공식력 있는 사이트에서는 '칼럼' 대신에 '컬럼'으로 사용되는 것을 확인할 수 있다.
  그렇다면 영어 단어인 'Column'의 발음을 살펴보자.
 
 


C. 아래는 네이버 영어사전에 명시되어 있는 Column 발음표이다.

미국식과 영국식의 발음이 다른데, /ɑː/ 와 /ɒ/ 차이인 것을 확인할 수 있다.
발음에 대해서 정리가 잘된 블로그의 글을 인용했다. 그럼 어떻게 다른지 한 번 보자.
 

미국식

ɑː =  [ɑ -ㅏ] + [ː - 장음] 

/ ɑː / 는 단순히 [아-] 가 아니다.
입을 더 이상 벌릴 수 없을 정도로 크게 벌린다.
하품을 할 때와 비슷하고 목구멍 깊은 곳에서 내는 강한 모음이다.
영국 영어다운 모음이다.
/ ɑː / 발음의 강한 울림은 RP와 런던 등 남부 발음을 느끼게 한다.
입을 적게 벌리게 되면 목 깊은 소리가 나지 않고 / aː / 에 가까운 발음이 된다.
/ aː / 는 영국 북부나 호주의 특징이 되는 모음이다.
ex) garden, party, glasses, dance, far

 

영국식 

ɒ = [ ɒ -ㅗ] or [ ɒ -ㅏ]
/ ɒ / 는 최대한 입을 벌려 힘차고 짧게 [오] 처럼 발음한다. 정확하게는 [오아]이다.
정통파 UK 발음을 배우려면 / ɒ / 는 반드시 익혀야 하는 발음이다.
ex) clock, hot, stop, coffee, long

출처 : 50177117님의 블로그

- ɒ 는 관용에 따른 표기가 재각각이라 좀 애매한 부분이 있다. 하기와 같은 이유이다.

  <외래어 표기법 제1장 제5항>
  이미 굳어진 외래어는 관용을 존중하되, 그 범위와 용례는 따로 정한다.
  ex.) body, hot 등
 

- 무튼간 조금씩 다르지만 미국식이나 영국식 모두 '' 가 속해 있다
  그렇다면 마지막으로 국립국어원으로 가보자.
 


D. 국립국어원 에서의 Column

단어 규정용례를 보자면 다음과 같다.

- 딱히.. 설명이 부실하지만 오표기에 '컬럼'이 존재하지 않는게 좀 걸린다.
  외래어 표기법의 영어 7항을 보면, 장음은 삭제가 된다. 따라  '카알람'은 아니니, '칼람'이 맞는 것은 100% 확실하다.
  외래어 표기법에는 /ɒ/ 에 대해서는 안 나와 있다.
  칼람은 그렇다 치고 사람들이 왜, 컬럼으로 부르게 된 계기도 궁금해서 질문을 해봤다. 


- 이 질문은 답변을 기다려 봐야겠다. (답변이 올런지..)


결론

필자도 '컬럼'으로 알고 있어 공부하다가 책에서 '칼럼' 하면 '왜 칼럼이라고 할까?' 싶었지만
본인이 외래어 표기법을 제대로 숙지 못했을 뿐. 익숙하지는 않지만 칼럼이라 부르도록 노력해야겠다. 
 
그나저나 공식력 있는 사이트에서 컬럼으로 표기되고 있는 곳이 매우 많다는 것이 놀라울 따름이다.
 
 

+ Recent posts