alltools.one
DevOps
2025-06-03
9 min
alltools.one Team
YAMLKubernetesK8sDevOpsContainers

Kubernetes를 위한 YAML: 필수 매니페스트 패턴

Kubernetes는 전적으로 YAML 매니페스트를 통해 구성됩니다. 모든 파드, 디플로이먼트, 서비스, 인그레스가 YAML로 정의됩니다. 이 패턴을 마스터하는 것은 컨테이너 오케스트레이션을 다루는 모든 사람에게 필수적입니다. 이 가이드에서는 프로덕션 준비 예제와 함께 가장 중요한 리소스 유형을 다룹니다.

네 가지 필수 필드

모든 Kubernetes 매니페스트에 필요한 것:

apiVersion: apps/v1      # 이 리소스 유형의 API 버전
kind: Deployment          # 리소스 유형
metadata:                 # 리소스 식별
  name: my-app
  namespace: production
  labels:
    app: my-app
spec:                     # 원하는 상태 사양
  # ... 리소스별 구성

Deployment

가장 일반적인 리소스 — 동일한 파드 세트를 관리합니다:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-server
  labels:
    app: api-server
    environment: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api-server
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: api-server
    spec:
      containers:
        - name: api
          image: myapp/api:v1.2.3
          ports:
            - containerPort: 8080
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: db-credentials
                  key: url
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          livenessProbe:
            httpGet:
              path: /healthz
              port: 8080
            initialDelaySeconds: 15
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 5

핵심 패턴

항상 리소스 요청과 제한을 설정하세요: 없으면 단일 파드가 모든 노드 리소스를 소비할 수 있습니다.

항상 헬스 프로브를 구성하세요:

  • livenessProbe: 파드가 응답하지 않으면 재시작
  • readinessProbe: 파드가 준비될 때까지 트래픽 전송 중지

특정 이미지 태그 사용: 프로덕션에서 latest를 절대 사용하지 마세요 — 롤백이 불가능해집니다.

Service

파드를 네트워크 트래픽에 노출:

apiVersion: v1
kind: Service
metadata:
  name: api-server
spec:
  type: ClusterIP
  selector:
    app: api-server
  ports:
    - port: 80
      targetPort: 8080
      protocol: TCP

Service 유형:

  • ClusterIP (기본): 내부 클러스터 접근만
  • NodePort: 각 노드 IP의 정적 포트에 노출
  • LoadBalancer: 클라우드 로드 밸런서 프로비저닝
  • ExternalName: DNS 이름에 매핑

ConfigMap과 Secret

ConfigMap (비민감 데이터)

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: "info"
  MAX_CONNECTIONS: "100"
  config.yaml: |
    server:
      port: 8080
      timeout: 30s

Secret (민감 데이터)

apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
stringData:
  url: "postgres://user:password@db:5432/myapp"
  api-key: "sk-1234567890"

파드에서 사용

# 환경 변수로
env:
  - name: LOG_LEVEL
    valueFrom:
      configMapKeyRef:
        name: app-config
        key: LOG_LEVEL

# 마운트된 파일로
volumes:
  - name: config
    configMap:
      name: app-config

Ingress

외부 HTTP 트래픽을 서비스로 라우팅:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - api.example.com
      secretName: tls-secret
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: api-server
                port:
                  number: 80

Horizontal Pod Autoscaler

CPU 또는 커스텀 메트릭 기반 파드 스케일링:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api-server-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api-server
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

일반적인 실수

1. 들여쓰기 오류

Kubernetes에서 YAML 들여쓰기는 중요합니다. 잘못된 공백 하나가 구조를 완전히 바꿉니다. YAML 검증기로 매니페스트를 검증하세요.

2. 라벨 불일치

Service 셀렉터가 Pod 라벨과 정확히 일치해야 합니다. 불일치는 Service가 트래픽을 라우팅할 파드를 찾을 수 없다는 것을 의미합니다.

3. 리소스 제한 누락

리소스 제한이 없는 파드는 다른 워크로드를 굶길 수 있습니다. 항상 요청 (보장된 최소)과 제한 (허용된 최대) 모두를 포함하세요.

4. 가변 이미지 태그

latest나 다른 가변 태그를 사용하면 롤백이 불가능하고 배포가 예측 불가능해집니다. 특정 버전이나 불변 다이제스트로 고정하세요.

멀티 문서 매니페스트

---를 문서 구분자로 사용하여 관련 리소스를 하나의 파일에 결합:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-server
spec:
  # ... deployment spec
---
apiVersion: v1
kind: Service
metadata:
  name: api-server
spec:
  # ... service spec

YAML 구문 패턴에 대한 더 많은 내용은 YAML 구문 튜토리얼을 참조하세요.

FAQ

Kubernetes YAML을 직접 작성해야 하나요, 생성기를 사용해야 하나요?

구조를 이해하기 위해 YAML을 직접 작성하는 것부터 시작하세요. 프로덕션에서는 Helm (템플릿 매니페스트), Kustomize (오버레이 기반 커스터마이징), CDK8s (코드 기반 생성) 같은 도구를 사용하세요. 이 도구들은 반복을 줄이고 매니페스트를 복제하지 않고 환경별 설정을 가능하게 합니다.

Kubernetes YAML 오류를 어떻게 디버깅하나요?

kubectl apply --dry-run=client -f manifest.yaml로 적용하지 않고 검증하세요. 구문 오류에는 kubectl explain deployment.spec.template.spec.containers가 예상 구조를 보여줍니다. kubevalkubeconform 도구는 배포 전에 Kubernetes API 스키마에 대해 검증합니다.

관련 리소스

Published on 2025-06-03
YAML for Kubernetes: Essential Manifest Patterns | alltools.one