Skip to main content

Services

Services provide stable network endpoints for accessing Pods. While Pods are ephemeral and can be created/destroyed dynamically, Services ensure your application remains accessible through a consistent endpoint.

Basic Service

A ClusterIP Service (default type) provides internal cluster access:
apiVersion: v1
kind: Service
metadata:
  name: nnappone-service
spec:
  selector:
    app: nnappone
  ports:
    - protocol: TCP
      port: 8080        # Service port
      targetPort: 80    # Container port
The Service routes traffic to Pods with labels matching the selector. In this case, any Pod with app: nnappone will receive traffic.

Service Types

Default type. Exposes the Service on a cluster-internal IP.
spec:
  type: ClusterIP  # Can be omitted (default)
  ports:
  - port: 8080
    targetPort: 80
Use case: Internal communication between services within the cluster.

Complete Service Example with Deployment

apiVersion: v1
kind: Service
metadata:
  name: nnweb-svc
  namespace: learning
  labels:
    app: hello-nn
spec:
  type: NodePort
  ports:
  - port: 80
    nodePort: 30003
    protocol: TCP
  selector:
    app: hello-nn
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-deploy
  namespace: learning
spec:
  replicas: 2
  selector:
    matchLabels:
      app: hello-nn
  minReadySeconds: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: hello-nn
    spec:
      containers:
      - name: webserver-pod
        image: lovelearnlinux/webserver:v1
        ports:
        - containerPort: 80

Service Discovery

# View services
kubectl get svc --namespace=learning

# Describe service (shows endpoints)
kubectl describe service nnweb-svc --namespace=learning

# View endpoints (Pod IPs backing the service)
kubectl get endpoints nnweb-svc --namespace=learning
Endpoints are automatically created and updated as Pods matching the selector are created or destroyed.

Health Checks with Probes

Kubernetes uses probes to determine Pod health and readiness.

Liveness Probe

Determines if a container is running. If the liveness probe fails, the container is restarted.
apiVersion: v1
kind: Pod
metadata:
  name: nnwebserver
spec:
  containers:
    - name: nnwebserver
      image: lovelearnlinux/webserver:v1
      livenessProbe:
        exec:
          command:
          - cat 
          - /var/www/html/index.html
        initialDelaySeconds: 10  # Wait before first probe
        timeoutSeconds: 3        # Probe timeout
        periodSeconds: 20        # Check every 20 seconds
        failureThreshold: 3      # Restart after 3 failures
      resources:
        requests:
          cpu: "500m"
          memory: "128Mi"
        limits:
          cpu: "1000m"
          memory: "256Mi"
      ports:
        - containerPort: 80
          name: http
          protocol: TCP

Probe Types

livenessProbe:
  exec:
    command:
    - cat 
    - /tmp/health.txt
  initialDelaySeconds: 5
  periodSeconds: 5
  failureThreshold: 3

Readiness Probe

Determines if a container is ready to accept traffic. Failed readiness probes remove the Pod from Service endpoints.
readinessProbe:
  httpGet:
    path: /ready
    port: 8080
  initialDelaySeconds: 5
  periodSeconds: 5
Liveness Probe:
  • Detects when a container is stuck or deadlocked
  • Failure triggers container restart
  • Use for: Detecting application hangs
Readiness Probe:
  • Detects when a container is ready to serve traffic
  • Failure removes Pod from Service load balancing
  • Use for: Warming up caches, waiting for dependencies
Startup Probe (Kubernetes 1.16+):
  • Gives containers time to start before liveness checks begin
  • Useful for slow-starting applications

Advanced Health Check Example

apiVersion: v1
kind: Pod
metadata:
  name: nnappone
  namespace: learning
  labels:
   app: nnappone
spec:
  containers:
    - name: networknuts-app
      image: lovelearnlinux/webserver:v1
      args:
        - /bin/sh
        - -c
        - touch /tmp/health.txt; sleep 30; rm -rf /tmp/health.txt; sleep 35
      livenessProbe:
        exec:
          command:
            - cat 
            - /tmp/health.txt
        initialDelaySeconds: 5
        periodSeconds: 5
        failureThreshold: 3
      resources:
        requests:
          cpu: "400m"
          memory: "128Mi"
        limits:
          cpu: "500m"
          memory: "256Mi"
      ports:
        - containerPort: 80
          name: http
          protocol: TCP
This example creates a health file, waits 30 seconds, then removes it. The liveness probe will fail after the file is removed, causing Kubernetes to restart the container.

Container Lifecycle Hooks

Lifecycle hooks allow you to run code at specific points in a container’s lifecycle.
apiVersion: v1
kind: Pod
metadata:
  name: nnappone
  namespace: learning
  labels:
   app: nnappone
spec:
  containers:
    - name: networknuts-app
      image: lovelearnlinux/webserver:v1
      lifecycle:
        postStart:
          exec:
            command: ["/bin/sh", "-c", "useradd networknuts -p redhat"]
        preStop:
          exec:
            command: ["/bin/sh","-c","rm -rf /home/networknuts; userdel networknuts"]
Executed immediately after a container is created.Use cases:
  • Initialize application state
  • Create required directories or files
  • Register with external services
If postStart fails, the container is terminated and restarted.

Service Management Commands

# Create service
kubectl create -f service-for-pod.yml

# Get services
kubectl get svc
kubectl get svc --namespace=learning

# Describe service
kubectl describe service nnappone-service

# Test service from within cluster
kubectl run -it --rm debug --image=busybox --restart=Never -- wget -O- http://nnappone-service:8080

# Delete service
kubectl delete service nnappone-service

Best Practices

  • Always use readiness probes for Pods behind Services
  • Set appropriate initialDelaySeconds to avoid false failures during startup
  • Use liveness probes conservatively to avoid restart loops
  • Set failureThreshold high enough to tolerate transient failures
  • Use preStop hooks for graceful shutdowns
  • Monitor Service endpoints to ensure Pods are being selected correctly
  • Use headless Services (clusterIP: None) when you need direct Pod IPs
  • Label Services and Pods consistently for easy discovery

Build docs developers (and LLMs) love