Updated: Aug 14, 2020
Till now we have studied about a number of concepts like pods,deployment,namespace etc. but end goal is components of a kubernetes cluster should work together and provide service to end user. Service is a concept which makes a usable software accessible for use.
There are 3 types of services in Kubernetes: ClusterIP,LoadBalancer and NodePort. We are going to discuss ClusterIP service in this article.
A Service enables network access to a set of Pods in Kubernetes.
Services select Pods based on their labels. When a network request is made to the service, it selects all Pods in the cluster matching the service's selector, chooses one of them, and forwards the network request to it.
ClusterIP is the default type of service in kubernetes.
The service is only accessible from within the Kubernetes cluster – you can’t make requests to your Pods from outside the cluster!.
To make the service available from outside, we have NodePort and LoadBalancer service type that we will discuss in the next article.
ClusterIP is the type mainly useful when one or more dependent services need to communicate internally or for testing purpose. Below is an example.
First we will start the nginx pod and use it in the service
kubectl create -f nginx_pod.yaml
kind: Service apiVersion: v1 metadata: name: my-backend-service spec: type: ClusterIP selector: app: myapp ports: - port: 80 targetPort: 80 # Make sure that nginx-pod used for the service is running [root@node1 kubernetes]#
We can access the service by port forwarding
kubectl port-forward service/my-backend-service 80:80 ## To the localhost
# To access from outside
kubectl port-forward service/my-backend-service --address=0.0.0.0 80:80
Now we will be able to see the nginx web page with opening the server IP from which we are accessing the kubernetes cluster on port 80.