Right now I am trying to host simple site using kubernetes. My application has a simple php file running both on frontend and backend. My frontend php file wants to access the backend php file and I am creating an ajax request to do the same. But not able to figure out what base-url I need to specify(for kubernetes) in my ajax call to access the backend.
My current setup:
Created two container images, one for frontend code and another for backend.
Pushed these images to my gcr.
Started a Kubernetes cluster. Setup yaml files for frontend RC and service, and backend RC and service
apiVersion: v1
kind: Service
metadata:
`labels:
name: mytestapp-be
name: mytestapp-be-service
spec:
ports:
- port: 80
targetPort: 80
protocol: TCP
selector:
app: mytestapp-be
tier: backend
I have created a service with above file. And my frontend application code, has an ajax snippet which carries a url to access the backend file using service name and port name.
url: "http://mytestapp-be-service:80",
normally, on a completely provisioned kubernetes cluster you should have dns working out of the box. If you deployed front and back in the same namespace, your pods should be able to communicate simply by service name. The problem you might be facing here is that when you open a page on a browser and attempt a request from it, simply by pointing to you backend service, you try to make this request from the browser which is not inside of the kubernetes cluster, and can not reach other pods by means of in-kubernetes networking.
If that is the case, you need to expose both front and backend, so both of them are accessible by the browser (there are a couple of ways to actually do that, starting with nodePort services, via LB services to Ingress.
It will be easier to pinpoint your problem if you post your yamls here. But here some general information:
The ease of internal service discovery is one of the strengths of kubernetes. For communication from inside a container to another service in k8s you can use the built in DNS or environment variables. DNS works as following: The service is available by its name and it resolves to the cluster IP of the service. So if your service name is backendservice
you should be able to reach its cluster IP by that name from within the cluster (under the specified namespace, if you chose one, e.g. backendservice.my-namespace
). The service port(s) should forward to the defined target port(s) of the pods that are part of the service. For example:
apiVersion: v1
kind: Service
metadata:
name: backendservice
spec:
selector:
name: nginxphppod
ports:
- name: http
port: 80
targetPort: 80
The service will be available by pointing your frontend to http://backendservice:80
For more information please read this and this.
To trouble shoot run kubectl get svc
and double check that all your services have a clusterIP assigned. This should be the case if you did not specify clusterIP: None
in your service yaml.