What is Service in Kubernetes: Definition and Usage
Service in Kubernetes is an abstraction that defines a logical set of Pods and a policy to access them. It enables stable network access to dynamic groups of Pods, even if their IP addresses change.How It Works
Imagine you have a group of workers (Pods) in a factory, but their seats keep changing every day. A Service acts like a receptionist who always knows where to find the right workers and directs requests to them. This receptionist has a fixed phone number (IP address) that never changes, so anyone calling can reach the workers without knowing their current seats.
In Kubernetes, Pods can be created and destroyed dynamically, so their IP addresses are not stable. The Service keeps track of which Pods are currently active and forwards network traffic to them. It uses labels to select the right Pods and provides a single IP and DNS name for clients to connect.
Example
This example shows a simple Kubernetes Service that exposes Pods with the label app: myapp on port 80.
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIPWhen to Use
Use a Service when you want to expose a set of Pods reliably inside or outside your Kubernetes cluster. For example:
- To allow other Pods to communicate with a group of backend servers without worrying about their IPs.
- To expose a web application to users inside the cluster using a
ClusterIPService. - To expose an application externally using
NodePortorLoadBalancerService types.
Services are essential for stable networking in Kubernetes, especially when Pods are frequently created or replaced.
Key Points
- A Service provides a stable IP and DNS name for a set of Pods.
- It uses label selectors to find the Pods it routes traffic to.
- Supports different types like
ClusterIP,NodePort, andLoadBalancer. - Helps decouple network clients from Pod lifecycle and IP changes.