Skip to content
LF Cert Trainer

Lesson 20 · Section 2: Core Concepts

Lesson 20: ClusterIP Services: a private address inside the cluster

How the default Service type gives your internal tiers one stable virtual IP and name, where that IP comes from, how the kernel turns it into a Pod address, and the commands that make it quick in the exam. · 20 min read · 4 min video

1/10ClusterIP Services
0:00 / 3:50

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why ClusterIP exists

Most traffic in a cluster never leaves it. A frontend calls an API, the API calls a database, a worker calls a queue. Each of those tiers is a set of Pods, and Pods are replaced constantly: every rollout, every node failure and every eviction brings a new Pod with a new IP address. A tier with three replicas even has three addresses at the same moment.

Callers cannot chase that. They need one address for "the API", and they need somebody else to decide which replica gets each connection. At the same time, a database or an internal API should not be reachable from the internet just because other Pods must reach it.

ClusterIP is the Service type made for this. It is also the default: a Service with no type is a ClusterIP Service, and every other type you will meet (NodePort, LoadBalancer) is a ClusterIP Service with something added on top.

What a ClusterIP Service is

ClusterIP Services between the tiers of an applicationClusterapi:80db:5432blockedOutside clientno route infrontend Podcalls api:80Service api10.96.14.20:80api Pod10.244.1.7:8080api Pod10.244.2.4:8080Service db10.96.201.8:5432db Pod10.244.2.9:5432
ClusterIP Services between the tiers of an application. Each tier calls the next one through a ClusterIP Service. Nothing outside the cluster has a route to those addresses.

Parts:

  • Outside client (no route in)
  • frontend Pod (calls api:80), in Cluster
  • Service api (10.96.14.20:80), in Cluster
  • api Pod (10.244.1.7:8080), in Cluster
  • api Pod (10.244.2.4:8080), in Cluster
  • Service db (10.96.201.8:5432), in Cluster
  • db Pod (10.244.2.9:5432), in Cluster

Connections:

  • frontend Pod to Service api: api:80
  • Service api to api Pod
  • Service api to api Pod
  • api Pod to Service db: db:5432
  • api Pod to Service db
  • Service db to db Pod
  • Outside client to Service api: blocked

The Service object itself is small. It says which Pods (the selector), which ports, and it carries the address Kubernetes gave it:

apiVersion: v1
kind: Service
metadata:
  name: api
  namespace: shop
spec:
  type: ClusterIP        # optional: this is the default
  selector:
    app: api             # Pods in namespace shop with this label are the backends
  ports:
    - name: http
      port: 80           # what callers use
      targetPort: 8080   # where the container listens

After you create it, spec.clusterIP is filled in for you. What you get:

You getExampleNotes
A virtual IP10.96.14.20Taken from the cluster's service range. Stays the same until the Service is deleted
A DNS nameapi.shop.svc.cluster.localAlso api from namespace shop, and api.shop from any namespace
Load spreadingone of the ready Pods per connectionOnly Pods that pass their readiness probe are used
No way in from outsideThe address is not routed outside the cluster, and no port is opened on the nodes

The fields you will actually set or read:

FieldMeaningDefault
spec.typeThe Service typeClusterIP
spec.clusterIPThe virtual IP. Leave it out to get a free one, set an address to choose it, or set None for a headless Serviceallocated
spec.selectorLabels the backend Pods must carry. Only Pods in the Service's own namespace countnone
spec.ports[].portThe port callers connect to on the Servicerequired
spec.ports[].targetPortThe container port: a number, or the name of a container portsame as port
spec.ports[].protocolTCP, UDP or SCTPTCP
spec.ports[].nameRequired as soon as the Service has more than one portnone

How it works

Where the address comes from

What happens when you create a ClusterIP ServicecreatewatchwatchwatchwriteswritesservesYoukubectl exposeService range10.96.0.0/12API serverpicks a free IPEndpointSlice ctrlfinds ready Podskube-proxyon every nodeCoreDNSapi.shop.svcEndpointSlicePod IPs and portsKernel rulesiptables / nftablesDNS recordapi → 10.96.14.20
What happens when you create a ClusterIP Service. The API server picks the address. Three watchers then react on their own: one lists the ready Pods, one writes kernel rules on every node, one publishes the DNS name.

