Session 4: Services, how pods find each other
A Deployment gives me multiple pods. That is good for availability.
It also creates a problem.
Pods are temporary. During a rollout, crash, reschedule, or scale event, Kubernetes destroys old pods and creates new ones. Their names change. Their IP addresses change. No application should depend on a specific pod IP.
That is what a Service solves.
A Service gives a changing group of pods one stable name and one stable virtual IP.
Think of it as the permanent front door for a temporary set of pods.
My demo Deployment might have two nginx pods today and five tomorrow. The pods can disappear and return with different addresses. But other workloads inside the cluster can always call http://demo.
The Service finds the right pods using labels.
The Deployment puts a label such as app=demo on each pod. The Service has a selector for the same label. Kubernetes continuously watches for matching, Ready pods and keeps its list of endpoints updated.
That is the important part. The Service does not point to a pod. It points to a rule.
Run this locally.
First, make sure Docker Desktop Kubernetes is running:
kubectl config use-context docker-desktop
kubectl get nodes
Create a Deployment with two pods:
kubectl create deployment demo --image=nginx --replicas=2
kubectl get pods -l app=demo
Create the Service:
kubectl expose deployment demo --port=80 --target-port=80
kubectl get service demo
kubectl get endpointslices -l kubernetes.io/service-name=demo
Now test it from inside the cluster:
kubectl run curl --rm -it --restart=Never \
--image=curlimages/curl -- curl -I http://demo
You should get an HTTP 200 OK response.
To view nginx from your own browser, run:
kubectl port-forward service/demo 8080:80
Open http://localhost:8080, then press Ctrl+C when finished.
Clean up:
kubectl delete deployment demo
kubectl delete service demo
Things to notice.
demois a stable DNS name inside the cluster.- The
EndpointSlicelists the actual pod IPs behind that name. - If a pod is deleted, Kubernetes updates the endpoints. Clients keep calling
demo. - The default Service type is
ClusterIP, which means it is available only inside the cluster.
The mental model.
Pods are replaceable workers. A Service is the stable phone number clients use to reach them.
Next: ConfigMaps and Secrets. How configuration stays out of container images.