- Kubernetes services enable communication between various components within and outside of the application. They enable loose coupling between micro-services in our application.
- Services are static IPs that can be attached to a pod or a group of pods using label selectors. They are not attached to deployments.
- Services prevent us from using the pod IP addresses for communication which could change when the pod is restarted.
- Lifecycle of pod and service are not connected. So even if a pod dies, we can restart it and attach the original service to have the same IP.
- Every service spans the entire cluster (all the nodes in the cluster)
- Every service has a unique IP across the K8s cluster
- Kubernetes creates a default ClusterIP Service which forwards requests from within the cluster to the Kubernetes master (API Server). So, there is at least 1 service in every Kubernetes cluster.
- K8s services are of three types:
- NodePort
- ClusterIP
- LoadBalancer
NodePort Service
Consider an application running in a pod on a node which is on the same network as our laptop, we could SSH into the node and then reach the application by its IP on the Kubernetes network (10.244.0.0/16
). But doing an SSH into the node to access the application is not the right way.
- NodePort service maps a port on the node (Node Port) to a port on the pod (Target Port) running the application. This will allow us to reach the application on the node’s IP address.
- Allowed range for NodePort: 30,000 - 32,767
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
type: NodePort
ports:
- targetPort: 80
port: 80
nodePort: 30008
selector:
app: myapp
type: front-end
-
selector
is used to select target pods for the service
-
port
- port on which the service would be accessible
-
targetPort
- port on the pod to which the requests would be forwarded
-
nodePort
- port on the node
-
If there are multiple target pods on the same node, the service will automatically load balance to these pods.
- If the target pods span multiple nodes in the cluster, as the NodePort service will span the entire cluster, it will map the target port on the pods to the same node port on all the nodes in the cluster, even the nodes that don’t have the application pod running in them. This will make the application available on the IP addresses of all of the nodes in the cluster.
ClusterIP Service