Search code examples
amazon-web-serviceskubernetescloudkops

How do pods communicates with the other pod in a cluster created using Kubernetes


I have created 1 master node and 1 worker node with 2 pods using kops in aws. In one pod i have my oracle database running and in other pod i have deployed my java web application. Now to run the java web application needs to talk to the database pod for To communicate between 2 pods in a cluster, i have configured the pod's IP address in my java application. I am able to access the application using the cloud providers public URL, everything is good in the dev environment. But in case of production environment, i cannot keep configuring the database Pod's IP address in my java application Pod.

How do people solve this issue ? Do you guys use Pod's Ip address to communicate with other pod's in kubernetes ? or is there any other way for communication between pods ?

Here is how my Pods look like in the cloud

   NAME                           READY     STATUS    RESTARTS   AGE       IP            NODE
csapp-8cd5d44556-7725f         1/1       Running   2          1d        100.96.1.54   ip-172-56-35-213.us-west-2.compute.internal
csdb-739d459467-92cmh          1/1       Running   0          1h        100.96.1.57   ip-172-27-86-213.us-west-2.compute.internal

Any help or directions on this issue would be helpful.


Solution

  • To make communication between two pods, you should use service resource with port type ClusterPort since they are in the same cluster.

    According to the output of kubectl get pods, you have two tiers:

    • App Tier: csapp-8cd5d44556-7725f

    • Data Tier : csdb-739d459467-92cmh

    Below is an example of service resource for data tier, then how it is used inside App tier.

    apiVersion: v1
    kind: Service
    metadata:
      name: example-data-tier
    spec:
      selector:
        app: csdb # ⚠️Make sure of this, it should select the POD csdb-...
      ports:
        - name: redis
          protocol: TCP
          port: 6379
          # type (default is ClusterPort which is for internal)
    

    And in the POD of App tier, you should feed the environment variable with values from the service above:

    apiVersion: v1
    kind: Pod
    spec:
      containers:
        - name: xx
          image: "xxx:v1"
          ports:
            - containerPort: 8080
              protocol: TCP
          env:
            - name: "REDIS_URL"
              value: "redis://$(EXAMPLE_DATA_TIER_SERVICE_HOST):$(EXAMPLE_DATA_TIER_SERVICE_PORT_REDIS)"
    

    If your DB is something other than Redis, you need to consider that when applying this solution.