Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 78 ยท Services and Networking

Services

Learn why Kubernetes Services exist, how selectors pick Pods, what EndpointSlices are, how port and targetPort differ, and how Services get DNS names.

Pods are disposable. Every Pod gets its own IP address, and when a Pod is replaced (after a crash, a rolling update or a node failure) its replacement gets a different one. If a front end stored the IP address of a back-end Pod, it would break within hours. Clients need an address that stays the same while the Pods behind it come and go.

A Service is that address. It gives a set of Pods one stable virtual IP and one stable DNS name, and spreads connections across whichever of those Pods are currently ready. In this lesson you will write a Service, see how it finds its Pods with a selector, learn the difference between port and targetPort, and run a Python stand-in that picks ready endpoints the way the real machinery does.

The cluster behavior in this lesson is shown with read-only manifests and commands, since no cluster runs on this site. The Python example is a stand-in for the selection and balancing logic. Who actually forwards the packets is the subject of How Services Really Work: kube-proxy.

Pods come and go

Pod IPs change A replacement Pod gets a new address.
Service IP stays One virtual IP for the lifetime of the Service.
Labels connect them The selector finds the Pods.
1 / 2

A first Service

Assume a Deployment whose Pods carry the label app: web and listen on port 8080. This Service (read-only) puts a stable address in front of them:

YAML
apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: shop
spec:
  selector:
    app: web
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 8080

Apply it and look at the result:

Terminal
kubectl apply -f service.yaml
kubectl get service web -n shop
TEXT
NAME   TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
web    ClusterIP   10.96.14.20    <none>        80/TCP    5s

The CLUSTER-IP is a virtual IP taken from the cluster's service range. No network interface has this address. It exists only as a rule on every node that says "traffic to 10.96.14.20 port 80 should be redirected to one of the real Pod addresses". Because it is virtual, ping 10.96.14.20 does not work even though connecting to port 80 does.

The default Service type, ClusterIP, is reachable only from inside the cluster. The other types are covered in NodePort, LoadBalancer and ExternalName.

port versus targetPort

Two numbers in a Service port confuse nearly everyone at first:

Field Meaning
port The port the Service listens on. Clients connect to web:80.
targetPort The port on the Pod that receives the traffic. Defaults to the same value as port.

In the example, clients use port 80 while the container listens on 8080. This lets you keep a conventional port in front while the application uses whatever it likes.

targetPort can also be a name. If the Pod template declares a named port, the Service refers to the name and keeps working even if the number changes in a later version:

YAML
# in the Pod template
ports:
  - name: http-app
    containerPort: 8080

# in the Service
ports:
  - port: 80
    targetPort: http-app

A Service may expose several ports. When it does, every port must have a unique name so that the entries can be told apart. Typical examples are an http port and a metrics port. A multi-port Service looks like this (read-only manifest):

YAML
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
    - name: http          # names are required when there is more than one port
      port: 80
      targetPort: 8080
    - name: metrics
      port: 9100
      targetPort: metrics-port
      protocol: TCP

Each port gets its own DNS SRV record (_http._tcp.web.<namespace>.svc.cluster.local) and its own pair of environment variables inside Pods created later (WEB_SERVICE_PORT_HTTP and WEB_SERVICE_PORT_METRICS, next to the plain WEB_SERVICE_PORT of the first port). All ports share the one cluster IP and the same selector, so every Pod behind the Service must serve every port. With kubectl create service clusterip web --tcp=80:8080 --tcp=9100:9100 you can generate a first version of such a manifest and then edit it.

Selectors: how a Service finds its Pods

The selector is a set of labels. Any Pod in the same namespace whose labels contain all of those key-value pairs becomes part of the Service. A selector is a promise about labels, not about Deployments: a Service neither knows nor cares what created the Pods. This is also why a typo in either the Service selector or the Pod template labels silently produces a Service with no backends.

Two consequences are worth remembering:

  • Selectors are not scoped by name or owner. A hand-made Pod with the label app: web joins the Service. That is a feature during a canary or migration, and a trap if you reuse labels carelessly. See Labels, Selectors and Annotations for the matching rules.
  • A Service only selects Pods in its own namespace.

Endpoints and EndpointSlices

A Service does not store a list of Pod IPs itself. A controller watches the Service and the Pods and writes the matching addresses into EndpointSlice objects. Each slice holds up to 100 endpoints by default, so large Services are split into several slices instead of one huge object that is rewritten on every change. The older Endpoints object served the same purpose but could not scale; it is deprecated in recent Kubernetes versions in favor of EndpointSlices.

Terminal
kubectl get endpointslices -n shop -l kubernetes.io/service-name=web
kubectl describe service web -n shop
TEXT
Name:              web
Namespace:         shop
Selector:          app=web
Type:              ClusterIP
IP:                10.96.14.20
Port:              http  80/TCP
TargetPort:        8080/TCP
Endpoints:         10.244.1.5:8080,10.244.2.7:8080

Every endpoint carries conditions. The important one is ready, which mirrors the Pod's readiness probe. A Pod that is running but not ready is kept out of the ready endpoints, so no new connections reach it. This is the main reason to write a readiness probe: it makes the Service pause traffic during startup and during hiccups instead of sending requests into a Pod that cannot answer them yet. (Pods that are shutting down are marked terminating, which allows well-behaved proxies to drain existing connections.)

The first thing to check when a Service "does not work" is its endpoints. An empty list means one of three things: the selector matches no Pods, the Pods exist but are not ready, or the Pods are in another namespace.

Services without a selector

If you omit the selector, Kubernetes creates no endpoints at all. You then create the EndpointSlice yourself and point it at anything, for example a database running outside the cluster. Clients still use the cluster-local name, and you can later move the database into the cluster by switching to a selector without changing any client.

DNS names

Every Service gets a DNS record created by the cluster's DNS add-on. The full name has this shape:

TEXT
<service>.<namespace>.svc.cluster.local

A Pod in the same namespace can simply use web. From another namespace it uses web.shop. The fully qualified form always works. How the short names get expanded is covered in DNS and Service Discovery.

Kubernetes also injects environment variables such as WEB_SERVICE_HOST and WEB_SERVICE_PORT into Pods, but only for Services that existed when the Pod started. Prefer DNS; it has no ordering problem.

Stand-in: a Service that picks ready endpoints

The real work is done by the EndpointSlice controller (which selects Pods by label and readiness) and by the node-level proxy (which spreads connections). The Python stand-in below reproduces both ideas in a few lines: it filters Pods with the selector, keeps only ready ones, translates port to targetPort, and rotates through the result. Real proxies do not necessarily rotate in strict order, so treat the round robin as a teaching simplification.

Python Select ready Pods and balance requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two lines show the two classic failure modes in miniature: an unready Pod is skipped until its probe passes, and a mistyped selector leaves the Service with an empty list.

Stand-in: Service DNS names

The second stand-in resolves the short, namespaced and qualified names of a few Services as seen from two different namespaces. It uses a plain dictionary in place of CoreDNS.

Python Which name reaches which Service?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that api fails from the payments namespace: a bare name only searches the Pod's own namespace. The db entry shows the cluster IP None, which marks a headless Service, introduced in the next lesson.

Common mistakes

  • Selector does not match the Pod labels, so the endpoint list is empty. Compare them with kubectl get pods --show-labels.
  • Wrong targetPort. The Service has endpoints but connections are refused, because the container listens on a different port.
  • No readiness probe, so traffic arrives while the application is still starting.
  • Pinging the ClusterIP. It is virtual; test with curl or nc against the Service port.
  • Using the Pod IP or the ClusterIP in configuration instead of the DNS name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A Service has port: 80 and targetPort: 8080. Which statement is correct?

    port is what the Service listens on, targetPort is the container port that receives the forwarded traffic.
  2. 2. A Service shows an empty Endpoints list. Which cause is NOT plausible?

    ClusterIP is the normal default type and has endpoints like any other. The other three are the usual reasons for no ready endpoints.
  3. 3. Why does a Service with two ports require a name on each port?

    When more than one port is defined, each needs a unique name so that references such as targetPort names and SRV records are unambiguous.
  4. 4. What does the ready condition of an endpoint reflect?

    Pods that fail their readiness probe are left out of the ready endpoints, so new connections are not sent to them.

Summary

  • A Service gives Pods a stable virtual IP, a DNS name and load balancing.
  • The selector chooses Pods by label within the same namespace; no selector means you manage the endpoints yourself.
  • EndpointSlices hold the actual Pod addresses, and only ready Pods receive traffic.
  • port is the Service port, targetPort is the container port (a number or a name).
  • Debug a Service by checking its endpoints, selector, readiness and targetPort in that order.

Next: how to reach a Service from outside the cluster in NodePort, LoadBalancer and ExternalName.