Kubernetes Services Explained: ClusterIP, NodePort, LoadBalancer
Services are the abstraction that enables network access to pods. Since pods are ephemeral and their IPs change, services provide a stable endpoint. Let’s explore each service type.
Service Types Overview
| Type | Access | Use Case |
|---|---|---|
| ClusterIP | Internal only | Internal microservices |
| NodePort | External via node IP | Development/testing |
| LoadBalancer | External via LB | Production cloud apps |
| ExternalName | DNS CNAME | External services |
ClusterIP (Default)
Internal-only service accessible within the cluster:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: ClusterIP # Default, can be omitted
selector:
app: my-app
ports:
- port: 80
targetPort: 8080# Create quickly
kubectl expose deployment my-app --port=80 --target-port=8080NodePort
Exposes service on each node’s IP at a static port:
apiVersion: v1
kind: Service
metadata:
name: my-nodeport
spec:
type: NodePort
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
nodePort: 30080 # Range: 30000-32767Access via: http://<node-ip>:30080
LoadBalancer
Cloud provider provisions external load balancer:
apiVersion: v1
kind: Service
metadata:
name: my-lb
spec:
type: LoadBalancer
selector:
app: my-app
ports:
- port: 80
targetPort: 8080Service Discovery
DNS-based Discovery
# Within cluster, access service by name
curl http://my-service
curl http://my-service.default.svc.cluster.localEnvironment Variables
# Kubernetes injects service info
echo $MY_SERVICE_SERVICE_HOST
echo $MY_SERVICE_SERVICE_PORTDebugging Services
# Check service and endpoints
kubectl get svc my-service
kubectl get endpoints my-service
# Verify selector matches pods
kubectl get pods --show-labels
# Test connectivity
kubectl run tmp --image=busybox --rm -it -- wget -O- my-serviceHeadless Services
For stateful applications needing direct pod access:
apiVersion: v1
kind: Service
metadata:
name: headless
spec:
clusterIP: None # Headless
selector:
app: my-stateful-appPractice Services
Services are heavily tested in CKA exams. Practice creating and debugging services with Sailor.sh in real cluster environments.