Table of contents
The article is about how one container communicates with another container in the same pod and how the pod interacts with another which lies in the same node. let's see one by one.
A] Container-to-Container Communication
Containers in the same pod communicate with each other using localhost, because Kubernetes provides ip to the pod not to the container. this type of networking happens only when one container is dependent on the other.
Let's see how it works.
Create a pod with 2 containers, one container using httpd image and another using ubuntu. when containers will start we will try to access httpd container from Ubuntu using localhost.
Pod Yaml file.
kind: Pod
apiVersion: v1
metadata:
name: ctc
spec:
containers:
- name: container1
image: httpd
ports:
- containerPort: 80
- name: container2
image: ubuntu:latest
command: ["/bin/sleep", "3650d"]
Start the pod using kubectl apply command and when containers start running enter into the ubuntu container which is container2.
$ kubectl exec ctc -it -c container2 -- /bin/bash
First, run apt update and install the curl command
$ apt update
$ apt install curl
Now check if containers can communicate or not.
$ curl localhost:80
B] Pod-to-Pod Communication
Kubernetes provides ip to each pod. pods can communicate with another pod in the same node using that IP and exposed port.
Let's create two pods. pod1 -> httpd, pod2 -> ubuntu
kind: Pod
apiVersion: v1
metadata:
name: pod1
spec:
containers:
- name: container1
image: httpd
ports:
- containerPort: 80
kind: Pod
apiVersion: v1
metadata:
name: pod2
spec:
containers:
- name: container2
image: ubuntu:latest
command: ["/bin/sleep", "3650d"]
To get the IPs of the pod.
$ kubectl get pods -o wide
After starting the pods, let's install curl inside pod2
$ kubectl exec pod2 -it -- /bin/bash
# Now we are in pod2 lets install curl
$ apt update
$ apt install curl
Finally, curl the httpd pod which pod1 from pod2
$ curl <pod1-IP>:80
Thank You!!!