오브젝트 & yaml 설명

KingTG·2024년 3월 31일

도커&k8s

목록 보기
9/13

오브젝트

  • 쿠버네티스 공식 문서

https://kubernetes.io/ko/docs/concepts/overview/working-with-objects/kubernetes-objects/

오브젝트란?

파드와 디플로이먼트는 스팩(spec)과 상태(status) 등의 값을 가지는데 이러한 값을 가지고 있는 파드와 디플로이먼트를 개별 속성을 포함해 부르는 단위를 오브젝트라고 한다.

  • 쿠버네티스는 이 상태를 영구히 유지하기 위해 작동한다.
  • 어떤 컨테이너화된 app이 동작중인지(어떤 노드에서 동작 중인지)
  • app이 이용할 수 있는 리소스
  • app의 재구동 정책,업그레이드

쿠버네티스의 기본 오브젝트

  • 파드(Pod) - 쿠버네티스에서 실행되는 최소 단위 (독립공간과 ip를 가진다.)
  • 네임스페이스(Namespace) - 쿠버네티스 클러스터에서 사용되는 리소스들을 구분해 관리하는 그룹
  • 볼륨(Volume) - 파드가 생성될 때 파드에서 사용할 수 있는 디렉토리 제공 (임지로 사용하지만 파드가 사라지더라도 저장과 보존이 가능한 디렉토리를 생성하고 사용할 수 있음)
  • 서비스(Service) - 파드는 클러스터 내에서 유동적이기 때문에 접속 정보가 고정되지 않는데 파드 접속을 안정적으로 유지하도록 서비스를 통해 내/외부로 연결

그 외 오브젝트

  • 디플로이먼트
  • 데몬셋
  • 컨피그맵
  • 레플리카셋
  • PV
  • PVC
  • 스테이트풀셋

  • 마스터 노드에 접속해 디렉토리 생성

mkdir -p /root/k8s-local-volume/1231

  • 쿠버네티스대시보드에 접속해 yaml파일 넣기

Namespace

  • 네임스페이스는 오브젝트들을 그룹핑 해준다.
apiVersion: v1
kind: Namespace
metadata:
  name: anotherclass-123
  labels:
    part-of: k8s-anotherclass
    managed-by: dashboard

Deployment

  • 파드를 만들고 업그레이드
apiVersion: apps/v1
kind: Deployment
metadata:
# 여기에 써준 네임스페이스에 소속된다.
  namespace: anotherclass-123
  name: api-tester-1231
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
    version: 1.0.0
    managed-by: dashboard
spec:
  selector:
    matchLabels:
      part-of: k8s-anotherclass
      component: backend-server
      name: api-tester
      instance: api-tester-1231
  
  # 파드의 갯수 설정
  replicas: 2
  strategy:
  # 업데이트 방식
    type: RollingUpdate
    
 # template 부터 내용대로 파드가 만들어 진다
  template:
    metadata:
      labels:
        part-of: k8s-anotherclass
        component: backend-server
        name: api-tester
        instance: api-tester-1231
        version: 1.0.0
    spec:
    # 파드를 띄울 노드를 선택
      nodeSelector:
        kubernetes.io/hostname: k8s-master
      containers:
        - name: api-tester-1231
        # 도커허브 주소
          image: 1pro/api-tester:v1.0.0
          ports:
          - name: http
            containerPort: 8080
            
            # 컨피그맵과 연결이 되어있고 app의 환경변수 부분
          envFrom:
            - configMapRef:
                name: api-tester-1231-properties
                
                # app이 잘 기동 됐는지 체크 기동이 안되면 재시작 잘되면 read,live 시작
          startupProbe:
            httpGet:
              path: "/startup"
              port: 8080
            periodSeconds: 5
            failureThreshold: 24
            
            # app에 트래픽을 연결 결정하는 속성
          readinessProbe:
            httpGet:
              path: "/readiness"
              port: 8080
            periodSeconds: 10
            failureThreshold: 3
            
            # app이 정상이 아니면 재시작하는 속성
          livenessProbe:
            httpGet:
              path: "/liveness"
              port: 8080
            periodSeconds: 10
            failureThreshold: 3
            
            # 파드 하나에 cpu와 메모리 할당 설정하지 않으면 모든 자원 소모
          resources:
            requests:
              memory: "100Mi"
              cpu: "100m"
              
              # 최대 사용량
            limits:
              memory: "200Mi"
              cpu: "200m"
              
              # 볼륨 연결
          volumeMounts:
          # 밑에 volumes.name이랑 매칭이 되서 persistentVolumeClamim이라는 오브젝트랑 연결
            - name: files
            # 마운트될 주소
              mountPath: /usr/src/myapp/files/dev
              # 밑에 volumes.name이랑 연결되서 시크릿 오브젝트랑 연결
            - name: secret-datasource
              mountPath: /usr/src/myapp/datasource
      volumes:
        - name: files
          persistentVolumeClaim:
            claimName: api-tester-1231-files
        - name: secret-datasource
          secret:
            secretName: api-tester-1231-postgresql

