You should create services for frontend and backend, and then you can communicate using:
- (Recommended) a DNS names of the services
<service-name>.<namespace-name>.svc.cluster.local which will be always the same
- (Not recommended) a IP address of the services (but they will be different with each re-creation of the service)
Example and further explanation below.
Let's create deployments with 3 replicas - one in default namespace, one in test namespace:
kubectl create deployment nginx --image=nginx --replicas=3
kubectl create deployment nginx --image=nginx --replicas=3 -n test
For each deployment we will create service type ClusterIP using kubectl expose(It's the same if I had created a service from a yaml file:):
kubectl expose deployment nginx --name=my-service --port=80
kubectl expose deployment nginx --name=my-service-test --port=80 -n test
Time to get IP addresses of the services:
user@shell:~$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 64d
my-service ClusterIP 10.107.224.54 <none> 80/TCP 12m
And in test namespace:
user@shell:~$ kubectl get svc -n test
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
my-service-test ClusterIP 10.110.51.62 <none> 80/TCP 8s
I will exec into pod in default namespace and curl IP address of the my-service-test in second namespace:
user@shell:~$ kubectl exec -it nginx-6799fc88d8-w5q8s -- sh
# curl 10.110.51.62
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
Okay, it's working... Let's try with hostname:
# curl my-service-test
curl: (6) Could not resolve host: my-service-test
Not working as expected. Let's check /etc/resolv.conf file:
# cat resolv.conf
nameserver 10.96.0.10
search test.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
It's looking for hostnames only in namespace where pod is located.
So pod in the test namespace will have something like:
# cat resolv.conf
nameserver 10.96.0.10
search test.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
Let's try to curl my-service-test.test.svc.cluster.local from pod in default namespace:
# curl my-service-test.test.svc.cluster.local
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
It's working.
If you have problems, make sure you have a proper CNI plugin installed for your cluster - also check this article - Cluster Networking for more details. If you are using some cloud provided solution (like AWS EKS or GCP GKE) you should have it by default.
Also check these: