## Intro

Kubernetes Services are the stable entry point to your applications. A misconfigured Service can silently drop traffic, route to the wrong pods, or leave your application unreachable. This article walks through common Service configuration mistakes with practical examples, shows how to spot them with kubectl commands, and provides fixes and validation steps.

You will learn:

- How Services select pods and why selector mismatches break routing.
- Common port, protocol, and targetPort mistakes.
- How to diagnose missing endpoints and headless service pitfalls.
- The role of session affinity and external traffic policies.
- Safe verification and rollback practices.

Each section includes realistic YAML snippets, expected output, and commands you can run in your own cluster to validate behavior. Whether you are new to Kubernetes or an experienced operator, these examples will help you troubleshoot and prevent costly misconfigurations.

## Version and Environment Inventory

Before changing anything, confirm your cluster version and inspect the current service and endpoints. This establishes a baseline and avoids compounding issues.

Check the client and server versions:

```bash
kubectl version --short
```

Expected output:

```
Client Version: v1.27.3
Server Version: v1.27.3
```

List existing services in your namespace:

```bash
kubectl get services -n my-app
```

Example output:

```
NAME        TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
my-service  ClusterIP   10.96.100.100   <none>        80/TCP    2d
```

Describe the service to see its selectors, ports, and events:

```bash
kubectl describe service my-service -n my-app
```

Check endpoints to confirm pods are matched:

```bash
kubectl get endpointslices -l kubernetes.io/service-name=my-service -n my-app
```

Expected output when healthy:

```
NAME               ADDRESSTYPE   PORTS   ENDPOINTS       AGE
my-service-abcde   IPv4          8080    10.244.1.5      2d
```

If endpoints are empty, the service is not selecting any pods. This is a common mistake we will delve into next.

Record these observations and timestamps before any changes. This makes rollback easier and gives you a clear picture of what worked before.

## Safe Configuration Path

A systematic approach prevents mistakes. Follow these steps when configuring a Service:

1. **Define the service type**: ClusterIP (default), NodePort, LoadBalancer, or ExternalName. Choose based on access needs.
2. **Specify selectors**: Match labels exactly with your pods. A typo or missing label leads to no endpoints.
3. **Map ports**: Set `port` (service port), `targetPort` (container port), and optionally `nodePort` (for NodePort services).
4. **Set protocol**: TCP (default), UDP, or SCTP. Mismatched protocols cause traffic failures.
5. **Apply and verify**: Use `kubectl apply` and then check endpoints and connectivity.

Example Service manifest:

```yaml
apiVersion: v1
kind: Service
metadata:
  name: web-service
  namespace: my-app
spec:
  selector:
    app: web
    tier: frontend
  ports:
  - name: http
    port: 80
    targetPort: 8080
    protocol: TCP
```

Apply the manifest:

```bash
kubectl apply -f web-service.yaml
```

Then verify that endpoints are populated:

```bash
kubectl get endpointslices -l kubernetes.io/service-name=web-service -n my-app
```

If no endpoints appear, check your pod labels:

```bash
kubectl get pods --show-labels -n my-app
```

## Verification and Diagnostics

Once a service is applied, verify it routes traffic correctly. Use these commands to diagnose common issues.

### Check Endpoints

```bash
kubectl get endpointslices -l kubernetes.io/service-name=my-service -n my-app
```

If empty, there is a selector mismatch or no ready pods. Inspect pod labels and readiness:

```bash
kubectl get pods -n my-app -o wide
```

Look for pods with the exact labels specified in `spec.selector`. Also confirm pods are `Running` and `Ready`.

### Test Connectivity from Another Pod

Create a temporary pod inside the cluster:

```bash
kubectl run -it --rm debug --image=busybox --restart=Never -n my-app -- sh
```

Then use `wget` or `nc` to hit the service:

```bash
wget -qO- http://my-service
```

If the service is on a different namespace, use the FQDN:

```bash
wget -qO- http://my-service.my-app.svc.cluster.local
```

### Examine Service Events

```bash
kubectl describe service my-service -n my-app
```

Events may show warnings about failed endpoints or firewall rules for LoadBalancer services.

### Port Forward as a Quick Test

If the service is not accessible externally, use port-forward to a pod directly:

```bash
kubectl port-forward pod/my-pod 8080:8080 -n my-app
```

Then test locally with `curl localhost:8080`. This bypasses the service and confirms pod health.

## Failure Modes and Recovery

Here are the most common mistakes with Kubernetes Services and how to recover from them.

### Selector Mismatch

**Mistake**: Service selector does not match any pod labels.

**Example** Service:

```yaml
selector:
  app: web
  tier: frontend
```

Pods have labels:

