1. Multi Port ClusterIP

하나의 ClusterIP 서비스에서 여러 Port 의 엔드포인트를 가지고, 각 Port마다 파드의 다른 Port 로 연결도 가능하다.

아래의 매니페스트처럼 spec.ports 배열필드에 여러 포트를 지정하면 된다. 여기서는 서비스의 8080 -> 파드의 80, 서비스의 8443 -> 파드의 443 포트로 연결된다.

apiVersion: v1
kind: Service
metadata:
  name: clusterip-multi
spec:
  type: ClusterIP
  ports:
    - name: "http-port"
      protocol: "TCP"
      port: 8080
      targetPort: 80
    - name: "https-port"
      protocol: "TCP"
      port: 8443
      targetPort: 443
  selector:
    app: sample-app

 

2. 포트 이름을 사용한 참조

Service 의 spec.ports[].targetPort 에 포트 번호를 지정하지 않고, 미리 정의해놓은 포트 이름으로 포트번호를 사용할 수도 있다. 먼저 서비스가 띄워질 파드를 정의할 때 spec.containers[].ports[] 에 포트 이름과 포트 번호를 지정하고, Service 에서는 targetPort 에 해당 포트 이름으로 설정해주면 된다. 이렇게 하면 Service 매니페스트에서는 동일한 변수명으로 포트를 지정하더라도, 실제 서비스가 띄워지는 Pod 마다 다른 포트로 연결해줄 수 있다.

 

아래의 매니페스트로 "http" 이름의 port 가 각각 80, 81 포트로 정의된 파드를 한개씩 띄우자

---
apiVersion: v1
kind: Pod
metadata:
  name: named-port-pod-80
  labels:
    app: sample-app
spec:
  containers:
    - name: nginx-container
      image: amsy810/echo-nginx:v2.0
      ports:
        - name: http
          containerPort: 80
---
apiVersion: v1
kind: Pod
metadata:
  name: named-port-pod-81
  labels:
    app: sample-app
spec:
  containers:
    - name: nginx-container
      image: amsy810/echo-nginx:v2.0
      env:
        - name: NGINX_PORT
          value: "81"
      ports:
        - name: http
          containerPort: 81

 

아래의 매니페스트로 "http" 이름을 통해 targetPort 를 지정한 Service 를 띄우자

apiVersion: v1
kind: Service
metadata:
  name: named-port-service
spec:
  type: ClusterIP
  ports:
    - name: "http-port"
      protocol: "TCP"
      port: 8080
      targetPort: http
  selector:
    app: sample-app

 

아래의 커맨드로 서비스의 목적지 파드의 엔드포인트의 port 가 각각 80, 81 로 설정되었는지 확인할 수 있다.

# 파드의 IP 확인
$ kubectl get pods -l app=sample-app -o custom-columns="NAME:{metadata.name},IP:{status.podIP}"
NAME                IP
named-port-pod-80   10.244.2.116
named-port-pod-81   10.244.1.132

# 서비스가 바라보는 파드의 port 확인
$ kubectl describe service named-port-service
Name:                     named-port-service
Namespace:                default
Labels:                   <none>
Annotations:              <none>
Selector:                 app=sample-app
Type:                     ClusterIP
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.96.134.44
IPs:                      10.96.134.44
Port:                     http-port  8080/TCP
TargetPort:               http/TCP
Endpoints:                10.244.1.132:81,10.244.2.116:80
Session Affinity:         None
Internal Traffic Policy:  Cluster
Events:                   <none>

 

블로그 이미지

망원동똑똑이

프로그래밍 지식을 자유롭게 모아두는 곳입니다.

,