[Kubernetes] Object 그려보며 이해하기

2025. 5. 31. 21:45·Kubernetes
반응형

Object 이해하기

쿠버네티스를 구성하는 각 Object의 구성을 그려보면 아래와 같다.

 

아래 각 Object를 생성하는 yaml 내용의 주석을 통해 각 상세한 내용을 이해해 보자.

 

참고로 아래 yaml들을 그대로 쿠버네티스 대시보드에 입력하면 생성이 되는데,

그 전에 아래 명령어를 통해 디렉토리를 생성해 두어야 한다.

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

 

출처 : https://cafe.naver.com/kubeops/36

Namespace

  • Namespace : Object들을 그룹핑해주는 역할.
apiVersion: v1
kind: Namespace
metadata:
  name: anotherclass-123
  labels:
    part-of: k8s-anotherclass
    managed-by: dashboard

 

Deployment

  • Deployment : 배포 설정을 지정하는 역할.
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: anotherclass-123 # 소속될 Namespace 이름
  name: api-tester-1231 # Deployment 이름. 한 Namespace에서 같은 Object끼리 중복되면 안된다.
  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 # 만들 Pod 개수
  strategy:
    type: RollingUpdate # Pod 업데이트 방식
  template: # 만들 Pod 양식
    metadata:
      labels:
        part-of: k8s-anotherclass
        component: backend-server
        name: api-tester
        instance: api-tester-1231
        version: 1.0.0
    spec:
      nodeSelector: # Pod를 띄울 노드
        kubernetes.io/hostname: k8s-master
      containers:
        - name: api-tester-1231
          image: 1pro/api-tester:v1.0.0 # Dockerhub 기준 컨테이너 이미지.
          ports:
          - name: http
            containerPort: 8080
          envFrom: # Application의 환경 변수
            - configMapRef: # 환경 변수를 제공해주는 ConfigMap 설정
                name: api-tester-1231-properties
          startupProbe: # App 기동 여부 확인하는 Probe
            httpGet:
              path: "/startup"
              port: 8080
            periodSeconds: 5
            failureThreshold: 36
          readinessProbe: # App에 트래픽 연결 여부를 결정하는 Probe
            httpGet:
              path: "/readiness"
              port: 8080
            periodSeconds: 10
            failureThreshold: 3
          livenessProbe: # App이 정상이 아닌 경우 재시작을 판단하는 Probe
            httpGet:
              path: "/liveness"
              port: 8080
            periodSeconds: 10
            failureThreshold: 3
          resources: # Pod에 할당할 리소스. 설정하지 않으면 Pod가 노드의 자원을 모두 사용하게 된다
            requests: # 최초 Pod에 할당할 리소스 
              memory: "100Mi"
              cpu: "100m"
            limits: # 최대 Pod에서 사용 가능한 리소스
              memory: "200Mi"
              cpu: "200m"
          volumeMounts:
            - name: files # 아래 volumes의 name과 매칭되어 연결되도록 설정하는 이름
              mountPath: /usr/src/myapp/files/dev # Pod 내부에 만들어지는 디렉토리
            - 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

  • Service : Pod에게 트래픽을 연결시켜주는 역할.
apiVersion: v1
kind: Service
metadata:
  namespace: anotherclass-123
  name: api-tester-1231 # Deployment와는 kind가 달라서 이름이 같아도 무방하다.
  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

  • ConfigMap : Pod에 환경 변수 값을 제공하는 역할.
  • Secret : ConfigMap과 비슷하나 Pod에 조금 더 중요한 값을 제공하는 역할.
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: # 정의한 key 이름으로 된 파일이 Pod 안에 생성된다
  postgresql-info.yaml: |
    driver-class-name: "org.postgresql.Driver"
    url: "jdbc:postgresql://postgresql:5431"
    username: "dev"
    password: "dev123"

 

PVC, PV

  • PVC(Persistent Volume Claim) : Pod에서 PV를 지정할 때 사용.
  • PV (Persistent Volume) : 실제 Volume을 지정하는 역할. Namespace에 소속되지 않은 Cluster Level Object이다.
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
  local:
    path: "/root/k8s-local-volume/1231" # Volume으로 사용할 경로. 해당 디렉토리가 사전에 존재해야 한다
  nodeAffinity: # 대상 노드 지정
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - {key: kubernetes.io/hostname, operator: In, values: [k8s-master]}

 

HPA

  • HPA(Horizontal Pod Autoscaler) : 부하에 따라 Pod를 늘려주고 줄여주는 스케일링 역할.
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 # 최소 유지할 Pod 개수
  maxReplicas: 4 # 최대 유지될 수 있는 Pod 개수
  metrics: # 스케일 아웃할 조건 설정
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60
  behavior:
    scaleUp: # 실제로는 스케일 아웃인데 명칭만 scaleUp
      stabilizationWindowSeconds: 120 # 스케일 아웃 이후 다음 스케일 아웃 대기 시간

Prometheus 설치로 이해하는 labels

labels는 Object에 걸려있는 App 정보를 바로 파악하기 위해 사용한다.

 

Prometheus는 쿠버네티스에서 권고하는 labels 설정 방법을 잘 따라서 만들어져 있다.

따라서 아래 Prometheus 그림을 통해 labels 속성을 이해해 보자.

  • part-of : Application의 전체 이름. 전체 서비스를 대표하는 이름이라고 생각하면 된다.
  • component : 이 서비스를 구성하고 있는 각각의 분리된 기능. part-of 아래에 여러 component들이 존재한다.
  • name : Application의 실제 이름. component 아래에 여러 App들이 존재할 수 있다.
  • instance : 목적에 따라 전체 App(part-of)을 여러 개 설치할 수 있는 Instance 식별자.
    • Prometheus에서는 k8s라고만 되어있으나, 쿠버네티스 가이드에서는 name에 식별자를 추가하는 예시가 많아서 이를 따르기 위해 prometheus-k8s로 변경했다.
  • version : App 버전이 변경될 때 수정이 필요한 버전. labels들 중 자주 수정되는 유일한 정보.
  • managed-by : 어떤 도구로 배포되었는지 기입하는 정보. 해당 Object를 생성하고 관리하는 주체를 확인하기 위함.

 

네이밍 규칙

네이밍 규칙에 대해 쿠버네티스에서는 권고하는 내용이 없다.

다만 현실적으로 인프라를 관리할 때 권장되는 네이밍 규칙은 아래와 같다.

  • Namespace : Namespace에 들어가는 App들에 대한 범위를 나타내는 이름.
  • 기타 Object : instance명으로만들어 두면 웬만해서는 같은 Object들 간의 이름이 겹칠 일이 없다.
    • 여러 개 붙일 수 있는 Object의 경우 그 뒤에 사용 목적에 따라 네이밍을 추가한다.

실습을 위한 인프라 구성

  • Deployment의 replicas 속성을 복사하여 ReplicaSet이라는 Object를 만든다.
    • ReplicaSet의 이름은 Deployment 이름에 임의의 문자가 추가된 형태로 만들어졌다.
  • ReplicaSet이 replicas 수 만큼 Pod를 생성한다. 삭제를 하더라도 ReplicaSet이 감지하고 다시 생성한다.
    • Pod의 이름은 ReplicaSet의 이름에 임의의 문자가 추가된 형태로 만들어졌다.
  • 각 목적에 맞게 여러 개 사용되는 경우 사용 목적에 맞게 네이밍을 추가한다.
    • Pod에는 서비스를 여러 개 덧붙일 수 있어 목적에 따라 internal / external 등의 네이밍 추가
    • 특정 이벤트를 위해 임계치를 다르게 준 HPA를 설정하기 위한 네이밍 추가
    • 별도로 사용하는 목적에 맞는 ConfigMap을 구성하기 위한 네이밍 추가

 

쿠버네티스 Object 간 연결

쿠버네티스에서 Object 간 연결하는 방법은 아래 두 가지 방법이 있다.

 

selector

labels는 App 정보를 파악하기 위한 목적 말고도,

selector와 매칭이 되어 두 Object를 연결하는 데 사용된다.

 

이 때 selector의 내용이 모두 labels에 포함되어야 한다.

(사실 instance가 고유한 이름을 가지므로 나머지 필드는 선택사항이다.)

 

Object 내에서 대상을 연결하는 속성

Object가 대상을 연결하기 위해 아래와 같이 자체적으로 속성을 제공하는 경우가 있다.

  • HPA : scaleTargetRef로 Deployment 이름 지정
  • Deployment : configMapRef에서 ConfigMap 지정, volumes에서 PVC 및 Secret 지정

최종 정리

Node도 클러스터를 구성하면서 쿠버네티스가 자동으로 만들어 놓은 Object가 있다.

해당 Object에도 labels이 있고, Pod의 nodeSelector, PV의 nodeAffinity가 해당 labels과 연결된다.

 

이 내용까지 포함하여 최종적으로 정리한 그림은 아래와 같다.

  • labels 앞에 prefix를 붙일 수 있는데, 이는 도메인을 가리킨다.
  • labels에 owner, realease 등 의미있는 정보들을 더 만들어 두고 관리하면좋다.
  • 여러 종류의 selector들이 있고 각각의 사용 방법들이 다르지만, 외울 필요 없이 템플릿에 맞춰서 사용하면 된다.

출처

https://inf.run/Ncohz
 

쿠버네티스 어나더 클래스 (지상편) - Sprint 1, 2 강의 | 일프로 - 인프런

일프로 | ⚓쿠버네티스(Kuberentes, Containerd, Docker Hub, Helm, Jenkins, Kustomize, ArgoCD) 🙇‍♀️아직 망설이시나요? 🙋‍♂️저만 믿고 따라오세요! 이론과 실습으로 당신의 실력을 ⭐어나더 레벨로 만

www.inflearn.com

반응형

'Kubernetes' 카테고리의 다른 글

[Kubernetes] Application 기능으로 이해하는 ConfigMap, Secret  (2) 2025.06.04
[Kubernetes] Application 기능으로 이해하는 Probe  (0) 2025.06.02
[Kubernetes] 실무에서 쿠버네티스가 정말 편한 이유  (0) 2025.05.30
[Kubernetes] 무게감 있게 쿠버네티스 설치  (0) 2025.05.29
[Kubernetes] 컨테이너 한 방 정리  (1) 2025.05.27
'Kubernetes' 카테고리의 다른 글
  • [Kubernetes] Application 기능으로 이해하는 ConfigMap, Secret
  • [Kubernetes] Application 기능으로 이해하는 Probe
  • [Kubernetes] 실무에서 쿠버네티스가 정말 편한 이유
  • [Kubernetes] 무게감 있게 쿠버네티스 설치
hojun-dev
hojun-dev
개발과 함께하는 일상을 그리는 블로그입니다.
  • hojun-dev
    개발 일상
    hojun-dev
  • 전체
    오늘
    어제
    • 분류 전체보기 (69)
      • Java & Spring (15)
      • Kubernetes (17)
      • Javascript (2)
      • Linux (2)
      • Setting (16)
      • Work (4)
      • 일상 (10)
      • 항해플러스 (3)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
hojun-dev
[Kubernetes] Object 그려보며 이해하기
상단으로

티스토리툴바