In Kubernetes, Services are an abstraction that defines a logical set of Pods and a policy by which to access them. This allows for seamless communication between different parts of your application, whether they are within the cluster or external clients.
A Service in Kubernetes is a stable endpoint that allows you to expose a set of Pods as a network service. It can be accessed through a consistent IP address and DNS name, regardless of the underlying Pods' lifecycle.
Kubernetes provides several types of Services:
| Service Type | Description |
|---|---|
| ClusterIP | Exposes the Service on a cluster-internal IP. Only reachable from within the cluster. |
| NodePort | Exposes the Service on each Node’s IP at a static port. Accessible from outside the cluster. |
| LoadBalancer | Exposes the Service externally using a cloud provider’s load balancer. |
| ExternalName | Maps the Service to the contents of the externalName field (e.g., DNS). |
To create a Service, you need to define it in a YAML file. Below is an example of a simple ClusterIP Service that exposes a set of Pods running a web application.
apiVersion: v1
kind: Service
metadata:
name: my-web-service
spec:
selector:
app: my-web-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIP
app: my-web-app).port is the port exposed by the Service, while targetPort is the port on the Pod.To create the Service, save the YAML to a file named service.yaml and run:
kubectl apply -f service.yaml
Once the Service is created, you can access it from within the cluster using the service name:
curl http://my-web-service
For NodePort Services, you can access it externally using any Node's IP address and the specified port:
curl http://<Node-IP>:<Node-Port>
Always use labels and selectors to ensure your Services can dynamically discover Pods. Avoid hardcoding IP addresses; use Service names for better maintainability.
targetPort matches the port your application is listening on.By understanding Services and networking in Kubernetes, you can build more resilient and scalable applications that communicate effectively across your cluster.
Task: Modify the Service YAML to set type: NodePort, apply it, and note the port assigned.
Exercise 2: Experiment with different Service types.
Task: Create a LoadBalancer Service and check if it gets an external IP (if using a cloud provider).
Exercise 3: Debug a Service issue.