Parts:

  • You (kubectl expose)
  • Service range (10.96.0.0/12)
  • API server (picks a free IP)
  • EndpointSlice ctrl (finds ready Pods)
  • kube-proxy (on every node)
  • CoreDNS (api.shop.svc)
  • EndpointSlice (Pod IPs and ports)
  • Kernel rules (iptables / nftables)
  • DNS record (api → 10.96.14.20)

Connections:

  • You to API server: create
  • Service range to API server
  • API server to EndpointSlice ctrl: watch
  • API server to kube-proxy: watch
  • API server to CoreDNS: watch
  • EndpointSlice ctrl to EndpointSlice: writes
  • kube-proxy to Kernel rules: writes
  • CoreDNS to DNS record: serves

The API server owns the service range. It is set with the --service-cluster-ip-range flag, and on a kubeadm cluster you can read it from the static Pod manifest on the control plane node. When a Service is created without a clusterIP, the API server picks a free address from that range and stores it in the object. Nothing on the network is configured at that moment: the address is only a number in etcd.

Three components watch the API server and each do one job:

  1. The EndpointSlice controller (inside kube-controller-manager) finds the Pods that match the selector and writes their IPs, ports and readiness into EndpointSlice objects.
  2. kube-proxy, on every node, combines the Service with its EndpointSlices and writes kernel rules: "a new connection to 10.96.14.20:80 goes to one of these Pod addresses".
  3. CoreDNS starts answering api.shop.svc.cluster.local with 10.96.14.20.

Because these are independent watchers, a Service can exist and have an IP while being useless: with no matching ready Pod, the EndpointSlice is empty and the kernel rule rejects the connection.

Under the hood · Two addresses you will find in every cluster
  • The first address of the service range belongs to the Service kubernetes in namespace default (10.96.0.1 on kubeadm). It points at the API server, and it is how Pods reach the API.
  • kubeadm gives cluster DNS the tenth address (10.96.0.10, Service kube-dns in kube-system). The kubelet writes that address into every Pod's /etc/resolv.conf, which is why DNS needs a fixed, well-known ClusterIP.

To make fixed addresses like that safe, the range is split into two bands. Automatic allocation uses the upper band first; the lower band (the first 256 addresses in a large range such as 10.96.0.0/12, fewer in small ranges, never fewer than 16) is left for addresses you choose yourself. If you must pin a ClusterIP, pick it from the low end.

On current clusters each allocated address is also visible as an object: kubectl get ipaddresses lists them, and kubectl get servicecidr shows the range without logging in to the control plane.

What happens to a packet

One connection to a ClusterIPNode ANode BpacketDNATnext timerecordsfrontend Podto 10.96.14.20:80Kernel rulespick one backendConntrack tableremembers the choiceapi Pod10.244.2.4:8080api Pod10.244.2.6:8080
One connection to a ClusterIP. The translation happens on the client's own node, before the packet leaves it. The connection tracking table remembers the choice so every later packet, and every reply, follows the same Pod.

Parts:

  • frontend Pod (to 10.96.14.20:80), in Node A
  • Kernel rules (pick one backend), in Node A
  • Conntrack table (remembers the choice), in Node A
  • api Pod (10.244.2.4:8080), in Node B
  • api Pod (10.244.2.6:8080), in Node B

Connections:

  • frontend Pod to Kernel rules: packet
  • Kernel rules to api Pod: DNAT
  • Kernel rules to api Pod: next time
  • Kernel rules and Conntrack table: records

The ClusterIP is virtual. No network interface owns it and no process listens on it. It only means something to the kernel rules that kube-proxy wrote, and those rules exist on every node.

  1. The frontend Pod opens a TCP connection to 10.96.14.20:80.
  2. The packet enters the kernel of the frontend's own node. A rule matches the destination address and port.
  3. The rule picks one ready backend and rewrites the destination (DNAT) to that Pod, for example 10.244.2.4:8080.
  4. The choice is saved in the kernel's connection tracking table (conntrack). Every later packet of this connection is rewritten the same way, and replies are rewritten back, so the client only ever sees the ClusterIP.
  5. From here it is ordinary Pod to Pod traffic, carried by the CNI plugin, to whatever node the backend runs on.