```yaml
labels:
  app: web
  tier: backend   # <-- mismatch
```

**Symptom**: Endpoints are empty. Service routes nowhere.

**Recovery**: Correct the selector or pod labels to match. Verify with `kubectl get endpoints`.

### Port and targetPort Confusion

**Mistake**: Setting `port` and `targetPort` incorrectly.

- `port`: The port the service listens on and other applications connect to.
- `targetPort`: The container port where the application actually listens.

If your application listens on container port 8080 but `targetPort` is set to 80, the service tries to send traffic to port 80 on the pod, which is not open. Result: connection refused.

**Example** incorrect:

```yaml
ports:
- port: 80
  targetPort: 80
```

Assuming container listens on 8080, fix:

```yaml
ports:
- port: 80
  targetPort: 8080
```

Verify from a debug pod:

```bash
curl http://my-service:80
```

### Protocol Mismatch

**Mistake**: Declaring `protocol: UDP` for a TCP application or vice versa.

**Example**: An Nginx deployment (TCP) gets a Service with `protocol: UDP`. Traffic fails silently.

**Recovery**: Set the correct protocol. Check the Service definition and application logs. Use `netstat` or `ss` inside the pod to see listening protocols.

### Headless Service Misuse

A headless service (clusterIP: None) is used for StatefulSets or when you need direct pod DNS without load balancing. If you expect load balancing but set clusterIP to None, you get all pod IPs returned and no load balancing.

**Example**:

```yaml
spec:
  clusterIP: None
  selector:
    app: myapp
```

DNS returns multiple A records. Some clients may not handle this well.

**Recovery**: Use a regular ClusterIP service if you need simple load balancing. Only use headless when you specifically need pod DNS or client-side load balancing.

### External Traffic Policy Confusion

For NodePort and LoadBalancer services, the default `externalTrafficPolicy: Cluster` causes traffic to be load balanced across all pods, sometimes routing through extra nodes. Setting `externalTrafficPolicy: Local` preserves client IP but may drop traffic on nodes without local pods.

**Symptom**: Inconsistent source IPs or long latencies.

**Recovery**: Decide based on requirements. For client source IP preservation, set `local`; otherwise, `cluster` is fine. Document the choice.

### Session Affinity Misconfiguration

Session affinity (sticky sessions) ensures a client always hits the same pod. If you need sticky sessions but don't set `sessionAffinity: ClientIP`, users may lose session state.

**Example**:

```yaml
spec:
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10800
```

If your application is stateless, skip this. If stateful, set it and test.

## Operations Checklist

Use this checklist when configuring or troubleshooting Services:

- [ ] Verify cluster version and connectivity (`kubectl version`).
- [ ] List existing services and endpoints before changes.
- [ ] Confirm service type (ClusterIP, NodePort, LoadBalancer) suits the access pattern.
- [ ] Match selectors to pod labels exactly. Use `kubectl get pods --show-labels`.
- [ ] Set `port` to the service port and `targetPort` to the container port.
- [ ] Choose the correct protocol (TCP/UDP/SCTP).
- [ ] For LoadBalancer services, check external IP allocation and cloud provider settings.
- [ ] Test connectivity from another pod inside the cluster.
- [ ] Verify endpoints are populated: `kubectl get endpoints <service>`.
- [ ] Document the service's purpose and dependencies.
- [ ] Have a rollback plan: save the previous manifest before applying changes.

## Common Pitfalls and How to Avoid Them

Here are additional pitfalls that can bite you:

1. **Using wrong namespace in commands**: Always specify `-n <namespace>` or set your context.
2. **Not updating Services when pod labels change**: If you change a deployment's pod template labels, update the service selector accordingly.
3. **Assuming a LoadBalancer is instantly available**: Cloud providers take minutes to provision. Poll the service status.
4. **Ignoring readiness probes**: If pods are not ready, they are removed from endpoints. Ensure readiness probes are correctly configured.
5. **Forgetting that Services are not firewalls**: Network policies control traffic. Services only provide a stable endpoint. Use NetworkPolicy for security.
6. **Overcomplicating with multiple ports**: Name ports and keep mappings clear.
7. **Not cleaning up unused services**: They can consume resources and cause confusion.

## Conclusion

Kubernetes Services are straightforward but hiding pitfalls. By following safe configuration practices, verifying with kubectl, and understanding common mistakes, you can avoid most outages. Always start with observation, change one thing at a time, and validate before considering the job done.

Next time you deploy a Service, run through the Operations Checklist and test connectivity from inside the cluster. If you encounter issues, use the diagnostic commands shown here to pinpoint the root cause quickly. Stay curious and keep your manifests version-controlled.