My frontend is setup as:
this.http.post<any>(`${environment.apiUrl}/auth/login`, {email, password})
Where apiUrl: 'http://backend/api'
I built the frontend in a container and exposed it to a loadbalancer service and I am trying to hook it up through a ClusterIP service to a backend on port 3000.
Frontend YAML:
apiVersion: v1
kind: Service
metadata:
name: frontend
spec:
selector:
tier: frontend
ports:
- port: 80
targetPort: 80
type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend
spec:
selector:
matchLabels:
tier: frontend
replicas: 1
template:
metadata:
labels:
tier: frontend
spec:
containers:
- name: frontend
image: <Image>
imagePullPolicy: Always
ports:
- containerPort: 80
Backend YAML:
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
spec:
selector:
matchLabels:
app: app
tier: backend
replicas: 1
template:
metadata:
labels:
app: app
tier: backend
spec:
containers:
- name: frontend-container
image: <Image>
ports:
- containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: backend
spec:
selector:
app: app
tier: backend
ports:
- protocol: TCP
port: 80
targetPort: 3000
As explained in the doc here.
But it doesn't work when I try to access it from the browser, I receive Unknown Error!!
Here are screenshots from inside the frontend making sure it is able to reach the backend internally.
I don't understand where I went wrong here. I am thinking the apiUrl var set to http://backend is not being translated correctly because if I changed that to a loadbalancer IP and rebuilt the image, exposed the backend to a LB service instead of ClusterIP. It does work.
But obviously I don't want to expose my backend to a LB service.
Any idea?
Look at the following:
outside world | k8s cluster
|
Browser --> | Nginx-pod --> backend-pod
|
|
The url http://backend/api
is only resolvable within the cluster, but your browser is in the outside world, so it does not know what this url is.
You ideally would use an ingress
to manage routes to cluster pods.
As @Elgarni said, clients' browser could not access your cluster, so http://backend/api
is not resolvable outside to cluster.
If you defined ingress, use kubectl get ingress
command and learn your external IP. then replace your ${environment.apiUrl}
to http://$EXTERNAL_IP/api/
or
define DNS record for your external IP and reach via your defined domain.