오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-08 00:00
관리 메뉴

우노

[K8S] labels, selector, match_labels의 차이 본문

DevOps/Kubernetes

[K8S] labels, selector, match_labels의 차이

운호(Noah) 2023. 10. 18. 18:20

들어가기 앞서,

  • Kubernetes의 Service는 특정 Pod에 네트워크 트래픽을 라우팅하는 역할을 합니다.
    • Service는 라벨 셀렉터(spec.selector)를 통해,
    • 해당 라벨과 동일한 라벨(spec.template.metadata.labels)을 가지고 있는 Pod에게 네트워크 트래픽을 라우팅하게 됩니다.
  • 하지만, 라우팅 설정에 사용되는 라벨 관련 필드는 다양하기 때문에 헷갈릴 수 있습니다.
    • service
      • spec.selector (Service가 어떤 Pod에 라우팅할지 정하기 위한 라벨 셀렉터)
    • deployment
      • metadata.labels (Deployment에 할당되는 라벨)
      • spec.selector.match_labels (Deployment가 어떤 Pod를 관리할지 정하기 위한 라벨 셀렉터)
      • spec.template.metadata.labels (Pod에 할당되는 라벨)
  • 따라서, 해당 포스팅에선 Service, Deployment 생성 예제를 통해 labels, selector, match_labels의 차이에 대해서 이해해보겠습니다.
  • 자원 생성 예제는 Terraform을 기반으로 설명하겠습니다.

Service 생성 코드

resource "kubernetes_service" "nginx" {
  metadata {
    name = "nginx-service"
  }

  spec {
    # Service가 어떤 Pod에 라우팅할지 정하기 위한 라벨 셀렉터
    selector = {
      app = "nginx"
    }

    port {
      port        = 80  # 서비스로 라우팅할 포트
      target_port = 80  # 선택한 Pod의 어떤 포트로 트래픽을 전달할지 설정
    }
  }
}

Deployment 생성 코드

resource "kubernetes_deployment" "nginx" {
  metadata {
    name = "nginx-deployment"
    labels = {
      app = "nginx"  # Deployment에 할당되는 라벨
    }
  }

  spec {
    replicas = 2

    # Deployment가 어떤 Pod를 관리할지 정하기 위한 라벨 셀렉터
    selector {
      match_labels = {
        app = "nginx"
      }
    }

    template {
      metadata {
        labels = {
          app = "nginx"  # Pod에 할당되는 라벨
        }
      }

      spec {
        container {
          image = "nginx:latest"
          name  = "nginx"
          port {
            container_port = 80
          }
        }
      }
    }
  }
}

요약

  • Service, Pod 라우팅을 위해선 Service의 spec.selector와 Deployment의 spec.template.metadata.labels가 일치해야합니다!
  • 또한, Deployment가 Pod를 관리하기 위해선 Deployment의 spec.selector.match_labels와 spec.template.metadata.labels가 일치해야합니다!
  • 즉, 아래 3가지 구성요소가 모두 일치해야합니다.
    • Service
      • spec.selector (Service가 어떤 Pod에 라우팅할지 정하기 위한 라벨 셀렉터)
    • Deployment
      • spec.selector.match_labels (Deployment가 어떤 Pod를 관리할지 정하기 위한 라벨 셀렉터)
      • spec.template.metadata.labels (Pod에 할당되는 라벨)
Comments