Three consequences follow from this design, and each of them shows up in real troubleshooting:

  • Load is spread per connection, not per request. A client that keeps one connection open (HTTP keep-alive, gRPC, a database pool) stays on the same Pod. Scaling a Deployment up does not move existing connections.
  • kube-proxy is not in the data path. If kube-proxy stops, existing rules keep working. What breaks is updates: new Services do not work on that node, and removed Pods still receive connections.
  • It works from nodes too. A node has the same rules as its Pods, so curl 10.96.14.20 works from a node's shell. The name does not, because a node's resolver does not use cluster DNS.
Under the hood · Seeing the rules with your own eyes

In iptables mode (the default), each Service gets a chain and each backend gets a chain. On a node:

sudo iptables -t nat -L KUBE-SERVICES -n | grep shop/api
sudo iptables -t nat -L KUBE-SVC-XXXXXXXXXXXXXXXX -n     # the chain name from the line above

The Service chain holds one rule per backend with a random probability (1/2 for the first of two, then the rest), each jumping to a KUBE-SEP-... chain that does the DNAT to one Pod IP. A Service with no ready backends gets a REJECT rule instead, which is why a client sees "connection refused" immediately rather than a timeout.

kube-proxy can also run in nftables or IPVS mode. The rules look different, the behaviour described in this lesson is the same. Check the mode with kubectl -n kube-system get cm kube-proxy -o yaml | grep mode (empty means the default).

How Pods find the Service

DNS is the way to do it. CoreDNS creates an A record for every Service, and each Pod's /etc/resolv.conf has search domains for its own namespace, so the short name works:

Called fromNames that resolve
A Pod in shopapi, api.shop, api.shop.svc, api.shop.svc.cluster.local
A Pod in another namespaceapi.shop, api.shop.svc, api.shop.svc.cluster.local
A node's shellnone (use the IP)

There is an older, second mechanism: environment variables. When a container starts, the kubelet injects API_SERVICE_HOST and API_SERVICE_PORT for every Service in the Pod's namespace. They are a snapshot: a Pod that started before the Service existed does not have them. Prefer DNS, and know the variables exist because you will see them in kubectl exec ... -- env.

Variations of ClusterIP

All of these are still type: ClusterIP. One field changes the behaviour.

SettingWhat changesUse it when
clusterIP: 10.96.0.50You choose the address. It must be free and inside the service rangeSomething is configured with a fixed IP, such as cluster DNS
clusterIP: NoneHeadless: no virtual IP and no kube-proxy rules. DNS returns the ready Pod IPs themselvesStatefulSets, or clients that do their own load balancing
No selectorKubernetes creates no EndpointSlice. You write one yourselfPointing a cluster name at something outside the cluster, such as an external database
sessionAffinity: ClientIPConnections from one client IP go to the same Pod (for three hours by default)The app keeps session state in memory
internalTrafficPolicy: LocalA connection only goes to backends on the caller's own nodeNode-local agents, such as a log collector per node

Using it

Example · Expose a Deployment inside the cluster and prove it works

The Deployment api in namespace shop runs two Pods labelled app: api that listen on port 8080. Other Pods should reach it as api on port 80.

kubectl -n shop expose deployment api --port=80 --target-port=8080
kubectl -n shop get svc api -o wide          # TYPE ClusterIP, a CLUSTER-IP, and the SELECTOR
kubectl -n shop describe svc api             # Endpoints: two Pod IPs with port 8080
kubectl -n shop run tmp --rm -it --restart=Never --image=busybox:1.37 -- wget -qO- http://api

kubectl expose leaves --type at ClusterIP and copies the Deployment's selector into the Service, so the two things that usually go wrong are right by construction. EXTERNAL-IP shows <none>: that is correct for this type.

Example · Write the manifest: two ports and a named target port

The Pods also serve metrics on 9090. A Service with more than one port must name each of them, and targetPort can refer to the name of a container port instead of its number. Then the Pod template can change the number later without touching the Service.

