Kubernetes Services
Kubernetes Services
Section titled โKubernetes ServicesโPods have ephemeral IP addresses. A Service provides a stable network endpoint in front of a set of pods, load balancing traffic across them.
How Services Work
Section titled โHow Services WorkโServices use label selectors to find pods. Any pod with matching labels receives traffic:
selector: app: my-app # routes to pods with this labelKubernetes maintains an Endpoints object that tracks the IPs of matching pods automatically as pods are created and destroyed.
Service Types
Section titled โService TypesโClusterIP (default)
Section titled โClusterIP (default)โAccessible only within the cluster. Used for internal service-to-service communication.
apiVersion: v1kind: Servicemetadata: name: my-app-servicespec: type: ClusterIP selector: app: my-app ports: - port: 80 # port the service listens on targetPort: 8080 # port on the pod# Access from inside the cluster using DNScurl http://my-app-service.default.svc.cluster.local# Or within the same namespace:curl http://my-app-serviceNodePort
Section titled โNodePortโExposes the service on a static port on every node. Accessible from outside the cluster at <NodeIP>:<NodePort>.
spec: type: NodePort selector: app: my-app ports: - port: 80 targetPort: 8080 nodePort: 30080 # must be 30000-32767Useful for development and testing. Not recommended for production โ prefer LoadBalancer or Ingress.
LoadBalancer
Section titled โLoadBalancerโProvisions a cloud load balancer (AWS ELB, GCP LB, Azure LB) that routes traffic to the NodePort:
spec: type: LoadBalancer selector: app: my-app ports: - port: 80 targetPort: 8080The cloud provider assigns an external IP automatically. Each service gets its own load balancer, which can be costly โ use Ingress to share one LB across multiple services.
ExternalName
Section titled โExternalNameโMaps a service name to an external DNS name. No proxying โ just DNS aliasing.
spec: type: ExternalName externalName: my.external-database.comDNS Resolution
Section titled โDNS ResolutionโKubernetes provides automatic DNS for services:
<service-name>.<namespace>.svc.cluster.localFrom the same namespace, just <service-name> works.
Multi-Port Services
Section titled โMulti-Port Servicesโports: - name: http port: 80 targetPort: 8080 - name: https port: 443 targetPort: 8443Common Commands
Section titled โCommon Commandsโkubectl get serviceskubectl describe service my-app-servicekubectl delete service my-app-service
# Check which pods the service routes tokubectl get endpoints my-app-serviceService vs Ingress
Section titled โService vs Ingressโ| Service (LoadBalancer) | Ingress | |
|---|---|---|
| Cost | One LB per service | One LB for all services |
| Routing | Port-based | Path and host-based HTTP routing |
| TLS termination | At LB level | At Ingress level |
| Use for | Non-HTTP protocols, single service | HTTP/HTTPS with multiple services |