【k8s】pod間通信をやってみた!


はじめに

現在、様々なサービスのマイクロサービス化が進んでいる。その際、重要になってくるの部分の一つとして、サービス間の通信が挙げられる。
また、マイクロサービスを導入していく場合、kubernetesを用いた開発がよく採用されている。

そこで、今回は、サービス間の通信の一手法として、kuberntesの最小リソースであるpod間の通信方法についてみてみる。

サービス間の通信方法については、pod間通信の他にも,
gRPCなどの通信方法がある。

今回作るもの

今回はすごく簡易的なものとして、k8sのdeploymentで作成されたhttpd サーバーのpodとnginxのpodを通信してみる

httpd

httpd_deployment.yml
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc
spec:
  selector:
    app: httpd
  ports:
  - port: 8090
    targetPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpd
spec:
  replicas: 1
  selector:
    matchLabels:
      app: httpd
  template:
    metadata:
      labels:
        app: httpd
    spec:
      containers:
      - name: httpd
        image: httpd:2-alpine
        ports:
        - containerPort: 80

nginx

nginx_deployment.yml

apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
spec:
  selector:
    app: nginx
  ports:
  - port: 8080
    targetPort: 80

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.18-alpine
        ports:
        - containerPort: 80

とりあえず、通信してみる

  • 上でつくったdeploymentたちを起動
$ kubectl apply -f httd_deployment.yml -f nginx_deployment.yml 
  • ちゃんと立ち上がったか確認
$ kubectl get po 

NAME                    READY   STATUS    RESTARTS   AGE
httpd-7f8bd9884-jptwt   1/1     Running   0          4m26s
nginx-d69ddfd76-r4lhq   1/1     Running   0          4m26s

statusが両方ともRunningになっていればok

httpd→nginx

  • httpdのpodに入る
$ kubectl exec -it httpd-7f8bd9884-jptwt sh
/ # 
  • httpdのpod内からnginxのpodにアクセスしてみる
/ # curl http://nginx-svc:8080

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

nginx→httpd

  • nginxのpodにはいる
$ kubectl exec -it nginx-d69ddfd76-r4lhq sh
  • nginxのpod内からhttpdのpodにアクセスしてみる
/ # curl http://httpd-svc:8090
<html><body><h1>It works!</h1></body></html>

アクセスできたのが確認できた。