Skip to main content

Services

A Service in Kubernetes is a resource that creates a stable, fixed access point (like an IP or DNS name) for other applications or users to reach a group of pods. Even though the individual pod IPs might change as pods are created or destroyed, the Service ensures that traffic is consistently routed to the right pods, handling load balancing and internal/external communication.


NodePort

In short, NodePort is used to map a port on the pod to the node, making it accessible via the node IP over the specified port.

What if there's multiple pods included in a service? How will the service distribute traffic between these pods?

By default, services resort to a round robin load balancing method, meaning that traffic is sent to the next available pod. IE request 1 goes to pod1, request 2 goes to pod2, request 3 goes to pod1, request 4 goes to pod2 etc.

What if I need clients to be kept connected to the same node & pod? Persistent sessions

Services offer the option for 'sessionAffinity', also known as sticky sessions. IE, client has logged in and added items to basket on pod1, moving to pod2 would result in them losing this data. With SessionAffinity, we have various options that can be used to define how session affinity;

 

 

Allows external traffic to access the Service by connecting to <NodeIP>:<NodePort>

targetPort - This is the port on the pod which the application is listening on.

port - The port that the Service listens on within the cluster (for internal traffic)

nodePort - The external port on the node where traffic enters the cluster (for external traffic)

example;

I have the following pod definition that I'd like to include in my new service:

apiVersion: v1
kind: Pod 
metadata: 
  name: nginx-pod
  labels:
    app: webapp
spec: 
  containers: 
  - name: nginx 
    image: nginx:latest 
    ports: 
    - containerPort: 80

Rather than copy the pod definition into the service definition, we'll instead make use of the labels assigned to the pod, as below:

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  type: NodePort
  ports:
    - targetPort: 80  # Defines the port on which to direct traffic to the pod
      port: 80        # The port that the Service listens on within the cluster (for internal traffic)
      nodePort: 30008 # The external port on the node where traffic enters the cluster (for external traffic)
  selector: #Selector to SELECT which labels will be associated with the service
    app: webapp #label from pod definition - to associate that pod with this service
    

Create service

kubectl create -f service-definition.yml

View service

kubectl get services