Kubernetes - Service

choko's avatar
Jun 29, 2024
Kubernetes - Service
 
notion image
  • Pod은 자체 IP를 가지고 다른 Pod와 통신할 수 있지만, 쉽게 사라지고 생성되는 특징 때문에 직접 통신하는 방법은 권장되지 않음
    • 별도의 고정된 IP를 가진 서비스를 만들고, 그 서비스를 통해 Pod에 접근하는 방식을 사용함.
    • 노출 범위에 따라
        1. ClusterIP
        1. NodePort
        1. LoadBalancer
        타입으로 나뉜다.
 
 
 

Service 설정

notion image
 
이제 redis에 접근할 counter 앱인 Deployment를 생성한다.
// counter-app.yml apiVersion: apps/v1 kind: Deployment metadata: name: counter spec: selector: matchLabels: app: counter tier: app template: metadata: labels: app: counter tier: app spec: containers: - name: counter image: ghcr.io/subicura/counter:latest env: - name: REDIS_HOST value: "redis" - name: REDIS_PORT value: "6379"
 
apply로 적용시킨 후, exec를 이용해 counter-app을 실행시킨다.
kubectl apply -f counter-app.yml kubectl get po kubectl exec -it counter-<xxxxx> -- sh
 

Service 생성 흐름

notion image
Service는 각 Pod를 바라보는 로드밸런서 역할을 하면서, 내부 도메인서버에 새 도메인을 생성한다.
  1. Endpoint Controller는 Service와 Pod을 감시하면서 조건에 맞는 Pod의 IP를 수집
  1. Endpoint Controller가 수집한 IP를 가지고 Endpoint 생성
  1. Kube-Proxy는 Endpoint 변화를 감시하고 노드의 iptables을 설정
  1. CoreDNS는 Service를 감시하고 서비스 이름과 IP를 CoreDNS에 추가
      • CoreDns
        • 쿠버네티스 클러스터 내에서 DNS 서비스를 제공하는 서버이다.
        • 클러스터 내부에서 파드 간 통신 및 서비스 검색을 위해 사용된다.
          • 자주 재생성되는 Pod는 새 IP를 할당받고, DNS를 통해 효율적으로 IP를 관리한다.
        • 쿠버네티스의 모든 노드에서 pod로서 실행된다.
  • Endpoint : 서비스의 접속 정보를 가지고 있음.
 

1. Service(ClusterIP)

  • 클러스터 내부의 파드 및 다른 서비스들이 해당 서비스에 접근할 때 사용된다.
  • ClusterIP는 클러스터 내부에 새로운 IP를 할당하고 여러개의 Pod를 바라보는 로드밸런서 기능을 제공한다.
  • 또 서비스 이름을 내부 도메인 서버에 등록하여 Pod간에 서비스 이름으로 통신할 수 있다.
// Service 예시 // counter-redis-svc.yml apiVersion: apps/v1 kind: Deployment metadata: name: redis spec: selector: matchLabels: app: counter tier: db template: metadata: labels: app: counter tier: db spec: containers: - name: redis image: redis ports: - containerPort: 6379 protocol: TCP // 하나의 YAML파일에 여러 개의 리소스를 정의할 "---" 구분자로 사용합니다. --- apiVersion: v1 kind: Service metadata: name: redis spec: ports: - port: 6379 protocol: TCP selector: app: counter tier: db
 
 
 

2. Service(NodePort)

  • 클러스터 내의 각 노드에 고정된 포트를 할당하여 서비스를 노출하는 방법
    • ClusterIP는 클러스터 내부에서만 접근할 수 있다. 클러스터 외부에서 접근하려면 NodePort를 만들어야 한다.
apiVersion: v1 kind: Service metadata: name: counter-app spec: type: NodePort ports: - port: 3000 protocol: TCP nodePort: 31000 // counter app을 해당 노드의 31000으로 오픈한다. selector: app: counter tier: app
spec.ports.nodePort : 노드에 오픈할 Port (미지정시 30000-32768 중에 자동 할당)
kubectl get pod -n mdl
 
 

3. Service(LoadBalancer)

  • 클러스터 외부에서 서비스에 접근할 수 있도록 외부 로드 밸런서를 사용하는 방법
  • 클라우드 제공업체에 따라 로드 밸런서가 서비스의 백엔드 파드로 트래픽을 전달
    • 이 과정에서 로드 밸런서는 트래픽을 분산하고, 장애 조치 및 확장을 관리
apiVersion: v1 kind: Service metadata: name: counter-lb spec: type: LoadBalancer ports: - port: 30000 targetPort: 3000 protocol: TCP selector: app: counter tier: app
  • 사실 Load Balancer는 클라우드 환경이 아니면 사용이 제한적임
 
 
 
 
 
Share article

Tom의 TIL 정리방