Skip to content

๐Ÿ”— Kubernetes Services

A Service in Kubernetes is an abstraction that defines a logical set of Pods and a policy by which to access them. It provides a stable virtual IP (ClusterIP) even if the actual Pod IPs change.


โœ… Why Use Services?

  • Expose applications to other pods or the outside world
  • Load balance traffic across Pod replicas
  • Decouple consumers from changing Pod IPs
  • Enable stable DNS-based communication between workloads

๐Ÿงฉ Service Types

1. ClusterIP (default)

  • Internal access only
  • Exposes service on a cluster-internal IP

2. NodePort

  • Exposes service on each Node's IP at a static port
  • Accessible outside the cluster via <NodeIP>:<NodePort>

3. LoadBalancer

  • Cloud provider provisioned external IP
  • Built on top of NodePort + external load balancer

4. ExternalName

  • Maps service to an external DNS name (e.g., mydb.example.com)

๐Ÿ› ๏ธ Create a ClusterIP Service

From Pod (imperative)

kubectl expose pod redis --port=6379 --name=redis-service --type=ClusterIP

From YAML

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 8080
  type: ClusterIP
kubectl apply -f service-definition.yaml

๐ŸŒ NodePort Service Example

apiVersion: v1
kind: Service
metadata:
  name: webapp-service
  namespace: default
spec:
  type: NodePort
  selector:
    name: simple-webapp
  ports:
    - port: 8080
      targetPort: 8080
      nodePort: 30080

Flow:

User -> NodeIP:30080 -> Service:8080 -> Pod:8080

Access Example:

curl http://<NodeIP>:30080

๐Ÿงช Inspecting Services

kubectl get services
kubectl get svc <name> -o yaml
kubectl describe svc <name>
kubectl get endpoints <svc-name>

Sample output:

NAME         ENDPOINTS                        AGE
kubernetes   172.17.0.2:6443,172.17.0.3:6443   25m

Each IP:PORT = 1 Pod endpoint.


๐Ÿง  Tips & Gotchas

  • Endpoints must match Pods with the selector
  • To specify a custom nodePort, use YAML, not kubectl expose
  • A Service with no matching Pods still exists but has no endpoints

๐ŸŒ Kubernetes DNS Access

If your Pod is in the marketing namespace and wants to reach a db-service in the same namespace:

Use:

  • Short DNS: db-service
  • Full DNS: db-service.marketing.svc.cluster.local

โœ… Summary

Service Type Access Scope Notes
ClusterIP Internal only Default
NodePort External via NodeIP Static port on every node
LoadBalancer External LB Cloud-provider only
ExternalName External DNS For services outside the cluster
  • Use kubectl expose or YAML to define Services
  • Check endpoints to verify Service โ†’ Pod linkage
  • Pair Services with labels and selectors for clean communication