You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Pods in Kubernetes are ephemeral and receive new IP addresses each time they are created. A Service provides a stable virtual IP address and DNS name that routes traffic to a set of pods, regardless of which specific pods are running or what their addresses are.
A Service selects pods using a label selector. kube-proxy on each node maintains iptables (or IPVS) rules that forward traffic from the Service's ClusterIP to one of the matching pod endpoints. When pods are added or removed, the endpoint list is updated automatically.
apiVersion: v1
kind: Service
metadata:
name: web-app-service
spec:
selector:
app: web-app
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: ClusterIP
ClusterIP (default) — exposes the service on an internal IP reachable only within the cluster. Use this for communication between services inside the cluster.
NodePort — opens a static port (30000–32767) on every node's IP. External clients can reach the service at NodeIP:NodePort. Simple but not recommended for production because it exposes every node.
LoadBalancer — provisions an external load balancer through the cloud provider (AWS ELB, GCP LB, etc.) and assigns it a public IP. This is the standard way to expose a service to the internet on managed Kubernetes.
ExternalName — maps the service to a DNS name outside the cluster. Useful for gradually migrating external dependencies into the cluster.
Setting clusterIP: None creates a headless service. Instead of a virtual IP, DNS returns the individual pod IPs. This is used by StatefulSets so each pod can be addressed individually (e.g., pod-0.my-service.namespace.svc.cluster.local).
# List services
kubectl get services
# Describe a service and see its endpoints
kubectl describe service web-app-service
# Port-forward a service to your local machine for testing
kubectl port-forward service/web-app-service 8080:80
# Check which pods are behind a service
kubectl get endpoints web-app-service
Every Service gets a DNS record of the form service-name.namespace.svc.cluster.local. Pods in the same namespace can use just the service name (web-app-service). This makes service-to-service communication simple and configuration-free.
A Service of type LoadBalancer creates one external load balancer per service, which can be expensive. An Ingress resource (backed by an Ingress controller like NGINX or Traefik) allows you to route multiple HTTP/HTTPS hostnames and paths through a single load balancer, reducing cost and complexity.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.