Service

  • 파드한테 트래픽 연결
apiVersion: v1
kind: Service
metadata:
  namespace: anotherclass-123
  # 서로다른 오브젝트끼리는 이름이 같아도 가능
  name: api-tester-1231
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
    version: 1.0.0
    managed-by: dashboard
spec:
  selector:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
  ports:
    - port: 80
      targetPort: http
      nodePort: 31231
  type: NodePort

Configmap, Secret

  • 파드에 환경변수 값을 제공
apiVersion: v1
kind: ConfigMap
metadata:
  namespace: anotherclass-123
  name: api-tester-1231-properties
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
    version: 1.0.0
    managed-by: dashboard
    
    # 환경변수에 들어갈 값의 내용
data:
  spring_profiles_active: "dev"
  application_role: "ALL"
  postgresql_filepath: "/usr/src/myapp/datasource/postgresql-info.yaml"
---
apiVersion: v1
kind: Secret
metadata:
  namespace: anotherclass-123
  name: api-tester-1231-postgresql
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
    version: 1.0.0
    managed-by: dashboard
stringData:
# yaml파일 파드안에 만들어짐
  postgresql-info.yaml: |
    driver-class-name: "org.postgresql.Driver"
    url: "jdbc:postgresql://postgresql:5431"
    username: "dev"
    password: "dev123"

PVC, PV

  • PVC(PersistentVolumeClaim) - 저장공간, RW모드 등 요청사항을 기술하여 PV에 전달, PV와 바이딩하는 목적으로 사용

  • PV(PersistentVolume) - 데이터를 저장할 볼륨을 생성하고 이를 클러스터에 등록

  • PVC,PV는 클러스터 레벨의 오브젝트이고, 디플로이와 서비스는 네임스페이스 레벨의 오브젝트

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  namespace: anotherclass-123
  name: api-tester-1231-files
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
    version: 1.0.0
    managed-by: kubectl
spec:
  resources:
    requests:
    # 저장공간
      storage: 2G
      # 읽기/쓰기 부여
  accessModes:
    - ReadWriteMany
  selector:
    matchLabels:
      part-of: k8s-anotherclass
      component: backend-server
      name: api-tester
      instance: api-tester-1231-files
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: api-tester-1231-files
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231-files
    version: 1.0.0
    managed-by: dashboard
spec:
  capacity:
    storage: 2G
  volumeMode: Filesystem
  accessModes:
    - ReadWriteMany
    
    # path를 볼륨으로 사용 path가 사전에 없으면 문제가 생기므로 미리 경로에 디렉토리를 만들어 준다
  local:
    path: "/root/k8s-local-volume/1231"
    
    # 대상 노드 위치 설정
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - {key: kubernetes.io/hostname, operator: In, values: [k8s-master]}

HPA

  • 부하에 따라 파드를 늘려주고 줄여주는 스케일링 역할
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  namespace: anotherclass-123
  name: api-tester-1231-default
  labels:
    part-of: k8s-anotherclass
    component: backend-server
    name: api-tester
    instance: api-tester-1231
    version: 1.0.0
    managed-by: dashboard
spec:
# 스케일링 대상
  scaleTargetRef:
    apiVersion: apps/v1
    # 오브젝트 종류 설정
    kind: Deployment
    name: api-tester-1231
    # 최소, 최대
  minReplicas: 2
  maxReplicas: 4
  # 파드에 cpu가 60% 늘어나면 스케일 아웃
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60
         
 # 파드가 한번 증가한 후 120초 동안 파드가 더 늘어나지 않도록 설정
 # 늘어나자마자 다시 늘리고 싶지 않을 때 설정         
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 120

네임스페이스 삭제

kubectl delete ns anotherclass-123

pv 삭제

kubectl delete pv api-tester-1231-files

삭제시 알아야 될 점

  • 네임스페이스를 삭제하면 안에 있는 오브젝트들이 모두 삭제된다.
  • pv는 네임스페이스에 속하지 않기 때문에 별도로 삭제 해주어야 된다.

0개의 댓글