ServiceのClusterIPを使ってみる (kubernetes)
kubernetes
Published: 2021-01-03

やったこと

Service の ClusterIP を使ってみます。

確認環境

$ k version
Client Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.2", GitCommit:"c97fe5036ef3df2967d086711e6c0c405941e14b", GitTreeState:"clean", BuildDate:"2019-10-15T19:18:23Z", GoVersion:"go1.12.10", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.3", GitCommit:"1e11e4a2108024935ecfcb2912226cedeafd99df", GitTreeState:"clean", BuildDate:"2020-10-14T12:41:49Z", GoVersion:"go1.15.2", Compiler:"gc", Platform:"linux/amd64"}

調査

first-cluster-ip.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-cluster-ip
spec:
  type: ClusterIP
  ports:
  - name: "hoge"
    protocol: "TCP"
    port: 8080
    targetPort: 80
  selector:
    app: sample5

sample5.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: sample5
  template:
    metadata:
      labels:
        app: sample5
    spec:
      containers:
        - name: nginx-container
          image: nginx:1.17
$ k apply -f sample5.yaml -f first-cluster-ip.yaml
deployment.apps/my-deployment created
service/my-cluster-ip created

$ k get pods -o wide
NAME                             READY   STATUS    RESTARTS   AGE   IP           NODE             NOMINATED NODE   READINESS GATES
my-deployment-5f9fb9cfc8-69w6v   1/1     Running   0          24s   10.1.0.221   docker-desktop   <none>           <none>
my-deployment-5f9fb9cfc8-c25mg   1/1     Running   0          24s   10.1.0.223   docker-desktop   <none>           <none>
my-deployment-5f9fb9cfc8-m5qnk   1/1     Running   0          24s   10.1.0.222   docker-desktop   <none>           <none>

$ k get service my-cluster-ip
NAME            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
my-cluster-ip   ClusterIP   10.109.253.129   <none>        8080/TCP   6m32s

※ 同じクラスタ内のコンテナからアクセス

$ curl -v http://10.109.253.129:8080

何回かアクセスを繰り返すと、アクセスが振り分けられていることが分かります。

$ k logs -f my-deployment-5f9fb9cfc8-69w6v
10.1.0.1 - - [28/Dec/2020:16:10:22 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"
10.1.0.1 - - [28/Dec/2020:16:17:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"
10.1.0.1 - - [28/Dec/2020:16:17:04 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"

$ k logs -f my-deployment-5f9fb9cfc8-c25mg
10.1.0.1 - - [28/Dec/2020:16:04:48 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"
10.1.0.1 - - [28/Dec/2020:16:10:27 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"
10.1.0.1 - - [28/Dec/2020:16:11:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"
10.1.0.1 - - [28/Dec/2020:16:17:06 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"

$ k logs -f my-deployment-5f9fb9cfc8-m5qnk
10.1.0.1 - - [28/Dec/2020:16:04:38 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"
10.1.0.1 - - [28/Dec/2020:16:17:03 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.64.0" "-"

参考