Kubernetes Services
A kubernetes service is an object in kubernetes which helps in communication between the external system and the pods within the kubernetes node.
Before getting into further details about services lets see how a single pod in kubernetes cluster would look like
As you can see that the the consumer service App1 is on a different node Node 1 and the pod which is exposing the App2 api is in another Node 2. Also, within node 2, the pod is inside a kubernetes private network which has a different family of IP address when compared to outer node, Node 2. So, there is no way to directly communicate from Node 1 to Pod.
So, basically Node 1 can connect to Node 2 IP but it cannot connect to the pod. This is where services come in handy.
Now, lets look at the same diagram along with the Service.
The NodePort service basically would listen to a port 30000 on the node and would forward the request to the pod.
Types of Services:
NodePort: This type of service helps us in mapping the port on the node to the port on the pod. For this to happen, basically three ports are involved in a service.
- Target port: This is dynamic port on the pod which runs the actual micro service.
- Port on the service itself: The service is like the virtual server on the node. Inside the cluster it has its own ip address. This is called the cluster IP.
- Node Port: This is the port on the node itself on which this service listens to. The valid port range for node port is 30000 to 32767
ClusterIP: The service creates a virtual IP inside the cluster to enable the communication between different micro-services. Cluster IP is the default type.
LoadBalancer: This helps up provision a load balancer for our services in supported cloud providers.
If we have multiple pods having the same selector then the service will automatically do the load balancing and forward the request to any of the matching pods randomly.
If the pods are distributed across multiple nodes, when we create a service for such kind of setup, k8s automatically creates a service which spans across multiple nodes. This enables us to use any of the ips of the nodes and to be able to access the application.