# In the Deployment's Pod template
ports:
  - name: http
    containerPort: 8080
  - name: metrics
    containerPort: 9090
apiVersion: v1
kind: Service
metadata:
  name: api
  namespace: shop
spec:
  selector:
    app: api
  ports:
    - name: http
      port: 80
      targetPort: http
    - name: metrics
      port: 9090
      targetPort: metrics

kubectl -n shop describe svc api now shows two Endpoints lines, one per port.

Example · Give a Service a fixed ClusterIP

A task asks for the Service cache in namespace shop at the address 10.96.0.50, in front of Pods labelled app: cache, port 6379. First check that the address is inside the range and free, then set it in the manifest (kubectl expose has a --cluster-ip flag for this too).

# On the control plane node of a kubeadm cluster
sudo grep service-cluster-ip-range /etc/kubernetes/manifests/kube-apiserver.yaml
kubectl get svc -A | grep -w 10.96.0.50      # no output: the address is free
apiVersion: v1
kind: Service
metadata:
  name: cache
  namespace: shop
spec:
  clusterIP: 10.96.0.50
  selector:
    app: cache
  ports:
    - port: 6379

An address outside the range, or one that is already taken, is rejected when you apply the manifest, and the error message tells you which of the two it was.

Example · A Service is silent: find out why in three commands

wget http://api from another Pod in shop fails. Work from the Service inward:

kubectl -n shop describe svc api             # 1. read Selector, TargetPort and Endpoints
kubectl -n shop get pods -l app=api -o wide  # 2. do Pods match the selector, and are they READY?
kubectl -n shop get pod <pod> -o jsonpath='{.spec.containers[*].ports}'   # 3. which port does the app use?
What you seeCauseFix
Endpoints: <none> and step 2 lists no PodsThe selector matches nothingFix spec.selector or the Pod labels
Endpoints: <none> and Pods show 0/1 READYPods fail their readiness probeFix the Pod, not the Service
Endpoints listed, connection refusedtargetPort is not the port the app listens onFix targetPort
"bad address" or "could not resolve"DNS: wrong name, or calling from another namespaceUse api.shop

Tricks

Common mistakes

  • Expecting access from outside. A ClusterIP has no route from your laptop or from another network. If a task says "reachable from outside the cluster", you need NodePort, LoadBalancer, an Ingress or a Gateway.
  • Testing with ping. Rules exist only for the Service's ports, so ICMP to a ClusterIP usually gets no reply even when the Service is healthy. Test with the real protocol: wget, curl or nc -zv api 80.
  • Swapping port and targetPort. Callers use port; the container listens on targetPort. If you leave targetPort out it equals port, which is wrong whenever the two differ.
  • A selector that matches nothing. app: Api and app: api are different labels, and a Service only selects Pods in its own namespace. The Service is created without complaint and simply has no endpoints.
  • Trying to edit the address. spec.clusterIP is immutable. Delete and recreate the Service.
  • Short names across namespaces. api only resolves inside namespace shop. From anywhere else use api.shop.
  • Trusting environment variables. API_SERVICE_HOST is missing in Pods that started before the Service was created. Use the DNS name.

Recap

  • ClusterIP is the default Service type: a stable virtual IP and DNS name, reachable only from inside the cluster.
  • The API server allocates the address from the service range; it never changes and cannot be edited.
  • kube-proxy writes rules on every node; the kernel on the caller's node sends each connection to a ready Pod.
  • clusterIP: None makes a headless Service; a fixed clusterIP must be free and inside the range.
  • In the exam: kubectl expose, then kubectl describe svc and read the endpoints before anything else.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

3 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Two ClusterIP Services in the payments namespace answer nobody. Each has a different mistake.

    Fix · Level 2 · standard · target 15 min

  • Get answers out of two pods that listen only on their own loopback address, one of them built from an image without a shell, with kubectl debug, port-forward and exec.

    Investigate · Level 2 · standard · target 20 min

  • Section capstone. Take over a half-finished namespace: get its Deployment running under a Pod limit, repair its Service, open it on a node port, add a Pod that calls another namespace, and write it all down as a manifest.

    Fix · Level 3 · challenge · target 30 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.