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

やったこと

Service の NodePort を使ってみます。

確認環境

$ 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"}

調査

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

first-nodeport.yaml

apiVersion: v1
kind: Service
metadata:
  name: my-nodeport
spec:
  type: NodePort
  ports:
  - name: "hoge"
    protocol: "TCP"
    port: 8080
    targetPort: 80
    nodePort: 30000
  selector:
    app: sample5
$ k apply -f sample5.yaml -f first-nodeport.yaml
deployment.apps/my-deployment created
service/my-nodeport created

$ k get service my-nodeport
NAME          TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
my-nodeport   NodePort   10.105.91.123   <none>        8080:30000/TCP   38s

$ k get pods -o wide
NAME                             READY   STATUS    RESTARTS   AGE    IP           NODE             NOMINATED NODE   READINESS GATES
my-deployment-5f9fb9cfc8-5626r   1/1     Running   0          5m4s   10.1.0.231   docker-desktop   <none>           <none>
my-deployment-5f9fb9cfc8-67bmc   1/1     Running   0          5m5s   10.1.0.230   docker-desktop   <none>           <none>
my-deployment-5f9fb9cfc8-72m6v   1/1     Running   0          5m4s   10.1.0.232   docker-desktop   <none>           <none>

ホストOSから実行します。

$ curl localhost:30000

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

$ k logs -f my-deployment-5f9fb9cfc8-5626r
192.168.65.3 - - [28/Dec/2020:16:35:55 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
192.168.65.3 - - [28/Dec/2020:16:35:56 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
192.168.65.3 - - [28/Dec/2020:16:35:57 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
192.168.65.3 - - [28/Dec/2020:16:36:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
^C
$ k logs -f my-deployment-5f9fb9cfc8-67bmc
192.168.65.3 - - [28/Dec/2020:16:35:59 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
192.168.65.3 - - [28/Dec/2020:16:36:00 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
^C
$ k logs -f my-deployment-5f9fb9cfc8-72m6v
192.168.65.3 - - [28/Dec/2020:16:35:49 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"
192.168.65.3 - - [28/Dec/2020:16:35:58 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.55.1" "-"

参考