Services โ Networking in Kubernetes
A Service is an abstraction that defines a logical set of pods and a policy for accessing them. Since pods are ephemeral and their IPs change constantly, Services provide a stable endpoint.
Without Services, you would have no reliable way to connect to your pods.
Why Services Exist
Problem: Pod IPs are temporary
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Pod A: 10.1.1.5 (running) โ
โ Pod A: 10.1.2.8 (restarted!) โ
โ Pod A: 10.1.3.2 (rescheduled!) โ
โ โ
โ How do other apps find Pod A? โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Solution: Services give a stable address
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Service: my-app (10.0.0.100) โ
โ โ โ
โ โโโโถ Pod A (10.1.1.5) โ
โ โโโโถ Pod A (10.1.2.8) โ
โ โโโโถ Pod A (10.1.3.2) โ
โ โ
โ Traffic always goes to 10.0.0.100 โ
โ Service load-balances across pods โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Service Types
ClusterIP (default) โ Exposes the Service only within the cluster. Internal traffic only.
NodePort โ Exposes the Service on each node's IP at a static port. Accessible from outside the cluster.
LoadBalancer โ Provisions an external load balancer (cloud providers). Exposes the Service externally.
ExternalName โ Maps a Service to an external DNS name. No proxying involved.
Creating a Service
# Quick way: expose a deployment
kubectl expose deployment nginx --port=80 --type=ClusterIP
# Full YAML definition
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
type: ClusterIP
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
selector โ Which pods to route traffic to. Must match pod labels.
port โ The port the Service listens on.
targetPort โ The port on the pod that receives traffic.
Service Discovery
# DNS-based discovery (automatic)
# Pods can reach a Service at:
# ..svc.cluster.local
# Example: access "nginx-service" in "default" namespace
curl http://nginx-service.default.svc.cluster.local
# Short form (same namespace only)
curl http://nginx-service
# Environment variables (legacy approach)
# K8s injects env vars for each Service into new pods