📦 Understanding the Kubernetes service.yaml File


In Kubernetes, Services are essential for exposing applications running in Pods to other parts of the cluster — or even externally. The service.yaml
file defines how your application is exposed via a Kubernetes Service object.
Let’s break it down with an example and explanation.
🧩 What is a Kubernetes Service?
A Service is a stable abstraction that exposes one or more Pods, defined by a selector. While Pods are ephemeral (they can die and restart), a Service ensures a consistent network endpoint for clients to use.
✍️ Basic service.yaml
Example
yamlCopyEditapiVersion: v1
kind: Service
metadata:
name: my-app-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80 # Port exposed by the service
targetPort: 8080 # Port the container is actually listening on
type: ClusterIP
🧠 Key Fields Explained
Field | Purpose |
apiVersion | Kubernetes API version (v1 for services). |
kind | Specifies this is a Service . |
metadata | Metadata like name , labels , etc. |
selector | Targets Pods with matching labels (app: my-app in this case). |
ports | Maps the service's port to the target container's port. |
type | Specifies how the service is exposed (more below). |
🛠️ Service Types
ClusterIP (default):
Exposes the service only within the cluster.NodePort:
Exposes the service on a static port on each node’s IP. Useful for dev/test.yamlCopyEdittype: NodePort ports: - port: 80 targetPort: 8080 nodePort: 30007
LoadBalancer:
Provisions a cloud provider's external load balancer.yamlCopyEdittype: LoadBalancer
ExternalName:
Maps the service to an external DNS name.yamlCopyEdittype: ExternalName externalName: example.com
🚀 Best Practices
Use labels to keep services flexible.
Avoid hardcoding
nodePort
unless necessary.For production, prefer
LoadBalancer
or use Ingress controllers for advanced routing.
✅ Quick Checklist
Are your Pod labels and Service selectors aligned?
Is your service type appropriate for the use case?
Have you defined all required ports and protocols?
🧪 Testing the Service
bashCopyEditkubectl apply -f service.yaml
kubectl get services
You can also use kubectl port-forward
or curl
from inside the cluster to test it.
🔚 Conclusion
The service.yaml
file is your gateway to stable, discoverable communication between components in a Kubernetes cluster. Whether you're exposing a frontend app or enabling backend microservices to talk, mastering services is critical to building resilient architectures.
Subscribe to my newsletter
Read articles from Pratik Raundale directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
