[Kubernetes] selector, matchLabels, app, template 개념 정리
Kubernetes에서 selector, matchLabels, app, template이 어떻게 Service, Deployment, DaemonSet, Pod를 연결하는지 예제 YAML과 함께 정리합니다.
selector, matchLabels, app, template의 사용 목적
Kubernetes에서는
Service, Deployment, DaemonSet, Pod 등이 Label 기반으로 서로 연결됩니다.
이때 핵심 역할을 하는 요소가 바로 다음 네 가지입니다.
selectormatchLabelsapptemplate
이 값들이 어떻게 연결되는지를 이해하면
Kubernetes 리소스 간 관계가 명확해집니다.
1. Pod
Pod에서 label은
해당 Pod를 식별하기 위한 메타데이터입니다.
아래 예시에서는 app: example-app 이
Pod를 대표하는 식별자 역할을 합니다.
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: example-app
spec:
containers:
- name: example-container
image: example-image
이 label 값은
Service나 Deployment가 하위 Pod를 찾을 때 사용됩니다.
2. DaemonSet
DaemonSet은
selector.matchLabels를 기준으로
자신이 관리할 Pod를 결정합니다.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: example-daemonset
spec:
selector:
matchLabels:
app: example-app
template:
metadata:
labels:
app: example-app
spec:
containers:
- name: example-container
image: example-image
핵심 포인트
selector.matchLabels.apptemplate.metadata.labels.app
두 값은 반드시 동일해야 합니다.
3. Deployment
Deployment 역시
selector.matchLabels와
template.metadata.labels를 통해 Pod를 관리합니다.
apiVersion: apps/v1
kind: Deployment
metadata:
name: example-deployment
spec:
selector:
matchLabels:
app: example-app
template:
metadata:
labels:
app: example-app
spec:
containers:
- name: example-container
image: example-image
Deployment는
이 template을 기반으로 ReplicaSet과 Pod를 생성합니다.
4. Service
Service는
selector를 이용해 트래픽을 전달할 Pod를 선택합니다.
apiVersion: v1
kind: Service
metadata:
name: example-service
spec:
selector:
app: example-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
Service는
labels.app = example-app 인 모든 Pod로
트래픽을 분산합니다.
개념 정리
selector / matchLabels
- Service 또는 Controller가
하위 Pod를 선택하기 위한 조건 selector.matchLabels값은
Pod의metadata.labels와 일치해야 함
app
- Pod를 식별하기 위해 관례적으로 많이 사용하는 label key
- 반드시
app일 필요는 없음 - 팀 또는 프로젝트 규칙에 따라 자유롭게 변경 가능
template
- Deployment, DaemonSet에서
Pod의 설계도 역할 - 이 template을 기준으로 실제 Pod가 생성됨
Note
- label key는 반드시
app일 필요는 없음 - 중요한 것은 다음 값들이 모두 일치하는 것
selector.matchLabels
template.metadata.labels
Pod.metadata.labels
이 규칙만 지키면
Service, Deployment, DaemonSet 간 연결이 정확하게 동작합니다.
마무리하며
Kubernetes의 핵심은
Label 기반 연결 구조를 이해하는 것입니다.
selector와 label의 관계를 정확히 이해하면
다음과 같은 문제가 사라집니다.
- Service에 트래픽이 안 가는 문제
- Deployment가 Pod를 인식하지 못하는 문제
- DaemonSet Pod가 생성되지 않는 문제
이 개념은 Kubernetes를 계속 다룰수록
반드시 체감하게 되는 핵심 개념입니다.