In this lesson, we will explore how Kubernetes services enable communication between different components of your applications and provide stable endpoints for accessing them.
Kubernetes services are an abstraction that defines a logical set of Pods and a policy by which to access them. Services allow you to expose your application running on a set of Pods as a network service.
Kubernetes supports several types of services:
| Service Type | Description |
|---|---|
| ClusterIP | Exposes the service on a cluster-internal IP. This is the default service type. |
| NodePort | Exposes the service on each Node’s IP at a static port. |
| 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 can use a YAML configuration file. Below is an example of a simple ClusterIP service that exposes a Deployment called my-app:
apiVersion: v1
kind: Service
metadata:
name: my-app-service
spec:
type: ClusterIP
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
port is the port that the service listens on, and targetPort is the port on the Pod that the traffic is directed to.Once the service is created, you can access it using the service name within the cluster. For example, if you have a Pod that needs to communicate with my-app-service, it can do so by simply using the DNS name my-app-service.
Here’s how you can access the service from a Pod:
# Assuming you have a Pod running a shell (like busybox)
kubectl run -i --tty --rm debug --image=busybox -- sh
# Inside the Pod, you can use curl to access the service:
curl http://my-app-service
Common Mistake: Forgetting to specify the correct
targetPortcan lead to connectivity issues, as the service will not know which port on the Pod to forward traffic to.
In this lesson, you learned about Kubernetes services and networking. You now know how to create and access services, as well as the different types of services available in Kubernetes. Understanding services is vital for building scalable and resilient applications in Kubernetes.
apiVersion: v1
kind: Service
metadata:
name: my-app-nodeport
spec:
type: NodePort
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
nodePort: 30000
apiVersion: v1
kind: Service
metadata:
name: external-google
spec:
type: ExternalName
externalName: www.google.com