Author : MD TAREQ HASSAN | Updated : 2021/04/30

What is a Service in Kubernetes

A service would get a static IP and a persistent DNS name and would manage a set of pods. Applications (pods) would communicates with each other and with outside clients via their associated services.

Why Service is Needed

Pods are ephemeral

Lets say a set of 3 pods (pod0, pod1, pod2) representing a backend app where all 3 pods will have IP address and combindly they would constitute a ReplicaSet. Fontend apps uses that backend app (dependency). Frontend was communicating with pod0, but after some time pod0 dies and replaced by pod3. Pod3 would have a new (different) IP address that means frontend would not be able to funstion because pod0 is no longer available.

Enter K8s Service - a logical grouping of pods (i.e. 3 pods that constitute a backend app in our example) in way that dependent entities (i.e. a frontend app in our example) do not need to know about specific pod. Rather the pods will sit behind the service and the service will act as a load balancer and handle incoming requests.

So a service acts as:

IP Address and DNS Name

Services Types

Kubernetes ServiceTypes allow you to specify what kind of Service you want (default is ClusterIP). Type values and their behaviors are:

Defining a Service

Example: suppose you have a set of Pods where each listens on TCP port 9376 and contains a label app=MyApp:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376

This specification creates a new Service object named “my-service” (defaults to type: ClusterIP), which targets TCP port 9376 on any Pod with the app=MyApp label.

Another example

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: MyApp
  ports:
      # By default and for convenience, the `targetPort` is set to the same value as the `port` field.
    - port: 80
      targetPort: 80
      # Optional field
      # By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
      nodePort: 30007

How Does a Service Select Pods?

Points To Be Noted

Next