CKA

(TIL) Kubernetes Labels & Selectors

심플코더 2025. 3. 23. 22:53

Labels란

Key-Value 형식의 메타데이터로 Kubernetes 객체에 붙일 수 있는 정보이다.

객체를 분류하고 그룹화하기위한 용도로 사용된다.

 

Selector란

Labels 기반으로 필터링을 진행하기 위한 도구로 특정 조건을 기준으로 Kubernetes 객체를 선택한다.

kubectl get pods --selector="app=frontend"

 

사용 예시

apiVersion: v1
kind: Pod
metadata:
  name: mypod
  labels:
    app: app1
    tier: frontend
spec:
  containers:
    - name: nginx
      image: nginx

 

kubectl get pods --selectors="app=app1" 이라는 명령어를 통해 위 객체를 필터링하여 리턴받을 수 있다.

 

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: my-replicaset
  labels:
    app: app1 
spec:
  replicas: 3
  selector:
    matchLabels:
      app: app1
      tier: frontend 
  template:
    metadata:
      labels:
        app: app1
        tier: frontend 
    spec:
      containers:
        - name: nginx
          image: nginx

 

위 예시는 replicaSet에서 Selector를 사용하는 예시로 spec.selector.matchLabels와 template.metadata.labels가 정확히 일치해야만 pod-replicaSet의 연결이 이루어진다.