1 분 소요

서론

k8s의 Service에 대해서 알아보도록 하겠습니다. 도커도 잘 모르는 시절 k8s를 공부했을 때 Service가 너무 어려웠는데 지금 다시 공부해보니 조금 알 것 같습니다. 심화는 다음 포스트에서 알아보도록 하겠습니다.

k8s Service

파드 집합에서 실행 중인 애플리케이션을 네트워크 서비스로 노출하는 추상화 방법

k8s의 pod는 클러스터의 목표 상태와 일치하기 위해서 생성되고 삭제됩니다. 생성되고 삭제될 때 pod의 ip는 달라지게 되는데, 새로 생성된 pod의 ip를 추적하기 위해서 Service를 사용하게 됩니다.

ClusterIP

Service의 default 타입은 ClusterIP입니다. 클러스터 내부 통신만 가능하고 외부에서 들어오는 트래픽은 받을 수 없습니다. 하나의 Service가 여러 pod를 관리한다면, 각각의 pod에 트래픽을 분산하는 역할을 합니다.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hello
  template:
    metadata:
      name: hello
      labels:
        app: hello
    spec:
      containers:
      - name: nginx
        image: nginxdemos/hello:plain-text
        ports:
        - name: http
          containerPort: 80
          protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: hello
spec:
  type: ClusterIP
  ports:
  - name: http
    port: 8080
    targetPort: 80
    protocol: TCP
  selector:
    app: hello

life

NodePort

ClusterIP와 달리 외부 트래픽을 받을 수 있는 타입입니다. 클러스터를 구성하는 각각의 Node에 동일한 포트를 열게 되는데, 열린 포트로 트래픽을 받고 ClusterIP에게 전달 후, ClusterIP가 각각의 pod에 트래픽을 분산하는 방식으로 이루어집니다.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hello
  template:
    metadata:
      name: hello
      labels:
        app: hello
    spec:
      containers:
      - name: nginx
        image: nginxdemos/hello:plain-text
        ports:
        - name: http
          containerPort: 80
          protocol: TCP
---

apiVersion: v1
kind: Service
metadata:
  name: hello
  labels:
    app: hello
spec:
  type: NodePort
  ports:
  - name: http
    protocol: TCP
    port: 8080
    targetPort: 80
    nodePort: 31000
  selector:
    app: hello
kubectl get node -o wide

life

위의 명령어를 통해 외부에 노출된 minikube의 ip를 확인할 수 있고, 확인한 ip로 request를 보내면 어떤 pod에 트래픽이 흘러갔는지 확인할 수 있습니다. M칩인 경우, minikube 터널링을 통해야만, 외부에서 접근가능하게 됩니다. 아래의 사진에서 터널링을 뚫고 request을 보낼 때 ClusterIP에 의해 트래픽이 분산되고 있는 것을 확인하실 수 있습니다.

life

결론

k8s의 pod는 죽었을 때 가용성을 유지하기 위해 다시 생성됩니다. 이때 새로운 IP가 발급되는데, 새로 발급받은 IP를 트래킹하기 위해서 Service를 사용하게 됩니다. Service의 타입은 여러 개가 있는데 default 타입은 ClusterIP 입니다. ClusterIP는 외부 트래픽을 받지 못하지만, 트래픽을 분산시키는 역할을 하게 됩니다. NodePort는 노드의 포트를 열어 외부 트래픽을 받을 수 있게 합니다. 받은 외부 트래픽을 ClusterIP에게 전달하고 ClusterIP는 다시 Pod들에게 트래픽을 분산하도록 합니다.

카테고리:

업데이트: