Kubernetes Tutorial · Networking · Lesson 13 of 26
Services
Give a changing set of pods one stable name and IP: ClusterIP, NodePort, LoadBalancer and headless Services.
Why Services
Pods come and go with new IPs. A Service gives them a stable virtual IP and DNS name and load-balances across the pods matching its selector that are ready.
| Type | Reachable from |
|---|---|
ClusterIP (default) |
Inside the cluster |
NodePort |
Each node's IP on a high port |
LoadBalancer |
A cloud load balancer in front of the nodes |
Headless (clusterIP: None) |
DNS returns pod IPs directly (StatefulSets) |
apiVersion: v1
kind: Service
metadata: {name: web}
spec:
selector: {app: web}
ports: [{port: 80, targetPort: 8080}]
kubectl create namespace demo-svc > /dev/null
trap 'kubectl delete namespace demo-svc --wait=false > /dev/null' EXIT
kubectl -n demo-svc create deployment echo --image=busybox:1.37 --replicas=2 -- sh -c 'echo "served by pod $(hostname)" > /tmp/index.html; httpd -f -p 8080 -h /tmp' > /dev/null
kubectl -n demo-svc expose deployment echo --port=80 --target-port=8080 > /dev/null
kubectl -n demo-svc rollout status deployment/echo --timeout=120s > /dev/null
echo "endpoints behind the Service: $(kubectl -n demo-svc get endpointslices -l kubernetes.io/service-name=echo -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{" "}{end}' | wc -w)"
kubectl -n demo-svc run client --rm -i --restart=Never --image=busybox:1.37 -- wget -qO- http://echo 2>/dev/null | head -1 | sed -E 's/echo-[a-z0-9]+-[a-z0-9]+/echo-<hash>/'
echo "type: $(kubectl -n demo-svc get svc echo -o jsonpath='{.spec.type}'), port $(kubectl -n demo-svc get svc echo -o jsonpath='{.spec.ports[0].port}') -> $(kubectl -n demo-svc get svc echo -o jsonpath='{.spec.ports[0].targetPort}')"
Output
endpoints behind the Service: 2 served by pod echo-<hash> type: ClusterIP, port 80 -> 8080
Run this on your computer — see “Get Started” for setup.
See Service.
Test yourself
A pod is running but not ready. Does its Service send it traffic?
Yes, alwaysNo: only ready pods are added to the Service's endpointsOnly on NodePort ServicesOnly if it has a label
Show answer
Answer: No: only ready pods are added to the Service's endpoints
Readiness controls Service membership.